forked from brando90/ultimate-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpython_pg.py
12093 lines (10054 loc) · 326 KB
/
python_pg.py
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
# %%
# to test impots
import sys
from typing import List, NewType
for path in sys.path:
print(path)
# %%
def __path_bn_layer_for_functional_eval(self, module, input):
for attr_str in dir(module):
target_attr = getattr(module, attr_str)
print(target_attr)
if type(target_attr) == torch.nn.BatchNorm1d:
target_attr.track_running_stats = True
target_attr.running_mean = input.mean()
target_attr.running_var = input.var()
target_attr.num_batches_tracked = torch.tensor(0, dtype=torch.long)
# "recurse" iterate through immediate child modules. Note, the recursion is done by our code no need to use named_modules()
for name, immediate_child_module in module.named_children():
self._path_bn_layer_for_functional_eval(immediate_child_module, name)
# %%
import time
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(levelname)s:%(name)s:%(message)s')
file_handler = logging.FileHandler('employee.log')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
class Employee:
"""A sample Employee class"""
def __init__(self, first, last):
self.first = first
self.last = last
logger.info('Created Employee: {} - {}'.format(self.fullname, self.email))
@property
def email(self):
return '{}.{}@email.com'.format(self.first, self.last)
@property
def fullname(self):
return '{} {}'.format(self.first, self.last)
emp_1 = Employee('John', 'Smith')
emp_2 = Employee('Corey', 'Schafer')
emp_3 = Employee('Jane', 'Doe')
######## END OF EMPLOYEE LOGGING EXAMPLE
def report_times(start, verbose=False):
'''
How much time has passed since the time "start"
:param float start: the number representing start (usually time.time())
'''
meta_str = ''
## REPORT TIMES
start_time = start
seconds = (time.time() - start_time)
minutes = seconds / 60
hours = minutes / 60
if verbose:
print(f"--- {seconds} {'seconds ' + meta_str} ---")
print(f"--- {minutes} {'minutes ' + meta_str} ---")
print(f"--- {hours} {'hours ' + meta_str} ---")
print('\a')
##
msg = f'time passed: hours:{hours}, minutes={minutes}, seconds={seconds}'
return msg, seconds, minutes, hours
#
# def params_in_comp_graph():
# import torch
# import torch.nn as nn
# # from torchviz import make_dot
# fc0 = nn.Linear(in_features=3, out_features=1)
# params = [('fc0', fc0)]
# mdl = nn.Sequential(OrderedDict(params))
#
# x = torch.randn(1, 3)
# # x.requires_grad = True # uncomment to put in computation graph
# y = torch.randn(1)
#
# l = (mdl(x) - y) ** 2
#
# # make_dot(l, params=dict(mdl.named_parameters()))
# params = dict(mdl.named_parameters())
# # params = {**params, 'x':x}
# make_dot(l, params=params).render('data/debug/test_img_l', format='png')
def check_if_tensor_is_detached():
a = torch.tensor([2.0], requires_grad=True)
b = a.detach()
b.requires_grad = True
print(a == b)
print(a is b)
print(a)
print(b)
la = (5.0 - a) ** 2
la.backward()
print(f'a.grad = {a.grad}')
lb = (6.0 - b) ** 2
lb.backward()
print(f'b.grad = {b.grad}')
def deep_copy_issue():
params = OrderedDict([('fc1', nn.Linear(in_features=3, out_features=1))])
mdl0 = nn.Sequential(params)
mdl1 = copy.deepcopy(mdl0)
print(id(mdl0))
print(mdl0)
print(id(mdl1))
print(mdl1)
# my update
mdl1.fc1.weight = nn.Parameter(mdl1.fc1.weight + 1)
mdl2 = copy.deepcopy(mdl1)
print(id(mdl2))
print(mdl2)
def download_mini_imagenet():
# download mini-imagenet automatically
import torch
import torch.nn as nn
import torchvision.datasets.utils as utils
from torchvision.datasets.utils import download_and_extract_archive
from torchvision.datasets.utils import download_file_from_google_drive
## download mini-imagenet
# url = 'https://drive.google.com/file/d/1rV3aj_hgfNTfCakffpPm7Vhpr1in87CR'
file_id = '1rV3aj_hgfNTfCakffpPm7Vhpr1in87CR'
filename = 'miniImagenet.tgz'
root = '~/tmp/' # dir to place downloaded file in
download_file_from_google_drive(file_id, root, filename)
def extract():
from torchvision.datasets.utils import extract_archive
from_path = os.path.expanduser('~/Downloads/miniImagenet.tgz')
extract_archive(from_path)
def download_and_extract_miniImagenet(root):
import os
from torchvision.datasets.utils import download_file_from_google_drive, extract_archive
## download miniImagenet
# url = 'https://drive.google.com/file/d/1rV3aj_hgfNTfCakffpPm7Vhpr1in87CR'
file_id = '1rV3aj_hgfNTfCakffpPm7Vhpr1in87CR'
filename = 'miniImagenet.tgz'
download_file_from_google_drive(file_id, root, filename)
fpath = os.path.join(root, filename) # this is what download_file_from_google_drive does
## extract downloaded dataset
from_path = os.path.expanduser(fpath)
extract_archive(from_path)
## remove the zip file
os.remove(from_path)
def torch_concat():
import torch
g1 = torch.randn(3, 3)
g2 = torch.randn(3, 3)
#
# def inner_loop1():
# n_inner_iter = 5
# inner_opt = torch.optim.SGD(net.parameters(), lr=1e-1)
#
# qry_losses = []
# qry_accs = []
# meta_opt.zero_grad()
# for i in range(task_num):
# with higher.innerloop_ctx(
# net, inner_opt, copy_initial_weights=False
# ) as (fnet, diffopt):
# # Optimize the likelihood of the support set by taking
# # gradient steps w.r.t. the model's parameters.
# # This adapts the model's meta-parameters to the task.
# # higher is able to automatically keep copies of
# # your network's parameters as they are being updated.
# for _ in range(n_inner_iter):
# spt_logits = fnet(x_spt[i])
# spt_loss = F.cross_entropy(spt_logits, y_spt[i])
# diffopt.step(spt_loss)
#
# # The final set of adapted parameters will induce some
# # final loss and accuracy on the query dataset.
# # These will be used to update the model's meta-parameters.
# qry_logits = fnet(x_qry[i])
# qry_loss = F.cross_entropy(qry_logits, y_qry[i])
# qry_losses.append(qry_loss.detach())
# qry_acc = (qry_logits.argmax(
# dim=1) == y_qry[i]).sum().item() / querysz
# qry_accs.append(qry_acc)
#
# # Update the model's meta-parameters to optimize the query
# # losses across all of the tasks sampled in this batch.
# # This unrolls through the gradient steps.
# qry_loss.backward()
#
# meta_opt.step()
# qry_losses = sum(qry_losses) / task_num
# qry_accs = 100. * sum(qry_accs) / task_num
# i = epoch + float(batch_idx) / n_train_iter
# iter_time = time.time() - start_time
# def inner_loop2():
# n_inner_iter = 5
# inner_opt = torch.optim.SGD(net.parameters(), lr=1e-1)
#
# qry_losses = []
# qry_accs = []
# meta_opt.zero_grad()
# meta_loss = 0
# for i in range(task_num):
# with higher.innerloop_ctx(
# net, inner_opt, copy_initial_weights=False
# ) as (fnet, diffopt):
# # Optimize the likelihood of the support set by taking
# # gradient steps w.r.t. the model's parameters.
# # This adapts the model's meta-parameters to the task.
# # higher is able to automatically keep copies of
# # your network's parameters as they are being updated.
# for _ in range(n_inner_iter):
# spt_logits = fnet(x_spt[i])
# spt_loss = F.cross_entropy(spt_logits, y_spt[i])
# diffopt.step(spt_loss)
#
# # The final set of adapted parameters will induce some
# # final loss and accuracy on the query dataset.
# # These will be used to update the model's meta-parameters.
# qry_logits = fnet(x_qry[i])
# qry_loss = F.cross_entropy(qry_logits, y_qry[i])
# qry_losses.append(qry_loss.detach())
# qry_acc = (qry_logits.argmax(
# dim=1) == y_qry[i]).sum().item() / querysz
# qry_accs.append(qry_acc)
#
# # Update the model's meta-parameters to optimize the query
# # losses across all of the tasks sampled in this batch.
# # This unrolls through the gradient steps.
# # qry_loss.backward()
# meta_loss += qry_loss
#
# qry_losses = sum(qry_losses) / task_num
# qry_losses.backward()
# meta_opt.step()
# qry_accs = 100. * sum(qry_accs) / task_num
# i = epoch + float(batch_idx) / n_train_iter
# iter_time = time.time() - start_time
def error_unexpected_way_to_by_pass_safety():
# https://stackoverflow.com/questions/62415251/why-am-i-able-to-change-the-value-of-a-tensor-without-the-computation-graph-know
import torch
a = torch.tensor([1, 2, 3.], requires_grad=True)
# are detached tensor's leafs? yes they are
a_detached = a.detach()
# a.fill_(2) # illegal, warns you that a tensor which requires grads is used in an inplace op (so it won't be recorded in computation graph so it wont take the right derivative of the forward path as this op won't be in it)
a_detached.fill_(
2) # weird that this one is allowed, seems to allow me to bypass the error check from the previous comment...?!
print(f'a = {a}')
print(f'a_detached = {a_detached}')
a.sum().backward()
def detach_playground():
import torch
a = torch.tensor([1, 2, 3.], requires_grad=True)
# are detached tensor's leafs? yes they are
a_detached = a.detach()
print(f'a_detached.is_leaf = {a_detached.is_leaf}')
# is doing sum on the detached tensor a leaf? no
a_detached_sum = a.sum()
print(f'a_detached_sum.is_leaf = {a_detached_sum.is_leaf}')
# is detaching an intermediate tensor a leaf? yes
a_sum_detached = a.sum().detach()
print(f'a_sum_detached.is_leaf = {a_sum_detached.is_leaf}')
# shows they share they same data
print(f'a == a_detached = {a == a_detached}')
print(f'a is a_detached = {a is a_detached}')
a_detached.zero_()
print(f'a = {a}')
print(f'a_detached = {a_detached}')
# a.fill_(2) # illegal, warns you that a tensor which requires grads is used in an inplace op (so it won't be recorded in computation graph so it wont take the right derivative of the forward path as this op won't be in it)
a_detached.fill_(
2) # weird that this one is allowed, seems to allow me to bypass the error check from the previous comment...?!
print(f'a = {a}')
print(f'a_detached = {a_detached}')
## conclusion: detach basically creates a totally new tensor which cuts gradient computations to the original but shares the same memory with original
out = a.sigmoid()
out_detached = out.detach()
out_detached.zero_()
out.sum().backward()
def clone_playground():
import torch
a = torch.tensor([1, 2, 3.], requires_grad=True)
a_clone = a.clone()
print(f'a_clone.is_leaf = {a_clone.is_leaf}')
print(f'a is a_clone = {a is a_clone}')
print(f'a == a_clone = {a == a_clone}')
print(f'a = {a}')
print(f'a_clone = {a_clone}')
# a_clone.fill_(2)
a_clone.mul_(2)
print(f'a = {a}')
print(f'a_clone = {a_clone}')
a_clone.sum().backward()
print(f'a.grad = {a.grad}')
def clone_vs_deepcopy():
import copy
import torch
x = torch.tensor([1, 2, 3.])
x_clone = x.clone()
x_deep_copy = copy.deepcopy(x)
#
x.mul_(-1)
print(f'x = {x}')
print(f'x_clone = {x_clone}')
print(f'x_deep_copy = {x_deep_copy}')
print()
def inplace_playground():
import torch
x = torch.tensor([1, 2, 3.], requires_grad=True)
y = x + 1
print(f'x.is_leaf = {x.is_leaf}')
print(f'y.is_leaf = {y.is_leaf}')
x += 1 # not allowed because x is a leaf, since changing the value of a leaf with an inplace forgets it's value then backward wouldn't work IMO (though its not the official response)
print(f'x.is_leaf = {x.is_leaf}')
def copy_initial_weights_playground_original():
import torch
import torch.nn as nn
import torch.optim as optim
import higher
import numpy as np
np.random.seed(1)
torch.manual_seed(3)
N = 100
actual_multiplier = 3.5
meta_lr = 0.00001
loops = 5 # how many iterations in the inner loop we want to do
x = torch.tensor(np.random.random((N, 1)), dtype=torch.float64) # features for inner training loop
y = x * actual_multiplier # target for inner training loop
model = nn.Linear(1, 1, bias=False).double() # simplest possible model - multiple input x by weight w without bias
meta_opt = optim.SGD(model.parameters(), lr=meta_lr, momentum=0.)
def run_inner_loop_once(model, verbose, copy_initial_weights):
lr_tensor = torch.tensor([0.3], requires_grad=True)
momentum_tensor = torch.tensor([0.5], requires_grad=True)
opt = optim.SGD(model.parameters(), lr=0.3, momentum=0.5)
with higher.innerloop_ctx(model, opt, copy_initial_weights=copy_initial_weights,
override={'lr': lr_tensor, 'momentum': momentum_tensor}) as (fmodel, diffopt):
for j in range(loops):
if verbose:
print('Starting inner loop step j=={0}'.format(j))
print(' Representation of fmodel.parameters(time={0}): {1}'.format(j, str(
list(fmodel.parameters(time=j)))))
print(' Notice that fmodel.parameters() is same as fmodel.parameters(time={0}): {1}'.format(j, (
list(fmodel.parameters())[0] is list(fmodel.parameters(time=j))[0])))
out = fmodel(x)
if verbose:
print(
' Notice how `out` is `x` multiplied by the latest version of weight: {0:.4} * {1:.4} == {2:.4}'.format(
x[0, 0].item(), list(fmodel.parameters())[0].item(), out[0].item()))
loss = ((out - y) ** 2).mean()
diffopt.step(loss)
if verbose:
# after all inner training let's see all steps' parameter tensors
print()
print("Let's print all intermediate parameters versions after inner loop is done:")
for j in range(loops + 1):
print(' For j=={0} parameter is: {1}'.format(j, str(list(fmodel.parameters(time=j)))))
print()
# let's imagine now that our meta-learning optimization is trying to check how far we got in the end from the actual_multiplier
weight_learned_after_full_inner_loop = list(fmodel.parameters())[0]
meta_loss = (weight_learned_after_full_inner_loop - actual_multiplier) ** 2
print(' Final meta-loss: {0}'.format(meta_loss.item()))
meta_loss.backward() # will only propagate gradient to original model parameter's `grad` if copy_initial_weight=False
if verbose:
print(' Gradient of final loss we got for lr and momentum: {0} and {1}'.format(lr_tensor.grad,
momentum_tensor.grad))
print(
' If you change number of iterations "loops" to much larger number final loss will be stable and the values above will be smaller')
return meta_loss.item()
print('=================== Run Inner Loop First Time (copy_initial_weights=True) =================\n')
meta_loss_val1 = run_inner_loop_once(model, verbose=True, copy_initial_weights=True)
print("\nLet's see if we got any gradient for initial model parameters: {0}\n".format(
list(model.parameters())[0].grad))
print('=================== Run Inner Loop Second Time (copy_initial_weights=False) =================\n')
meta_loss_val2 = run_inner_loop_once(model, verbose=False, copy_initial_weights=False)
print("\nLet's see if we got any gradient for initial model parameters: {0}\n".format(
list(model.parameters())[0].grad))
print('=================== Run Inner Loop Third Time (copy_initial_weights=False) =================\n')
final_meta_gradient = list(model.parameters())[0].grad.item()
# Now let's double-check `higher` library is actually doing what it promised to do, not just giving us
# a bunch of hand-wavy statements and difficult to read code.
# We will do a simple SGD step using meta_opt changing initial weight for the training and see how meta loss changed
meta_opt.step()
meta_opt.zero_grad()
meta_step = - meta_lr * final_meta_gradient # how much meta_opt actually shifted inital weight value
meta_loss_val3 = run_inner_loop_once(model, verbose=False, copy_initial_weights=False)
def copy_initial_weights_playground():
import torch
import torch.nn as nn
import torch.optim as optim
import higher
import numpy as np
np.random.seed(1)
torch.manual_seed(3)
N = 100
actual_multiplier = 3.5 # the parameters we want the model to learn
meta_lr = 0.00001
loops = 5 # how many iterations in the inner loop we want to do
x = torch.randn(N, 1) # features for inner training loop
y = x * actual_multiplier # target for inner training loop
model = nn.Linear(1, 1,
bias=False) # model(x) = w*x, simplest possible model - multiple input x by weight w without bias. goal is to w~~actualy_multiplier
outer_opt = optim.SGD(model.parameters(), lr=meta_lr, momentum=0.)
def run_inner_loop_once(model, verbose, copy_initial_weights):
lr_tensor = torch.tensor([0.3], requires_grad=True)
momentum_tensor = torch.tensor([0.5], requires_grad=True)
inner_opt = optim.SGD(model.parameters(), lr=0.3, momentum=0.5)
with higher.innerloop_ctx(model, inner_opt, copy_initial_weights=copy_initial_weights,
override={'lr': lr_tensor, 'momentum': momentum_tensor}) as (fmodel, diffopt):
for j in range(loops):
if verbose:
print('Starting inner loop step j=={0}'.format(j))
print(' Representation of fmodel.parameters(time={0}): {1}'.format(j, str(
list(fmodel.parameters(time=j)))))
print(' Notice that fmodel.parameters() is same as fmodel.parameters(time={0}): {1}'.format(j, (
list(fmodel.parameters())[0] is list(fmodel.parameters(time=j))[0])))
out = fmodel(x)
if verbose:
print(
f' Notice how `out` is `x` multiplied by the latest version of weight: {x[0, 0].item()} * {list(fmodel.parameters())[0].item()} == {out[0].item()}')
loss = ((out - y) ** 2).mean()
diffopt.step(loss)
if verbose:
# after all inner training let's see all steps' parameter tensors
print()
print("Let's print all intermediate parameters versions after inner loop is done:")
for j in range(loops + 1):
print(' For j=={0} parameter is: {1}'.format(j, str(list(fmodel.parameters(time=j)))))
print()
# let's imagine now that our meta-learning optimization is trying to check how far we got in the end from the actual_multiplier
weight_learned_after_full_inner_loop = list(fmodel.parameters())[0]
meta_loss = (weight_learned_after_full_inner_loop - actual_multiplier) ** 2
print(' Final meta-loss: {0}'.format(meta_loss.item()))
meta_loss.backward() # will only propagate gradient to original model parameter's `grad` if copy_initial_weight=False
if verbose:
print(' Gradient of final loss we got for lr and momentum: {0} and {1}'.format(lr_tensor.grad,
momentum_tensor.grad))
print(
' If you change number of iterations "loops" to much larger number final loss will be stable and the values above will be smaller')
return meta_loss.item()
print('=================== Run Inner Loop First Time (copy_initial_weights=True) =================\n')
meta_loss_val1 = run_inner_loop_once(model, verbose=True, copy_initial_weights=True)
print("\nLet's see if we got any gradient for initial model parameters: {0}\n".format(
list(model.parameters())[0].grad))
print('=================== Run Inner Loop Second Time (copy_initial_weights=False) =================\n')
meta_loss_val2 = run_inner_loop_once(model, verbose=False, copy_initial_weights=False)
print("\nLet's see if we got any gradient for initial model parameters: {0}\n".format(
list(model.parameters())[0].grad))
print('=================== Run Inner Loop Third Time (copy_initial_weights=False) =================\n')
final_meta_gradient = list(model.parameters())[0].grad.item()
# Now let's double-check `higher` library is actually doing what it promised to do, not just giving us
# a bunch of hand-wavy statements and difficult to read code.
# We will do a simple SGD step using meta_opt changing initial weight for the training and see how meta loss changed
outer_opt.step()
outer_opt.zero_grad()
meta_step = - meta_lr * final_meta_gradient # how much meta_opt actually shifted inital weight value
meta_loss_val3 = run_inner_loop_once(model, verbose=False, copy_initial_weights=False)
meta_loss_gradient_approximation = (meta_loss_val3 - meta_loss_val2) / meta_step
print()
print(
'Side-by-side meta_loss_gradient_approximation and gradient computed by `higher` lib: {0:.4} VS {1:.4}'.format(
meta_loss_gradient_approximation, final_meta_gradient))
def tqdm_torchmeta():
from torchvision.transforms import Compose, Resize, ToTensor
import torchmeta
from torchmeta.datasets.helpers import miniimagenet
from pathlib import Path
from types import SimpleNamespace
from tqdm import tqdm
## get args
args = SimpleNamespace(episodes=5, n_classes=5, k_shot=5, k_eval=15, meta_batch_size=1, n_workers=4)
args.data_root = Path("~/automl-meta-learning/data/miniImagenet").expanduser()
## get meta-batch loader
train_transform = Compose([Resize(84), ToTensor()])
dataset = miniimagenet(
args.data_root,
ways=args.n_classes,
shots=args.k_shot,
test_shots=args.k_eval,
meta_split='train',
download=False)
dataloader = torchmeta.utils.data.BatchMetaDataLoader(
dataset,
batch_size=args.meta_batch_size,
num_workers=args.n_workers)
with tqdm(dataset):
print(f'len(dataloader)= {len(dataloader)}')
for episode, batch in enumerate(dataloader):
print(f'episode = {episode}')
train_inputs, train_labels = batch["train"]
print(f'train_labels[0] = {train_labels[0]}')
print(f'train_inputs.size() = {train_inputs.size()}')
pass
if episode >= args.episodes:
break
# if __name__ == "__main__":
# start = time.time()
# print('pytorch playground!')
# # params_in_comp_graph()
# # check_if_tensor_is_detached()
# # deep_copy_issue()
# # download_mini_imagenet()
# # extract()
# # download_and_extract_miniImagenet(root='~/tmp')
# # download_and_extract_miniImagenet(root='~/automl-meta-learning/data')
# # torch_concat()
# # detach_vs_cloe()
# # error_unexpected_way_to_by_pass_safety()
# # clone_playground()
# # inplace_playground()
# # clone_vs_deepcopy()
# # copy_initial_weights_playground()
# tqdm_torchmeta()
# print('--> DONE')
# time_passed_msg, _, _, _ = report_times(start)
# print(f'--> {time_passed_msg}')
# %%
import sys
print(sys.version) ##
print(sys.path)
def helloworld():
print('helloworld')
print('hello12345')
def union_dicts():
d1 = {'x': 1}
d2 = {'y': 2, 'z': 3}
d_union = {**d1, **d2}
print(d_union)
def get_stdout_old():
import sys
# contents = ""
# #with open('some_file.txt') as f:
# #with open(sys.stdout,'r') as f:
# # sys.stdout.mode = 'r'
# for line in sys.stdout.readlines():
# contents += line
# print(contents)
# print(sys.stdout)
# with open(sys.stdout.buffer) as f:
# print(f.readline())
# import subprocess
# p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
# stdout = []
# while True:
# line = p.stdout.readline()
# stdout.append(line)
# print( line )
# if line == '' and p.poll() != None:
# break
# print( ''.join(stdout) )
import sys
myfile = "input.txt"
def print(*args):
__builtins__.print(*args, file=sys.__stdout__)
with open(myfile, "a+") as f:
__builtins__.print(*args, file=f)
print('a')
print('b')
print('c')
repr(sys.stdout)
def get_stdout():
import sys
myfile = "my_stdout.txt"
# redefine print
def print(*args):
__builtins__.print(*args, file=sys.__stdout__) # prints to terminal
with open(myfile, "a+") as f:
__builtins__.print(*args, file=f) # saves in a file
print('a')
print('b')
print('c')
def logging_basic():
import logging
logging.warning('Watch out!') # will print a message to the console
logging.info('I told you so') # will not print anything
def logging_to_file():
import logging
logging.basicConfig(filename='example.log', level=logging.DEBUG)
# logging.
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
def logging_to_file_INFO_LEVEL():
import logging
import sys
format = '{asctime}:{levelname}:{name}:lineno {lineno}:{message}'
logging.basicConfig(filename='example.log', level=logging.INFO, format=format, style='{')
# logging.basicConfig(stream=sys.stdout,level=logging.INFO,format=format,style='{')
# logging.
logging.debug('This message should NOT go to the log file')
logging.info('This message should go to log file')
logging.warning('This, too')
def logger_SO_print_and_write_to_my_stdout():
"""My sample logger code to print to screen and write to file (the same thing).
Note: trying to replace this old answer of mine using a logger:
- https://github.com/CoreyMSchafer/code_snippets/tree/master/Logging-Advanced
Credit:
- https://www.youtube.com/watch?v=jxmzY9soFXg&t=468s
- https://github.com/CoreyMSchafer/code_snippets/tree/master/Logging-Advanced
- https://stackoverflow.com/questions/21494468/about-notset-in-python-logging/21494716#21494716
Other resources:
- https://docs.python-guide.org/writing/logging/
- https://docs.python.org/3/howto/logging.html#logging-basic-tutorial
- https://stackoverflow.com/questions/61084916/how-does-one-make-an-already-opened-file-readable-e-g-sys-stdout/61255375#61255375
"""
from pathlib import Path
import logging
import os
import sys
from datetime import datetime
## create directory (& its parents) if it does not exist otherwise do nothing :)
# get current time
current_time = datetime.now().strftime('%b%d_%H-%M-%S')
logs_dirpath = Path(f'~/logs/python_playground_logs_{current_time}/').expanduser()
logs_dirpath.mkdir(parents=True, exist_ok=True)
my_stdout_filename = logs_dirpath / Path('my_stdout.log')
# remove my_stdout if it exists (note you can also just create a new log dir/file each time or append to the end of the log file your using)
# os.remove(my_stdout_filename) if os.path.isfile(my_stdout_filename) else None
## create top logger
logger = logging.getLogger(
__name__) # loggers are created in hierarchy using dot notation, thus __name__ ensures no name collisions.
logger.setLevel(
logging.DEBUG) # note: use logging.DEBUG, CAREFUL with logging.UNSET: https://stackoverflow.com/questions/21494468/about-notset-in-python-logging/21494716#21494716
## log to my_stdout.log file
file_handler = logging.FileHandler(filename=my_stdout_filename)
# file_handler.setLevel(logging.INFO) # not setting it means it inherits the logger. It will log everything from DEBUG upwards in severity to this handler.
log_format = "{asctime}:{levelname}:{lineno}:{name}:{message}" # see for logrecord attributes https://docs.python.org/3/library/logging.html#logrecord-attributes
formatter = logging.Formatter(fmt=log_format, style='{') # set the logging format at for this handler
file_handler.setFormatter(fmt=formatter)
## log to stdout/screen
stdout_stream_handler = logging.StreamHandler(
stream=sys.stdout) # default stderr, though not sure the advatages of logging to one or the other
# stdout_stream_handler.setLevel(logging.INFO) # Note: having different set levels means that we can route using a threshold what gets logged to this handler
log_format = "{name}:{levelname}:-> {message}" # see for logrecord attributes https://docs.python.org/3/library/logging.html#logrecord-attributes
formatter = logging.Formatter(fmt=log_format, style='{') # set the logging format at for this handler
stdout_stream_handler.setFormatter(fmt=formatter)
logger.addHandler(hdlr=file_handler) # add this file handler to top logger
logger.addHandler(hdlr=stdout_stream_handler) # add this file handler to top logger
logger.log(logging.NOTSET, 'notset')
logger.debug('debug')
logger.info('info')
logger.warning('warning')
logger.error('error')
logger.critical('critical')
def logging_unset_level():
"""My sample logger explaining UNSET level
Resources:
- https://stackoverflow.com/questions/21494468/about-notset-in-python-logging
- https://www.youtube.com/watch?v=jxmzY9soFXg&t=468s
- https://github.com/CoreyMSchafer/code_snippets/tree/master/Logging-Advanced
"""
import logging
logger = logging.getLogger(
__name__) # loggers are created in hierarchy using dot notation, thus __name__ ensures no name collisions.
print(f'DEFAULT VALUE: logger.level = {logger.level}')
file_handler = logging.FileHandler(filename='my_log.log')
log_format = "{asctime}:{levelname}:{lineno}:{name}:{message}" # see for logrecord attributes https://docs.python.org/3/library/logging.html#logrecord-attributes
formatter = logging.Formatter(fmt=log_format, style='{')
file_handler.setFormatter(fmt=formatter)
stdout_stream_handler = logging.StreamHandler(stream=sys.stdout)
stdout_stream_handler.setLevel(logging.INFO)
log_format = "{name}:{levelname}:-> {message}" # see for logrecord attributes https://docs.python.org/3/library/logging.html#logrecord-attributes
formatter = logging.Formatter(fmt=log_format, style='{')
stdout_stream_handler.setFormatter(fmt=formatter)
logger.addHandler(hdlr=file_handler)
logger.addHandler(hdlr=stdout_stream_handler)
logger.log(logging.NOTSET, 'notset')
logger.debug('debug')
logger.info('info')
logger.warning('warning')
logger.error('error')
logger.critical('critical')
def logger():
from pathlib import Path
import logging
# create directory (& its parents) if it does not exist otherwise do nothing :)
logs_dirpath = Path('~/automl-meta-learning/logs/python_playground_logs/').expanduser()
logs_dirpath.mkdir(parents=True, exist_ok=True)
my_stdout_filename = logs_dirpath / Path('my_stdout.log')
# remove my_stdout if it exists (used to have this but now I decided to create a new log & file each)
# os.remove(my_stdout_filename) if os.path.isfile(my_stdout_filename) else None
logger = logging.getLogger(
__name__) # loggers are created in hierarchy using dot notation, thus __name__ ensures no name collisions.
logger.setLevel(logging.INFO)
log_format = "{asctime}:{levelname}:{name}:{message}"
formatter = logging.Formatter(fmt=log_format, style='{')
file_handler = logging.FileHandler(filename=my_stdout_filename)
file_handler.setFormatter(fmt=formatter)
logger.addHandler(hdlr=file_handler)
logger.addHandler(hdlr=logging.StreamHandler())
for i in range(3):
logger.info(f'i = {i}')
logger.info(f'logger DONE')
def logging_example_from_youtube():
"""https://github.com/CoreyMSchafer/code_snippets/blob/master/Logging-Advanced/employee.py
"""
import logging
# import pytorch_playground # has employee class & code
import sys
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(name)s:%(message)s')
file_handler = logging.FileHandler('sample.log')
file_handler.setLevel(logging.ERROR)
file_handler.setFormatter(formatter)
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.addHandler(stream_handler)
logger.critical('not really critical :P')
def add(x, y):
"""Add Function"""
return x + y
def subtract(x, y):
"""Subtract Function"""
return x - y
def multiply(x, y):
"""Multiply Function"""
return x * y
def divide(x, y):
"""Divide Function"""
try:
result = x / y
except ZeroDivisionError:
logger.exception('Tried to divide by zero')
else:
return result
logger.info(
'testing if log info is going to print to screen. it should because everything with debug or above is printed since that stream has that level.')
num_1 = 10
num_2 = 0
add_result = add(num_1, num_2)
logger.debug('Add: {} + {} = {}'.format(num_1, num_2, add_result))
sub_result = subtract(num_1, num_2)
logger.debug('Sub: {} - {} = {}'.format(num_1, num_2, sub_result))
mul_result = multiply(num_1, num_2)
logger.debug('Mul: {} * {} = {}'.format(num_1, num_2, mul_result))
div_result = divide(num_1, num_2)
logger.debug('Div: {} / {} = {}'.format(num_1, num_2, div_result))
def plot():
"""
source:
- https://www.youtube.com/watch?v=UO98lJQ3QGI
- https://github.com/CoreyMSchafer/code_snippets/blob/master/Python/Matplotlib/01-Introduction/finished_code.py
"""
from matplotlib import pyplot as plt
plt.xkcd()
ages_x = [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]
py_dev_y = [20046, 17100, 20000, 24744, 30500, 37732, 41247, 45372, 48876, 53850, 57287, 63016, 65998, 70003, 70000,
71496, 75370, 83640, 84666,
84392, 78254, 85000, 87038, 91991, 100000, 94796, 97962, 93302, 99240, 102736, 112285, 100771, 104708,
108423, 101407, 112542, 122870, 120000]
plt.plot(ages_x, py_dev_y, label='Python')
js_dev_y = [16446, 16791, 18942, 21780, 25704, 29000, 34372, 37810, 43515, 46823, 49293, 53437, 56373, 62375, 66674,
68745, 68746, 74583, 79000,
78508, 79996, 80403, 83820, 88833, 91660, 87892, 96243, 90000, 99313, 91660, 102264, 100000, 100000,
91660, 99240, 108000, 105000, 104000]
plt.plot(ages_x, js_dev_y, label='JavaScript')
dev_y = [17784, 16500, 18012, 20628, 25206, 30252, 34368, 38496, 42000, 46752, 49320, 53200, 56000, 62316, 64928,
67317, 68748, 73752, 77232,
78000, 78508, 79536, 82488, 88935, 90000, 90056, 95000, 90000, 91633, 91660, 98150, 98964, 100000, 98988,
100000, 108923, 105000, 103117]
plt.plot(ages_x, dev_y, color='#444444', linestyle='--', label='All Devs')
plt.xlabel('Ages')
plt.ylabel('Median Salary (USD)')
plt.title('Median Salary (USD) by Age')
plt.legend()
plt.tight_layout()
plt.savefig('plot.png')
plt.show()
def subplot():
"""https://github.com/CoreyMSchafer/code_snippets/blob/master/Python/Matplotlib/10-Subplots/finished_code.py
"""
import pandas as pd
from matplotlib import pyplot as plt
plt.style.use('seaborn')
data = read_csv('data.csv')
ages = data['Age']
dev_salaries = data['All_Devs']
py_salaries = data['Python']
js_salaries = data['JavaScript']
fig1, ax1 = plt.subplots()
fig2, ax2 = plt.subplots()
ax1.plot(ages, dev_salaries, color='#444444',
linestyle='--', label='All Devs')
ax2.plot(ages, py_salaries, label='Python')
ax2.plot(ages, js_salaries, label='JavaScript')
ax1.legend()
ax1.set_title('Median Salary (USD) by Age')
ax1.set_ylabel('Median Salary (USD)')
ax2.legend()
ax2.set_xlabel('Ages')
ax2.set_ylabel('Median Salary (USD)')
plt.tight_layout()
plt.show()
fig1.savefig('fig1.png')
fig2.savefig('fig2.png')
#
# def import_utils_test():
# import uutils
# # import uutils.utils as utils
# # from uutils.utils import logger
#
# print(uutils)
# print(utils)
# print(logger)
#
# print()
def sys_path():
"""
python -c "import sys; print(sys.path)”