-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprojected_classification.py
More file actions
2138 lines (2005 loc) · 97.1 KB
/
projected_classification.py
File metadata and controls
2138 lines (2005 loc) · 97.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding=UTF-8
import argparse
import os
import sys
import psutil
from typing import Callable, Dict, Iterable, Optional, List
import torch
import torch.cuda.amp as amp
import torch.nn as nn
import torch.nn.functional as F
from pyutils.config import configs
from pyutils.general import AverageMeter
from pyutils.general import logger as lg
from pyutils.torch_train import (
BestKModelSaver,
count_parameters,
get_learning_rate,
load_model,
set_torch_deterministic,
)
from pyutils.typing import Criterion, DataLoader, Optimizer, Scheduler
import time
from core import builder
from core.datasets.mixup import MixupAll
from core.utils import (
get_parameter_group,
register_hidden_hooks,
probe_near2far_matrix,
CosSimLoss,
reset_optimizer_and_scheduler,
get_mid_weight,
)
from core.models.patch_metalens import PatchMetalens
import csv
from thirdparty.MAPS_old.core.utils import SharpnessScheduler
from thirdparty.MAPS_old.core.fdfd.pardiso_solver import pardisoSolver
from pyutils.general import ensure_dir
from matplotlib import pyplot as plt
import h5py
import copy
import numpy as np
import wandb
import datetime
import psutil
import torch
def overfit_single_batch(
model: nn.Module,
train_loader: DataLoader,
optimizer: Optimizer,
criterion: Callable,
device: torch.device = torch.device("cuda:0"),
max_iters: int = 100,
aux_criterions: Dict = {},
grad_scaler: Optional[Callable] = None,
teacher: Optional[nn.Module] = None,
):
model.train()
data_iter = iter(train_loader)
data, target = next(data_iter) # one batch only!
data, target = data.to(device), target.to(device)
for i in range(max_iters):
with amp.autocast(enabled=grad_scaler._enabled):
output = model(data)
if isinstance(output, tuple):
output = output[0]
class_loss = criterion(output, target)
loss = class_loss
for name, config in aux_criterions.items():
aux_criterion, weight = config
if name == "kd" and teacher is not None:
with torch.no_grad():
teacher_scores = teacher(data)
aux_loss = weight * aux_criterion(output, teacher_scores, target)
loss += aux_loss
optimizer.zero_grad()
grad_scaler.scale(loss).backward()
grad_scaler.step(optimizer)
grad_scaler.update()
pred = output.argmax(dim=1)
acc = (pred == target).float().mean().item()
print(f"[Iter {i:3d}] Loss: {loss.item():.4f} | Acc: {acc*100:.2f}%", flush=True)
if acc == 1.0:
print(f"✅ Model successfully overfit the batch at iteration {i}!")
break
def update_admm_dual_variable(
model: torch.nn.Module,
stitched_response: List[torch.Tensor],
admm_vars: Dict,
) -> None:
"""
Updates the ADMM dual variable u: u <- u + x - z
Args:
model: the DONN model with trained metasurface layers
stitched_response: List of projected implementable transfer matrices (z)
admm_vars: ADMM variables (z, u, rho)
path_depth: number of metasurface layers
"""
for i in range(configs.model.conv_cfg.path_depth):
# x is the current (non-implementable) transfer matrix from DONN
x = model.state_dict()[f"features.conv1.conv._conv_pos.metalens.{i}_17.W_buffer"]
admm_vars['z_admm'][i] = stitched_response[i].detach()
admm_vars['u_admm'][i] = admm_vars['u_admm'][i] + x - admm_vars['z_admm'][i]
def transfer_weights(src_model, tgt_model):
"""
Transfers weights from src_model to tgt_model, skipping layers with mismatched sizes.
Parameters:
- src_model (torch.nn.Module): The source model providing the weights.
- tgt_model (torch.nn.Module): The target model receiving the weights.
Returns:
- loaded_keys (list): Successfully loaded keys.
- skipped_keys (list): Keys skipped due to shape mismatch.
"""
src_state_dict = src_model.state_dict()
tgt_state_dict = tgt_model.state_dict()
loaded_keys = []
skipped_keys = []
# Create a new state_dict with only matching keys
filtered_state_dict = {}
for key, param in src_state_dict.items():
if key in tgt_state_dict and param.shape == tgt_state_dict[key].shape:
filtered_state_dict[key] = param # Only load matching keys
loaded_keys.append(key)
else:
skipped_keys.append(key)
# Update target model's state_dict
tgt_state_dict.update(filtered_state_dict)
tgt_model.load_state_dict(tgt_state_dict)
# print(f"✅ Successfully loaded {len(loaded_keys)} layers.")
# print(f"⚠️ Skipped {len(skipped_keys)} layers due to size mismatch:")
# for key in skipped_keys:
# print(f" - {key}: Expected {tgt_state_dict[key].shape}, but found {src_state_dict[key].shape}")
return None
# return loaded_keys, skipped_keys
def probe_full_tm(
device,
patched_metalens,
full_wave_down_sample_rate = 1,
):
# time_start = time.time()
number_atoms = configs.invdes.num_atom
sources = torch.eye(number_atoms * round(15 // full_wave_down_sample_rate), device=device)
sim_key = list(patched_metalens.total_opt.objective.sims.keys())
assert len(sim_key) == 1, f"there should be only one sim key, but we got {sim_key}"
if hasattr(patched_metalens.total_opt.objective.sims[sim_key[0]].solver, "clear_solver_cache"):
patched_metalens.total_opt.objective.sims[sim_key[0]].solver.clear_solver_cache()
patched_metalens.total_opt.objective.sims[sim_key[0]].solver.set_cache_mode(True)
# we first need to run the normalizer
if patched_metalens.total_normalizer_list is None or len(patched_metalens.total_normalizer_list) < number_atoms * round(15 // full_wave_down_sample_rate):
total_normalizer_list = []
for idx in range(number_atoms * round(15 // full_wave_down_sample_rate)):
source_i = sources[idx].repeat_interleave(full_wave_down_sample_rate)
source_zero_padding = torch.zeros(int(0.5 * 50), device=device)
source_i = torch.cat([source_zero_padding, source_i, source_zero_padding])
boolean_source_mask = torch.zeros_like(source_i, dtype=torch.bool)
boolean_source_mask[torch.where(source_i != 0)] = True
custom_source = dict(
source=source_i,
slice_name="in_slice_1",
mode="Hz1",
wl=0.85,
direction="x+",
)
if configs.invdes.param_method == "level_set":
weight = patched_metalens.get_design_variables(
-0.05 * torch.ones_like(patched_metalens.get_pillar_width()),
)
_ = patched_metalens.total_opt(
sharpness=256,
weight=weight,
custom_source=custom_source
)
elif configs.invdes.param_method == "grating_width":
raise NotImplementedError("grating_width is deprecated")
_ = patched_metalens.total_opt(
sharpness=256,
weight={"design_region_0": patched_metalens.weights},
custom_source=custom_source
)
else:
raise NotImplementedError(f"Unknown param_method: {configs.invdes.param_method}")
source_field = patched_metalens.total_opt.objective.response[('in_slice_1', 'in_slice_1', 0.85, "Hz1", 300)]["fz"].squeeze()
total_normalizer_list.append(source_field[boolean_source_mask].mean())
if idx == number_atoms * round(15 // full_wave_down_sample_rate) - 1:
patched_metalens.set_total_normalizer_list(total_normalizer_list)
# now we already have the normalizer, we can run the full wave response
if hasattr(patched_metalens.total_opt.objective.sims[sim_key[0]].solver, "clear_solver_cache"):
patched_metalens.total_opt.objective.sims[sim_key[0]].solver.clear_solver_cache()
with torch.no_grad():
full_wave_response = torch.zeros(
(
number_atoms * round(15 // full_wave_down_sample_rate),
number_atoms * round(15 // full_wave_down_sample_rate),
),
device=device,
dtype=torch.complex128
)
for idx in range(number_atoms * round(15 // full_wave_down_sample_rate)):
source_i = sources[idx].repeat_interleave(full_wave_down_sample_rate)
source_zero_padding = torch.zeros(int(0.5 * 50), device=device)
source_i = torch.cat([source_zero_padding, source_i, source_zero_padding])
boolean_source_mask = torch.zeros_like(source_i, dtype=torch.bool)
boolean_source_mask[torch.where(source_i != 0)] = True
custom_source = dict(
source=source_i,
slice_name="in_slice_1",
mode="Hz1",
wl=0.85,
direction="x+",
)
if configs.invdes.param_method == "level_set":
_ = patched_metalens.total_opt(
sharpness=256,
weight=patched_metalens.get_design_variables(
patched_metalens.get_pillar_width(),
),
custom_source=custom_source
)
elif configs.invdes.param_method == "grating_width":
raise NotImplementedError("grating_width is deprecated")
_ = patched_metalens.total_opt(
sharpness=256,
weight={"design_region_0": patched_metalens.weights},
custom_source=custom_source
)
else:
raise NotImplementedError(f"Unknown param_method: {configs.invdes.param_method}")
response = patched_metalens.total_opt.objective.response[('in_slice_1', 'nearfield_1', 0.85, "Hz1", 300)]["fz"].squeeze()
response = response[full_wave_down_sample_rate // 2 :: full_wave_down_sample_rate]
assert len(response) == number_atoms * round(15 // full_wave_down_sample_rate), f"{len(response)}!= {number_atoms * round(15 // full_wave_down_sample_rate)}"
full_wave_response[idx] = response
full_wave_response = full_wave_response.transpose(0, 1)
if configs.model.conv_cfg.max_tm_norm:
full_wave_response = full_wave_response / torch.max(full_wave_response.abs())
else:
normalizer = torch.stack(patched_metalens.total_normalizer_list, dim=0).to(device)
normalizer = normalizer.unsqueeze(1)
full_wave_response = full_wave_response / normalizer
if hasattr(patched_metalens.total_opt.objective.sims[sim_key[0]].solver, "clear_solver_cache"):
patched_metalens.total_opt.objective.sims[sim_key[0]].solver.clear_solver_cache()
patched_metalens.total_opt.objective.sims[sim_key[0]].solver.set_cache_mode(False)
# time_end = time.time()
# print(f"this is the time for probing the full wave response: {time_end - time_start}", flush=True)
return full_wave_response
def set_test_model_transfer_matrix(
model,
model_test,
patched_metalens,
device,
):
if model_test is not None:
transfer_weights(model, model_test)
for i in range(configs.model.conv_cfg.path_depth):
current_width = model.state_dict()[f"features.conv1.conv._conv_pos.metalens.{i}_17.widths"]
print(f"this is the current width: {current_width}", flush=True)
# clip it to the range of [0.01, 0.28]
current_width = torch.clamp(current_width, min=0.01, max=0.28)
print(f"this is the current width after clipping: {current_width}", flush=True)
current_weights = get_mid_weight(0.05, current_width)
patched_metalens.direct_set_pillar_width(current_weights)
hr_tm = probe_full_tm(
device,
patched_metalens,
full_wave_down_sample_rate = 1,
)
model_test.features.conv1.conv._conv_pos.metalens[f"{i}_17"].set_param_from_target_matrix(hr_tm)
def design_using_LPA(
model,
model_test,
patched_metalens,
device,
):
if model_test is not None:
transfer_weights(model, model_test)
for i in range(configs.model.conv_cfg.path_depth):
current_lr_tm = model.state_dict()[f"features.conv1.conv._conv_pos.metalens.{i}_1.W_buffer"]
patched_metalens.set_target_phase_response(current_lr_tm)
patched_metalens.rebuild_param()
hr_tm = probe_full_tm(
device,
patched_metalens,
full_wave_down_sample_rate = 1,
)
model_test.features.conv1.conv._conv_pos.metalens[f"{i}_1"].set_param_from_target_matrix(hr_tm)
def project_to_implementable_subspace(
model,
model_test,
patched_metalens,
patched_metalens_list,
invdes_criterion,
prev_pillar_width,
out_epoch,
proj_idx,
in_downsample_rate_scheduler,
out_downsample_rate_scheduler,
near2far_matrix,
ds_near2far_matrix,
device,
probe_full_wave = True,
invdes_lr=None,
invdes_sharp=None,
layer_wise_matching=True,
epoch_per_proj=None,
finetune_entire = False,
match_entire_epoch=None,
admm_vars=None,
):
'''
there is not reparameterization of the transfer matrix of the metasurface during the DONN training,
so we cannot ensure that the transfer matrix from DONN is implementable in the real world,
for example, transfer matrix is not unitary, which means that it is not energy-conserved.
in this function, we use the inverse design to project the transfer matrix of the metasurface trained in DONN to the implementable subspace
we can actually get the real-world width of the metaatom array that corresponds to the required DONN transfer matrix"
'''
# lr = 5e-3
# lr = configs.invdes.lr
print(f"learning rate to be used: {invdes_lr}", flush=True)
print(f"this is the sharpness to be used: {invdes_sharp}", flush=True)
stitched_response_list = []
if model_test is not None:
transfer_weights(model, model_test)
current_pillar_width = []
in_downsample_rate = in_downsample_rate_scheduler.step()
out_downsample_rate = out_downsample_rate_scheduler.step()
if finetune_entire:
target_entire_transfer_matrix = None
current_ds_near2far_matrix = near2far_matrix[
in_downsample_rate//2::in_downsample_rate,
:
]
current_ds_near2far_matrix = current_ds_near2far_matrix.reshape(current_ds_near2far_matrix.shape[0], -1, out_downsample_rate).sum(dim=-1)
for i in range(configs.model.conv_cfg.path_depth):
current_lens_tm = model.state_dict()[f"features.conv1.conv._conv_pos.metalens.{i}_17.W_buffer"]
current_ds_near2far_matrix = current_ds_near2far_matrix.to(current_lens_tm.dtype)
if target_entire_transfer_matrix is None:
target_entire_transfer_matrix = current_ds_near2far_matrix @ current_lens_tm
else:
target_entire_transfer_matrix = current_ds_near2far_matrix @ current_lens_tm @ target_entire_transfer_matrix
target_entire_transfer_matrix_phase = torch.angle(target_entire_transfer_matrix)
target_entire_transfer_matrix_phase_variants = torch.stack([
target_entire_transfer_matrix_phase, # Original
target_entire_transfer_matrix_phase + 2 * torch.pi,
target_entire_transfer_matrix_phase - 2 * torch.pi,
], dim=0)
target_transfer_matrix = []
for i in range(configs.model.conv_cfg.path_depth):
target_transfer_matrix.append(model.state_dict()[f"features.conv1.conv._conv_pos.metalens.{i}_17.W_buffer"])
if layer_wise_matching:
for i in range(configs.model.conv_cfg.path_depth):
# first, we need to read the transfer matrix of the metasurface trained in DONN
A = target_transfer_matrix[i]
target_response = A
if configs.model.conv_cfg.max_tm_norm:
target_response = target_response / torch.max(target_response.abs())
target_phase_response = torch.angle(target_response)
target_phase_variants = torch.stack([
target_phase_response, # Original
target_phase_response + 2 * torch.pi,
target_phase_response - 2 * torch.pi,
], dim=0) # Shape (3, N)
if configs.invdes.project_init == "LPA" or prev_pillar_width is None:
patched_metalens.set_target_phase_response(target_phase_response)
patched_metalens.rebuild_param()
elif configs.invdes.project_init == "last_time":
patched_metalens.direct_set_pillar_width(prev_pillar_width[i])
else:
raise NotImplementedError(f"Unknown project_init: {configs.invdes.project_init}")
# optimizer = torch.optim.Adam(patched_metalens.parameters(), lr=lr)
# scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
# optimizer, T_max=num_epoch, eta_min=lr * 1e-2
# )
invdes_optimizer, invdes_scheduler = reset_optimizer_and_scheduler(
model=patched_metalens,
lr_init=invdes_lr[0],
lr_final=invdes_lr[1],
num_epoch=epoch_per_proj,
)
sharp_scheduler = SharpnessScheduler(
initial_sharp=invdes_sharp[0],
final_sharp=invdes_sharp[1],
total_steps=epoch_per_proj,
)
for epoch in range(epoch_per_proj):
sharpness = sharp_scheduler.get_sharpness()
invdes_optimizer.zero_grad()
# time_start = time.time()
stitched_response = patched_metalens.forward(
sharpness=sharpness,
in_down_sample_rate=in_downsample_rate,
out_down_sample_rate=out_downsample_rate,
)
# if epoch == epoch_per_proj - 1:
# quit()
# time_end = time.time()
# print(f"this is the time for the forward: {time_end - time_start}", flush=True)
if configs.model.conv_cfg.max_tm_norm:
stitched_response = stitched_response / torch.max(stitched_response.abs()) # normalize the response
if isinstance(invdes_criterion, CosSimLoss):
loss_fn_output = invdes_criterion(
stitched_response,
target_response.to(stitched_response.dtype),
)
loss_fn_output = -loss_fn_output
elif configs.invdes.criterion.name == "TMMatching":
loss_fn_output = invdes_criterion(
stitched_response,
target_response,
target_phase_variants,
seperate_loss=configs.invdes.seperate_loss,
)
elif configs.invdes.criterion.name == "ResponseMatching":
loss_fn_output = invdes_criterion(
target_response,
stitched_response,
(i + 1) if getattr(configs.invdes.criterion, "weighted_response", False) else 0,
)
if isinstance(loss_fn_output, tuple):
loss = loss_fn_output[0]
else:
loss = loss_fn_output
if configs.invdes.admm:
x_admm = stitched_response
diff = x_admm - admm_vars['z_admm'][i] + admm_vars['u_admm'][i]
loss += (admm_vars['rho_admm'] / 2.0) * torch.norm(diff) ** 2
# time_start = time.time()
loss.backward()
# time_end = time.time()
# print(f"this is the time for the backward: {time_end - time_start}", flush=True)
patched_metalens.disable_solver_cache()
# for p in patched_metalens.parameters():
# if p.grad is not None:
# print(f"this is the norm of the gradient: {p.grad.norm()}", flush=True)
# process = psutil.Process(os.getpid())
# mem = process.memory_info().rss / 1024**2 # in MB
# print(f"CPU memory usage: {mem:.2f} MB", flush=True)
invdes_optimizer.step()
invdes_scheduler.step()
sharp_scheduler.step()
# for p in patched_metalens.parameters():
# if p.grad is not None:
# print(f"this is the norm of the gradient: {p.grad.norm()}", flush=True)
print(f"epoch: {epoch}, loss: {loss.item()}", flush=True)
# fig, ax = plt.subplots(1, 3, figsize=(15, 5))
# im0 = ax[0].imshow(
# target_response.abs().cpu().numpy()
# )
# ax[0].set_title("Target Magnitude")
# fig.colorbar(im0, ax=ax[0])
# im1 = ax[1].imshow(
# stitched_response.detach().abs().cpu().numpy()
# )
# ax[1].set_title("Stitched Magnitude")
# fig.colorbar(im1, ax=ax[1])
# im2 = ax[2].imshow(
# (stitched_response - target_response).detach().abs().cpu().numpy()
# )
# ax[2].set_title("Difference Magnitude")
# fig.colorbar(im2, ax=ax[2])
# fig.suptitle(f"this is the sharpness we are using: {sharpness}", fontsize=16)
# plt.savefig(configs.plot.plot_root + f"convid-{i}_epoch-{out_epoch}_projID-{proj_idx}_invdesEpoch-{epoch}.png", dpi = 300)
# plt.close()
current_pillar_width.append(patched_metalens.get_pillar_width())
with torch.no_grad():
sharpness = sharp_scheduler.get_sharpness()
print(f"this is the sharpness we are using to set the model: {sharpness}", flush=True)
stitched_response = patched_metalens.forward(
sharpness=sharpness,
in_down_sample_rate=in_downsample_rate,
out_down_sample_rate=out_downsample_rate,
)
if isinstance(invdes_criterion, CosSimLoss):
loss_fn_output = invdes_criterion(
stitched_response,
target_response.to(stitched_response.dtype),
)
loss_fn_output = -loss_fn_output
elif configs.invdes.criterion.name == "TMMatching":
loss_fn_output = invdes_criterion(
stitched_response,
target_response,
target_phase_variants,
seperate_loss=configs.invdes.seperate_loss,
)
elif configs.invdes.criterion.name == "ResponseMatching":
loss_fn_output = invdes_criterion(
target_response,
stitched_response,
(i + 1) if getattr(configs.invdes.criterion, "weighted_response", False) else 0
)
if isinstance(loss_fn_output, tuple):
loss = loss_fn_output[0]
else:
loss = loss_fn_output
print(f"final loss: {loss.item()}", flush=True)
# fig, ax = plt.subplots(1, 3, figsize=(15, 5))
# im0 = ax[0].imshow(
# target_response.abs().cpu().numpy()
# )
# ax[0].set_title("Target Magnitude")
# fig.colorbar(im0, ax=ax[0])
# im1 = ax[1].imshow(
# stitched_response.detach().abs().cpu().numpy()
# )
# ax[1].set_title("Stitched Magnitude")
# fig.colorbar(im1, ax=ax[1])
# im2 = ax[2].imshow(
# (stitched_response - target_response).detach().abs().cpu().numpy()
# )
# ax[2].set_title("Difference Magnitude")
# fig.colorbar(im2, ax=ax[2])
# fig.suptitle(f"this is the sharpness we are using: {sharpness}", fontsize=16)
# plt.savefig(configs.plot.plot_root + f"convid-{i}_epoch-{out_epoch}_projID-{proj_idx}_invdesEpoch-{epoch_per_proj}.png", dpi = 300)
# plt.close()
model.features.conv1.conv._conv_pos.metalens[f"{i}_17"].set_param_from_target_matrix(stitched_response)
stitched_response_list.append(stitched_response)
# sweep real transfer matrix and set it to the model_test
if probe_full_wave and not finetune_entire:
high_res_response = probe_full_tm(device=device, patched_metalens=patched_metalens)
# print("this is the keys in the model: ", list(model_test.features.conv1.conv._conv_pos.metalens.keys()))
model_test.features.conv1.conv._conv_pos.metalens[f"{i}_17"].set_param_from_target_matrix(high_res_response)
full_wave_response = high_res_response
if target_response.shape != full_wave_response.shape:
# assert full_wave_response.shape[-1] % target_response.shape[-1] == 0, f"{full_wave_response.shape[-1]} % {target_response.shape[-1]} != 0"
# assert full_wave_response.shape[-2] % target_response.shape[-2] == 0, f"{full_wave_response.shape[-2]} % {target_response.shape[-2]} != 0"
# assert full_wave_response.shape[-1] // target_response.shape[-1] == full_wave_response.shape[-2] // target_response.shape[-2]
# ds_rate = full_wave_response.shape[-1] // target_response.shape[-1]
# full_wave_response = full_wave_response[
# ds_rate//2::ds_rate,
# :
# ]
# full_wave_response = full_wave_response.reshape(full_wave_response.shape[0], -1, ds_rate).sum(dim=-1)
upsampled_target_real = F.interpolate(target_response.real.unsqueeze(0).unsqueeze(0), size=full_wave_response.shape[-2:], mode="bilinear", align_corners=False).squeeze()
upsampled_target_imag = F.interpolate(target_response.imag.unsqueeze(0).unsqueeze(0), size=full_wave_response.shape[-2:], mode="bilinear", align_corners=False).squeeze()
upsampled_target_response = upsampled_target_real + 1j * upsampled_target_imag
ds_rate = full_wave_response.shape[-1] / target_response.shape[-1]
upsampled_target_response = upsampled_target_response / ds_rate
else:
upsampled_target_response = target_response
fig, ax = plt.subplots(2, 4, figsize=(20, 10))
im0 = ax[0, 0].imshow(
target_response.abs().cpu().numpy()
)
ax[0, 0].set_title("Target Magnitude")
fig.colorbar(im0, ax=ax[0, 0])
im1 = ax[0, 1].imshow(
stitched_response.detach().abs().cpu().numpy()
)
ax[0, 1].set_title("Stitched Magnitude")
fig.colorbar(im1, ax=ax[0, 1])
im2 = ax[0, 2].imshow(
full_wave_response.abs().cpu().numpy()
)
ax[0, 2].set_title("Full Magnitude")
fig.colorbar(im2, ax=ax[0, 2])
im3 = ax[0, 3].imshow(
(
full_wave_response / torch.norm(full_wave_response, p=2) - upsampled_target_response / torch.norm(upsampled_target_response, p=2)
).abs().cpu().numpy()
)
ax[0, 3].set_title("Difference Magnitude")
fig.colorbar(im3, ax=ax[0, 3])
im4 = ax[1, 0].imshow(
torch.angle(target_response).cpu().numpy()
)
ax[1, 0].set_title("Target Phase")
fig.colorbar(im4, ax=ax[1, 0])
im5 = ax[1, 1].imshow(
torch.angle(stitched_response.detach()).cpu().numpy()
)
ax[1, 1].set_title("Stitched Phase")
fig.colorbar(im5, ax=ax[1, 1])
im6 = ax[1, 2].imshow(
torch.angle(full_wave_response).cpu().numpy()
)
ax[1, 2].set_title("Full Phase")
fig.colorbar(im6, ax=ax[1, 2])
im7 = ax[1, 3].imshow(
torch.angle(
full_wave_response / torch.norm(full_wave_response, p=2) - upsampled_target_response / torch.norm(upsampled_target_response, p=2)
).cpu().numpy()
)
ax[1, 3].set_title("Difference Phase")
fig.colorbar(im7, ax=ax[1, 3])
plt.savefig(configs.plot.plot_root + f"epoch-{out_epoch}_convid-{i}.png")
plt.close()
else:
if stitched_response.shape != target_response.shape:
# interpolate the target to the same size as the transfer matrix
W_stitched = stitched_response.shape[-1]
W_target = target_response.shape[-1]
stitched_response_real = F.interpolate(stitched_response.real.unsqueeze(0).unsqueeze(0), size=target_response.shape[-2:], mode="bilinear", align_corners=False).squeeze()
stitched_response_imag = F.interpolate(stitched_response.imag.unsqueeze(0).unsqueeze(0), size=target_response.shape[-2:], mode="bilinear", align_corners=False).squeeze()
stitched_response = stitched_response_real + 1j * stitched_response_imag
ds_rate = W_stitched / W_target
stitched_response = stitched_response * ds_rate
fig, ax = plt.subplots(2, 3, figsize=(15, 10))
im0 = ax[0, 0].imshow(
target_response.abs().cpu().numpy()
)
ax[0, 0].set_title("Target Magnitude")
fig.colorbar(im0, ax=ax[0, 0])
im1 = ax[0, 1].imshow(
stitched_response.detach().abs().cpu().numpy()
)
ax[0, 1].set_title("Stitched Magnitude")
fig.colorbar(im1, ax=ax[0, 1])
im3 = ax[0, 2].imshow(
(stitched_response - target_response).detach().abs().cpu().numpy()
)
ax[0, 2].set_title("Difference Magnitude")
fig.colorbar(im3, ax=ax[0, 2])
im4 = ax[1, 0].imshow(
torch.angle(target_response).cpu().numpy()
)
ax[1, 0].set_title("Target Phase")
fig.colorbar(im4, ax=ax[1, 0])
im5 = ax[1, 1].imshow(
torch.angle(stitched_response.detach()).cpu().numpy()
)
ax[1, 1].set_title("Stitched Phase")
fig.colorbar(im5, ax=ax[1, 1])
im7 = ax[1, 2].imshow(
torch.angle(stitched_response - target_response).detach().cpu().numpy()
)
ax[1, 2].set_title("Difference Phase")
fig.colorbar(im7, ax=ax[1, 2])
plt.savefig(configs.plot.plot_root + f"epoch-{out_epoch}_convid-{i}.png")
plt.close()
if not finetune_entire:
assert layer_wise_matching, "neither layer-wise matching nor entire matching is set while projection is on, please check the configs"
current_pillar_width = torch.stack(current_pillar_width, dim=0) # shape (depth, num_atom)
stitched_response = torch.stack(stitched_response_list, dim=0)
lg.info(f"this is the current pillar width: {current_pillar_width}")
return stitched_response.detach(), current_pillar_width
# fine-tune the entire transfer matrix
# by matching UTUT
else:
# reset the return value
match_entire_stitched_response_list = []
match_entire_current_pillar_width = []
for i in range(configs.model.conv_cfg.path_depth):
# if configs.invdes.project_init == "LPA" or prev_pillar_width is None:
# patched_metalens.set_target_phase_response(target_phase_response)
# patched_metalens.rebuild_param()
# elif configs.invdes.project_init == "last_time":
# patched_metalens.direct_set_pillar_width(prev_pillar_width[i])
# else:
# raise NotImplementedError(f"Unknown project_init: {configs.invdes.project_init}")
if len(current_pillar_width) == 0: # which means that we are not using the layer-wise matching
assert not layer_wise_matching, "layer-wise matching is set but the len of current_pillar_width is 0, something is wrong"
assert configs.invdes.project_init != "LPA", "project_init can not be LPA since we don't know the layer wise response info"
if prev_pillar_width is not None:
# if we have the previous pillar width, we can set it to the patched_metalens
# otherwise, we only have a entire transfer matrix, and we cannot layer-wise set each layer
patched_metalens_list[i].direct_set_pillar_width(prev_pillar_width[i])
else: # which means that we are using the layer-wise matching and we can get the current_pillar_width from it
patched_metalens_list[i].direct_set_pillar_width(current_pillar_width[i])
invdes_optimizer, invdes_scheduler = reset_optimizer_and_scheduler(
model=patched_metalens_list,
lr_init=invdes_lr[0] if configs.invdes.adaptive_finetune_lr else configs.invdes.finetune_lr_init,
lr_final=invdes_lr[1] if configs.invdes.adaptive_finetune_lr else configs.invdes.finetune_lr_final,
num_epoch=match_entire_epoch,
)
sharp_scheduler = SharpnessScheduler(
initial_sharp=invdes_sharp[0],
final_sharp=invdes_sharp[1],
total_steps=match_entire_epoch,
)
for i in range(match_entire_epoch):
sharpness = sharp_scheduler.get_sharpness()
invdes_optimizer.zero_grad()
curren_entire_transfer_matrix = None
for j in range(configs.model.conv_cfg.path_depth):
current_layer_tm = patched_metalens_list[j].forward(
sharpness=sharpness,
in_down_sample_rate=in_downsample_rate,
out_down_sample_rate=out_downsample_rate,
)
current_ds_near2far_matrix = near2far_matrix[
in_downsample_rate//2::in_downsample_rate,
:
]
current_ds_near2far_matrix = current_ds_near2far_matrix.reshape(current_ds_near2far_matrix.shape[0], -1, out_downsample_rate).sum(dim=-1)
current_ds_near2far_matrix = current_ds_near2far_matrix.to(current_layer_tm.dtype)
if curren_entire_transfer_matrix is None:
curren_entire_transfer_matrix = current_ds_near2far_matrix @ current_layer_tm
else:
curren_entire_transfer_matrix = current_ds_near2far_matrix @ current_layer_tm @ curren_entire_transfer_matrix
if configs.invdes.criterion.name == "TMMatching":
loss_fn_output = invdes_criterion(
curren_entire_transfer_matrix,
target_entire_transfer_matrix,
target_entire_transfer_matrix_phase_variants,
seperate_loss=configs.invdes.seperate_loss
)
elif configs.invdes.criterion.name == "ResponseMatching":
loss_fn_output = invdes_criterion(
target_entire_transfer_matrix,
curren_entire_transfer_matrix,
1 if getattr(configs.invdes.criterion, "weighted_response", False) else 0,
)
else:
raise NotImplementedError(f"Unknown criterion: {configs.invdes.criterion.name}")
if isinstance(loss_fn_output, tuple):
loss = loss_fn_output[0]
else:
loss = loss_fn_output
loss.backward()
for j in range(configs.model.conv_cfg.path_depth):
patched_metalens_list[j].disable_solver_cache()
# process = psutil.Process(os.getpid())
# mem = process.memory_info().rss / 1024**2 # in MB
# print(f"CPU memory usage: {mem:.2f} MB", flush=True)
invdes_optimizer.step()
invdes_scheduler.step()
sharp_scheduler.step()
print(f"matching entire epoch: {i}, loss: {loss.item()}", flush=True)
if i == match_entire_epoch - 1:
match_entire_current_pillar_width = [patched_metalens_list[idx].get_pillar_width() for idx in range(configs.model.conv_cfg.path_depth)]
with torch.no_grad():
sharpness = sharp_scheduler.get_sharpness()
match_entire_stitched_response_list = [
patched_metalens_list[idx].forward(
sharpness=sharpness,
in_down_sample_rate=in_downsample_rate,
out_down_sample_rate=out_downsample_rate,
) for idx in range(configs.model.conv_cfg.path_depth)
]
stitched_response = torch.stack(match_entire_stitched_response_list, dim=0)
current_pillar_width = torch.stack(match_entire_current_pillar_width, dim=0)
for i in range(configs.model.conv_cfg.path_depth):
model.features.conv1.conv._conv_pos.metalens[f"{i}_17"].set_param_from_target_matrix(match_entire_stitched_response_list[i])
if probe_full_wave:
for i in range(configs.model.conv_cfg.path_depth):
high_res_response = probe_full_tm(device=device, patched_metalens=patched_metalens_list[i])
# print("this is the keys in the model: ", list(model_test.features.conv1.conv._conv_pos.metalens.keys()))
model_test.features.conv1.conv._conv_pos.metalens[f"{i}_17"].set_param_from_target_matrix(high_res_response)
full_wave_response = high_res_response
target_response = target_transfer_matrix[i]
if target_response.shape != full_wave_response.shape:
# assert full_wave_response.shape[-1] % target_response.shape[-1] == 0, f"{full_wave_response.shape[-1]} % {target_response.shape[-1]} != 0"
# assert full_wave_response.shape[-2] % target_response.shape[-2] == 0, f"{full_wave_response.shape[-2]} % {target_response.shape[-2]} != 0"
# assert full_wave_response.shape[-1] // target_response.shape[-1] == full_wave_response.shape[-2] // target_response.shape[-2]
# ds_rate = full_wave_response.shape[-1] // target_response.shape[-1]
# full_wave_response = full_wave_response[
# ds_rate//2::ds_rate,
# :
# ]
# full_wave_response = full_wave_response.reshape(full_wave_response.shape[0], -1, ds_rate).sum(dim=-1)
upsampled_target_real = F.interpolate(target_response.real.unsqueeze(0).unsqueeze(0), size=full_wave_response.shape[-2:], mode="bilinear", align_corners=False).squeeze()
upsampled_target_imag = F.interpolate(target_response.imag.unsqueeze(0).unsqueeze(0), size=full_wave_response.shape[-2:], mode="bilinear", align_corners=False).squeeze()
upsampled_target_response = upsampled_target_real + 1j * upsampled_target_imag
ds_rate = full_wave_response.shape[-1] / target_response.shape[-1]
upsampled_target_response = upsampled_target_response / ds_rate
else:
upsampled_target_response = target_response
fig, ax = plt.subplots(2, 4, figsize=(20, 10))
im0 = ax[0, 0].imshow(
target_response.abs().cpu().numpy()
)
ax[0, 0].set_title("Target Magnitude")
fig.colorbar(im0, ax=ax[0, 0])
im1 = ax[0, 1].imshow(
stitched_response[i].detach().abs().cpu().numpy()
)
ax[0, 1].set_title("Stitched Magnitude")
fig.colorbar(im1, ax=ax[0, 1])
im2 = ax[0, 2].imshow(
full_wave_response.abs().cpu().numpy()
)
ax[0, 2].set_title("Full Magnitude")
fig.colorbar(im2, ax=ax[0, 2])
im3 = ax[0, 3].imshow(
(
full_wave_response / torch.norm(full_wave_response, p=2) - upsampled_target_response / torch.norm(upsampled_target_response, p=2)
).abs().cpu().numpy()
)
ax[0, 3].set_title("Difference Magnitude")
fig.colorbar(im3, ax=ax[0, 3])
im4 = ax[1, 0].imshow(
torch.angle(target_response).cpu().numpy()
)
ax[1, 0].set_title("Target Phase")
fig.colorbar(im4, ax=ax[1, 0])
im5 = ax[1, 1].imshow(
torch.angle(stitched_response[i].detach()).cpu().numpy()
)
ax[1, 1].set_title("Stitched Phase")
fig.colorbar(im5, ax=ax[1, 1])
im6 = ax[1, 2].imshow(
torch.angle(full_wave_response).cpu().numpy()
)
ax[1, 2].set_title("Full Phase")
fig.colorbar(im6, ax=ax[1, 2])
im7 = ax[1, 3].imshow(
torch.angle(
full_wave_response / torch.norm(full_wave_response, p=2) - upsampled_target_response / torch.norm(upsampled_target_response, p=2)
).cpu().numpy()
)
ax[1, 3].set_title("Difference Phase")
fig.colorbar(im7, ax=ax[1, 3])
plt.savefig(configs.plot.plot_root + f"epoch-{out_epoch}_convid-{i}_full_lens.png")
plt.close()
lg.info(f"this is the current pillar width: {current_pillar_width}")
return stitched_response.detach(), current_pillar_width
def train(
model: nn.Module,
train_loader: DataLoader,
optimizer: Optimizer,
scheduler: Scheduler,
epoch: int,
criterion: Criterion,
aux_criterions: Dict,
mixup_fn: Callable = None,
device: torch.device = torch.device("cuda:0"),
grad_scaler: Optional[Callable] = None,
teacher: Optional[nn.Module] = None,
stitched_response: torch.Tensor = None,
plot: bool = False,
# params for inverse design projection
patched_metalens: Optional[PatchMetalens] = None,
patched_metalens_list: Optional[List[PatchMetalens]] = None,
invdes_criterion: Optional[Callable] = None,
current_pillar_width: Optional[torch.Tensor] = None,
invdes_lr: tuple = None,
invdes_sharp: tuple = None,
in_downsample_rate_scheduler: Optional[Scheduler] = None,
out_downsample_rate_scheduler: Optional[Scheduler] = None,
near2far_matrix: Optional[torch.Tensor] = None,
ds_near2far_matrix: Optional[torch.Tensor] = None,
admm_vars = None,
) -> None:
# the invdes_lr looks like (5e-3, 5e-5)
# the invdes_sharp looks like (10, 256)
assert len(invdes_lr) == 2, f"len(invdes_lr) != 2, {invdes_lr}"
assert len(invdes_sharp) == 2, f"len(invdes_sharp) != 2, {invdes_sharp}"
assert configs.invdes.num_epoch % configs.invdes.epoch_per_proj == 0, f"{configs.invdes.num_epoch} % {configs.invdes.epoch_per_proj} != 0"
if configs.model.conv_cfg.TM_model_method == "end2end":
end2end_sharpness_scheduler = builder.make_scheduler(
optimizer=None,
name="end2end_sharpness",
cfgs=configs.end2end_sharpness_scheduler,
)
else:
end2end_sharpness_scheduler = None
num_proj_during_train = round(configs.invdes.num_epoch // configs.invdes.epoch_per_proj) - 1 # we must do a projection at the end of the training
proj_batch_interval = len(train_loader) // (num_proj_during_train + 1)
current_project_count = 0
invdes_array = np.linspace(invdes_lr[0], invdes_lr[1], num_proj_during_train + 2) # * get_learning_rate(optimizer) / configs.optimizer.lr
invdes_sharp_array = np.linspace(invdes_sharp[0], invdes_sharp[1], num_proj_during_train + 2)
# print("this is the invdes_array: ", invdes_array, flush=True)
# print("this is the invdes_sharp_array: ", invdes_sharp_array, flush=True)
model.train()
step = epoch * len(train_loader)
class_meter = AverageMeter("ce")
aux_meters = {name: AverageMeter(name) for name in aux_criterions}
data_counter = 0
correct = 0
total_data = len(train_loader.dataset)
for batch_idx, (data, target) in enumerate(train_loader):
if configs.model.conv_cfg.TM_model_method == "end2end":
sharpness = end2end_sharpness_scheduler.step()
print(f"this is the sharpness: {sharpness}", flush=True)
if sharpness >= configs.end2end_sharpness_scheduler.final_sharpness:
break
else:
sharpness = None
data = data.to(device, non_blocking=True)
data_counter += data.shape[0]
target = target.to(device, non_blocking=True)
if mixup_fn is not None:
data, target = mixup_fn(data, target)
with amp.autocast(enabled=grad_scaler._enabled):
output = model(data, sharpness)
if isinstance(output, tuple):
output, inner_fields = output
class_loss = criterion(output, target)
class_meter.update(class_loss.item())
loss = class_loss
# if batch_idx == len(train_loader) - 1:
# print("this is the criterion: ", criterion, flush=True)
# print("this is the output: ", output[0], flush=True)
# print("this is the target: ", target[0], flush=True)
# print("this is the loss: ", loss, flush=True)
smoothing_loss = 0
# if hasattr(model, "get_smoothing_loss"):
# # you can pass in a hyperparameter e.g. 1e-3
# smoothing_loss = model.get_smoothing_loss(lambda_smooth=1e-3)
# loss += smoothing_loss
intensity_loss = 0
# lambda_intensity = 1e-3
# total_intensity = output.sum(dim=1).mean()
# intensity_loss = -lambda_intensity * total_intensity
# loss += intensity_loss
for name, config in aux_criterions.items():
aux_criterion, weight = config
aux_loss = 0
if name in {"kd", "dkd"} and teacher is not None:
with torch.no_grad():
teacher_scores = teacher(data).data.detach()
aux_loss = weight * aux_criterion(output, teacher_scores, target)
elif name == "mse_distill" and teacher is not None:
with torch.no_grad():
teacher(data).data.detach()
teacher_hiddens = [
m._recorded_hidden
for m in teacher.modules()
if hasattr(m, "_recorded_hidden")
]
student_hiddens = [
m._recorded_hidden
for m in model.modules()
if hasattr(m, "_recorded_hidden")
]
aux_loss = weight * sum(
F.mse_loss(h1, h2)
for h1, h2 in zip(teacher_hiddens, student_hiddens)
)
elif name == "distance_constraint": # this prevent the wegiths from being too faraway from the initial weights
assert stitched_response is not None
aux_loss = weight * aux_criterion(stitched_response, model.features.conv1.conv._conv_pos.equivalent_W)
elif name == "smooth_penalty":
aux_loss = weight * aux_criterion(model.features.conv1.conv._conv_pos.equivalent_W)
elif name == "admm":
aux_loss = weight * aux_criterion(model.features.conv1.conv._conv_pos.equivalent_W, admm_vars)