File size: 51,401 Bytes
e065c61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
"""
megatrain_utils.py

Plain-PyTorch memory utilities for single-GPU training, with GH200-friendly
CPU staging and selective activation offload.

Keeps:
- module parking / restore
- optimizer-state + master-param parking / restore
- grouped training-state parking
- memory reporting

Adds:
- activation offload via autograd saved_tensors_hooks
- optional built-in save_on_cpu mode
- selective wrapping of expensive modules
- optional checkpointing for wrapped modules
"""

from __future__ import annotations

from contextlib import contextmanager
from dataclasses import dataclass, field
from typing import Any, Iterable, Optional, Sequence

import torch.utils.checkpoint as checkpoint

import psutil
import torch
from accelerate import logging
from accelerate.utils.versions import is_torch_version
from torch import nn
from torch.autograd.graph import saved_tensors_hooks
from transformers import is_torch_npu_available


CPU_DEVICE = torch.device("cpu")


# ---------------------------------------------------------------------------
# Generic helpers
# ---------------------------------------------------------------------------

def _is_tensor(x: Any) -> bool:
    return isinstance(x, torch.Tensor)


def _tensor_nbytes(t: torch.Tensor) -> int:
    return t.numel() * t.element_size()


def _nested_tensor_nbytes(obj: Any) -> int:
    if _is_tensor(obj):
        return _tensor_nbytes(obj)
    if isinstance(obj, dict):
        return sum(_nested_tensor_nbytes(v) for v in obj.values())
    if isinstance(obj, (list, tuple, set)):
        return sum(_nested_tensor_nbytes(v) for v in obj)
    return 0


def _pin_if_possible(t: torch.Tensor, pin_memory: bool) -> torch.Tensor:
    if not pin_memory:
        return t
    if t.device.type != "cpu":
        return t
    try:
        return t.pin_memory()
    except RuntimeError:
        return t


def _to_cpu_tensor(t: torch.Tensor, pin_memory: bool) -> torch.Tensor:
    out = t.detach().to("cpu")
    return _pin_if_possible(out, pin_memory=pin_memory)


def _to_device_tensor(
    t: torch.Tensor,
    device: torch.device | str,
    non_blocking: bool,
) -> torch.Tensor:
    return t.to(device=device, non_blocking=non_blocking)


def _infer_module_device(module: nn.Module) -> torch.device:
    for p in module.parameters():
        return p.device
    for b in module.buffers():
        return b.device
    return CPU_DEVICE


def _infer_optimizer_device(optimizer: torch.optim.Optimizer) -> torch.device:
    for group in optimizer.param_groups:
        for p in group["params"]:
            if isinstance(p, torch.Tensor):
                return p.device
    return torch.device("cuda" if torch.cuda.is_available() else "cpu")


def _resolve_tensor_by_name(mapping: dict[str, torch.Tensor], name: str) -> Optional[torch.Tensor]:
    return mapping.get(name, None)


def _move_container_tensors_inplace(
    obj: Any,
    *,
    to_cpu: bool,
    device: torch.device | str,
    pin_memory: bool,
    non_blocking: bool,
) -> Any:
    if _is_tensor(obj):
        if to_cpu:
            return _to_cpu_tensor(obj, pin_memory=pin_memory)
        return _to_device_tensor(obj, device=device, non_blocking=non_blocking)

    if isinstance(obj, dict):
        for k, v in list(obj.items()):
            obj[k] = _move_container_tensors_inplace(
                v,
                to_cpu=to_cpu,
                device=device,
                pin_memory=pin_memory,
                non_blocking=non_blocking,
            )
        return obj

    if isinstance(obj, list):
        for i, v in enumerate(obj):
            obj[i] = _move_container_tensors_inplace(
                v,
                to_cpu=to_cpu,
                device=device,
                pin_memory=pin_memory,
                non_blocking=non_blocking,
            )
        return obj

    if isinstance(obj, tuple):
        return tuple(
            _move_container_tensors_inplace(
                v,
                to_cpu=to_cpu,
                device=device,
                pin_memory=pin_memory,
                non_blocking=non_blocking,
            )
            for v in obj
        )

    if isinstance(obj, set):
        return {
            _move_container_tensors_inplace(
                v,
                to_cpu=to_cpu,
                device=device,
                pin_memory=pin_memory,
                non_blocking=non_blocking,
            )
            for v in obj
        }

    return obj


# ---------------------------------------------------------------------------
# Parking handles
# ---------------------------------------------------------------------------

@dataclass
class ModuleParkingHandle:
    param_names: list[str] = field(default_factory=list)
    grad_names: list[str] = field(default_factory=list)
    buffer_names: list[str] = field(default_factory=list)

    param_devices: dict[str, torch.device] = field(default_factory=dict)
    grad_devices: dict[str, torch.device] = field(default_factory=dict)
    buffer_devices: dict[str, torch.device] = field(default_factory=dict)

    bytes_moved: int = 0


@dataclass
class OptimizerParkingHandle:
    original_device: torch.device
    extra_attr_names: list[str] = field(default_factory=list)
    bytes_moved: int = 0


@dataclass
class TrainingParkingHandle:
    module_handles: dict[str, ModuleParkingHandle] = field(default_factory=dict)
    optimizer_handle: Optional[OptimizerParkingHandle] = None


# ---------------------------------------------------------------------------
# Module parking / restore
# ---------------------------------------------------------------------------

@torch.no_grad()
def module_nbytes(
    module: nn.Module,
    *,
    include_grad: bool = True,
    include_buffers: bool = True,
    only_trainable: bool = False,
    only_frozen: bool = False,
) -> int:
    total = 0

    for p in module.parameters():
        if only_trainable and not p.requires_grad:
            continue
        if only_frozen and p.requires_grad:
            continue
        total += _tensor_nbytes(p.data)
        if include_grad and p.grad is not None:
            total += _tensor_nbytes(p.grad)

    if include_buffers:
        for b in module.buffers():
            total += _tensor_nbytes(b)

    return total


@torch.no_grad()
def park_module_to_cpu(
    module: nn.Module,
    *,
    include_buffers: bool = True,
    include_grads: bool = False,
    only_frozen: bool = False,
    only_trainable: bool = False,
    pin_memory: bool = True,
) -> ModuleParkingHandle:
    if only_frozen and only_trainable:
        raise ValueError("only_frozen and only_trainable cannot both be True")

    handle = ModuleParkingHandle()

    for name, p in module.named_parameters(recurse=True):
        if only_frozen and p.requires_grad:
            continue
        if only_trainable and not p.requires_grad:
            continue

        handle.param_names.append(name)
        handle.param_devices[name] = p.device
        handle.bytes_moved += _tensor_nbytes(p.data)
        p.data = _to_cpu_tensor(p.data, pin_memory=pin_memory)

        if include_grads and p.grad is not None:
            handle.grad_names.append(name)
            handle.grad_devices[name] = p.grad.device
            handle.bytes_moved += _tensor_nbytes(p.grad)
            p.grad = _to_cpu_tensor(p.grad, pin_memory=pin_memory)

    if include_buffers:
        for name, b in module.named_buffers(recurse=True):
            if b is None:
                continue
            handle.buffer_names.append(name)
            handle.buffer_devices[name] = b.device
            handle.bytes_moved += _tensor_nbytes(b)
            b.data = _to_cpu_tensor(b.data, pin_memory=pin_memory)

    return handle


@torch.no_grad()
def restore_module_from_cpu(
    module: nn.Module,
    handle: ModuleParkingHandle,
    *,
    device: torch.device | str | None = None,
    non_blocking: bool = True,
) -> None:
    named_params = dict(module.named_parameters(recurse=True))
    named_buffers = dict(module.named_buffers(recurse=True))

    for name in handle.param_names:
        p = _resolve_tensor_by_name(named_params, name)
        if p is None:
            continue
        target_device = device if device is not None else handle.param_devices[name]
        p.data = _to_device_tensor(p.data, target_device, non_blocking=non_blocking)

    for name in handle.grad_names:
        p = _resolve_tensor_by_name(named_params, name)
        if p is None or p.grad is None:
            continue
        target_device = device if device is not None else handle.grad_devices[name]
        p.grad = _to_device_tensor(p.grad, target_device, non_blocking=non_blocking)

    for name in handle.buffer_names:
        b = _resolve_tensor_by_name(named_buffers, name)
        if b is None:
            continue
        target_device = device if device is not None else handle.buffer_devices[name]
        b.data = _to_device_tensor(b.data, target_device, non_blocking=non_blocking)


@contextmanager
def parked_module(
    module: nn.Module,
    *,
    include_buffers: bool = True,
    include_grads: bool = False,
    only_frozen: bool = False,
    only_trainable: bool = False,
    pin_memory: bool = True,
    restore_device: torch.device | str | None = None,
    non_blocking: bool = True,
):
    handle = park_module_to_cpu(
        module,
        include_buffers=include_buffers,
        include_grads=include_grads,
        only_frozen=only_frozen,
        only_trainable=only_trainable,
        pin_memory=pin_memory,
    )
    try:
        yield handle
    finally:
        restore_module_from_cpu(
            module,
            handle,
            device=restore_device,
            non_blocking=non_blocking,
        )


# ---------------------------------------------------------------------------
# Optimizer parking / restore
# ---------------------------------------------------------------------------

_COMMON_MASTER_PARAM_ATTRS = (
    "shard_fp32_from_float16_groups",
    "fp32_from_fp16_groups",
    "master_params",
    "main_params",
)


@torch.no_grad()
def optimizer_state_nbytes(optimizer: torch.optim.Optimizer) -> int:
    total = 0
    for state in optimizer.state.values():
        total += _nested_tensor_nbytes(state)
    return total


@torch.no_grad()
def park_optimizer_state_to_cpu(
    optimizer: torch.optim.Optimizer,
    *,
    pin_memory: bool = True,
    include_master_params: bool = True,
) -> OptimizerParkingHandle:
    original_device = _infer_optimizer_device(optimizer)
    handle = OptimizerParkingHandle(original_device=original_device)

    for state in optimizer.state.values():
        handle.bytes_moved += _nested_tensor_nbytes(state)
        _move_container_tensors_inplace(
            state,
            to_cpu=True,
            device=CPU_DEVICE,
            pin_memory=pin_memory,
            non_blocking=False,
        )

    if include_master_params:
        for attr_name in _COMMON_MASTER_PARAM_ATTRS:
            if hasattr(optimizer, attr_name):
                attr_val = getattr(optimizer, attr_name)
                handle.bytes_moved += _nested_tensor_nbytes(attr_val)
                new_val = _move_container_tensors_inplace(
                    attr_val,
                    to_cpu=True,
                    device=CPU_DEVICE,
                    pin_memory=pin_memory,
                    non_blocking=False,
                )
                setattr(optimizer, attr_name, new_val)
                handle.extra_attr_names.append(attr_name)

    return handle


@torch.no_grad()
def restore_optimizer_state_from_cpu(
    optimizer: torch.optim.Optimizer,
    handle: OptimizerParkingHandle | None = None,
    *,
    device: torch.device | str | None = None,
    non_blocking: bool = True,
    include_master_params: bool = True,
) -> None:
    target_device = device if device is not None else (
        handle.original_device if handle is not None else _infer_optimizer_device(optimizer)
    )

    for state in optimizer.state.values():
        _move_container_tensors_inplace(
            state,
            to_cpu=False,
            device=target_device,
            pin_memory=False,
            non_blocking=non_blocking,
        )

    if include_master_params:
        attr_names: Iterable[str]
        if handle is not None:
            attr_names = handle.extra_attr_names
        else:
            attr_names = [name for name in _COMMON_MASTER_PARAM_ATTRS if hasattr(optimizer, name)]

        for attr_name in attr_names:
            if not hasattr(optimizer, attr_name):
                continue
            attr_val = getattr(optimizer, attr_name)
            new_val = _move_container_tensors_inplace(
                attr_val,
                to_cpu=False,
                device=target_device,
                pin_memory=False,
                non_blocking=non_blocking,
            )
            setattr(optimizer, attr_name, new_val)


@contextmanager
def parked_optimizer_state(
    optimizer: torch.optim.Optimizer,
    *,
    pin_memory: bool = True,
    include_master_params: bool = True,
    restore_device: torch.device | str | None = None,
    non_blocking: bool = True,
):
    handle = park_optimizer_state_to_cpu(
        optimizer,
        pin_memory=pin_memory,
        include_master_params=include_master_params,
    )
    try:
        yield handle
    finally:
        restore_optimizer_state_from_cpu(
            optimizer,
            handle,
            device=restore_device,
            non_blocking=non_blocking,
            include_master_params=include_master_params,
        )


# ---------------------------------------------------------------------------
# Grouped training-state parking
# ---------------------------------------------------------------------------

@torch.no_grad()
def park_training_state(
    *,
    modules: Optional[dict[str, nn.Module]] = None,
    optimizer: Optional[torch.optim.Optimizer] = None,
    pin_memory: bool = True,
    include_optimizer_master_params: bool = True,
    include_module_buffers: bool = True,
    include_module_grads: bool = False,
    only_frozen_modules: bool = False,
) -> TrainingParkingHandle:
    handle = TrainingParkingHandle()

    if modules:
        for name, module in modules.items():
            handle.module_handles[name] = park_module_to_cpu(
                module,
                include_buffers=include_module_buffers,
                include_grads=include_module_grads,
                only_frozen=only_frozen_modules,
                pin_memory=pin_memory,
            )

    if optimizer is not None:
        handle.optimizer_handle = park_optimizer_state_to_cpu(
            optimizer,
            pin_memory=pin_memory,
            include_master_params=include_optimizer_master_params,
        )

    return handle


@torch.no_grad()
def restore_training_state(
    handle: TrainingParkingHandle,
    *,
    modules: Optional[dict[str, nn.Module]] = None,
    optimizer: Optional[torch.optim.Optimizer] = None,
    device: torch.device | str | None = None,
    non_blocking: bool = True,
    include_optimizer_master_params: bool = True,
) -> None:
    if modules:
        for name, module in modules.items():
            if name in handle.module_handles:
                restore_module_from_cpu(
                    module,
                    handle.module_handles[name],
                    device=device,
                    non_blocking=non_blocking,
                )

    if optimizer is not None and handle.optimizer_handle is not None:
        restore_optimizer_state_from_cpu(
            optimizer,
            handle.optimizer_handle,
            device=device,
            non_blocking=non_blocking,
            include_master_params=include_optimizer_master_params,
        )

# ---------------------------------------------------------------------------
# Activation offloading, borrowed from trl
# ---------------------------------------------------------------------------


if is_torch_npu_available():
    import torch_npu  # noqa: F401

# Import DTensor for FSDP v2 support with version-aware import path
DTensor = None
if torch.distributed.is_available():
    try:
        if is_torch_version(">=", "2.5.0"):
            from torch.distributed.tensor import DTensor
        else:
            # from torch 2.0.0 (oldest supported accelerate torch version), DTensor is in torch.distributed._tensor
            from torch.distributed._tensor import DTensor
    except (ImportError, AttributeError):
        DTensor = None

logger = logging.get_logger(__name__)


def _get_unique_tensor_key(tensor: torch.Tensor) -> tuple:
    """
    Get a unique key for a tensor based on its storage pointer and dtype. This allows deduplication of tensors that
    share the same underlying storage. From:
    https://github.com/volcengine/verl/blob/main/verl/utils/activation_offload.py

    Args:
        tensor: The tensor to get the key for

    Returns:
        A tuple of (storage_pointer, dtype) that uniquely identifies the tensor's storage
    """
    # Handle special tensor types - primarily for FSDP v2 DTensor
    actual_tensor = tensor

    # For DTensor (FSDP v2), extract the local tensor
    if DTensor is not None and isinstance(tensor, DTensor) and hasattr(tensor, "_local_tensor"):
        actual_tensor = tensor._local_tensor

    # Try to get storage pointer, but fall back to tensor id if not accessible
    try:
        storage_ptr = actual_tensor.untyped_storage().data_ptr() + actual_tensor.storage_offset()
    except (RuntimeError, AttributeError):
        # For tensors with invalid storage, use tensor id
        # This won't enable deduplication for these tensors, but allows offloading to work
        storage_ptr = id(actual_tensor)

    return (storage_ptr, actual_tensor.dtype)


class OffloadActivations(saved_tensors_hooks):
    """
    Context manager under which activation tensors created in the forward pass will be offloaded.

    Enable the memory efficiency technique of activation offloading, where activations bigger than `min_offload_size`
    bytes will be offloaded to CPU in the forward and brought back in the backward. This is in contrast to maintaining
    the activation on GPU VRAM throughout the program.

    This manager contains the option of using one additional CUDA stream to handle the communication between CUDA and
    CPU, which is intended to overlap with the default computation stream to improve runtime. We designed
    synchronization with a few heuristics for optimizing the tradeoff between runtime vs memory usage.

    Args:
        use_pin_memory (`bool`, *optional*, defaults to `True`):
            Whether to offloaded Tensor will be placed in pinned memory on the CPU. Pinned memory allows the Tensor to
            be moved back onto GPU more quickly but is a limited resource.
        use_streams (`bool`, *optional*, defaults to `True`):
            Whether to use streams for performance optimization where the communications get overlapped with the
            computation. Requires a torch build after torch-2.5.0.
        min_offload_size (`int`, *optional*, defaults to `1024`):
            Minimum number of bytes a Tensor must be in order to qualify for offloading. If the tensor is too small, we
            do not want to waste bandwidth and resources moving it to CPU and back.
        max_fwd_stash_size (`int`, *optional*, defaults to `5`):
            Maximum size of the forward stash, or the maximum number of consecutive activations to keep alive during
            the forward pass. This number must be at least 1. Keeping alive more activations will potentially allow
            more overlap between the communication and compute streams at the cost of increasing memory usage. Keeping
            alive fewer activations will conserve memory, but may cause poor overlap between the streams, increasing
            runtime.

    Raises:
        ValueError: if `max_fwd_stash_size` is not at least `1`.

    Example:
    ```python
    >>> with OffloadActivations():
    ...     outputs = model(inputs, labels=labels)
    >>> loss = outputs.loss
    >>> loss.backward()
    ```
    """

    def __init__(
        self,
        use_pin_memory: bool = True,
        use_streams: bool = True,
        min_offload_size: int = 1024,
        max_fwd_stash_size: int = 5,
    ) -> None:
        self.use_streams = use_streams

        self.min_tensor_size_bytes = min_offload_size  # we don't want to bother with small tensors
        self.tracker = {}  # tensor_id => (new_tensor, if_modified)  ---> track what saved/offloaded tensors are where
        self.tensor_id = 0
        self.is_first_forward_call = True
        self.is_first_backward_call = True
        self.is_first_forward_pass = True

        # Storage deduplication: maps storage key to tensor_id to avoid offloading same storage multiple times
        self.storage_to_tensor_id = {}

        # Parameter filtering: track parameter storage pointers to skip them during offloading
        self.param_storages = set()

        # Managing cpu memory
        self.use_pin_memory = use_pin_memory
        self.virtual_memory_safe_pct = 60  # we should not exceed this percentage of memory

        self.accelerator_type = (
            torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"
        )
        # NOTE: xpu doesn't have `default_stream` API, use `current_stream` instead
        if self.accelerator_type == "xpu":  # comp stream
            self.s0 = torch.xpu.current_stream()
        elif is_torch_npu_available() and self.accelerator_type == "npu":
            self.s0 = torch.npu.current_stream()
        else:
            self.s0 = torch.cuda.default_stream()

        # For streaming
        if self.use_streams:
            if self.accelerator_type == "xpu":  # comms stream
                self.s1 = torch.xpu.Stream()
            elif self.accelerator_type == "npu":
                self.s1 = torch.npu.Stream()
            else:
                self.s1 = torch.cuda.Stream()
            self.fwd_stash = {}  # tensor_id => (activation, ev1)
            if max_fwd_stash_size < 1:
                raise ValueError(f"max_fwd_stash_size should be at least 1 but is {max_fwd_stash_size}")
            self.max_fwd_stash_size = max_fwd_stash_size
            self.bwd_tensor_stash = {}  # tensor_id => activation
            self.bwd_ev_stash = {}  # tensor_id => ev0
            self.curr_graph_id = None
            self.curr_autograd_node = None

        # -------- platform util functions -------- #
        def verify_sufficient_virtual_memory():
            curr_pct = get_cpu_ram_pct()
            if curr_pct > self.virtual_memory_safe_pct:
                logger.warning(f"{curr_pct=}% > {self.virtual_memory_safe_pct=}% of virtual memory used")

        def get_cpu_ram_pct() -> float:
            # get the percentage of memory used by the system
            return psutil.virtual_memory().percent

        def get_tensor_id() -> int:
            # create a unique id for each tensor we are managing
            self.tensor_id += 1
            return self.tensor_id

        def get_num_bytes_tensor(x: torch.Tensor) -> int:
            # get the number of bytes in a tensor, for memory management purposes
            return x.element_size() * x.nelement()  # x.element_size() * x._base_storage().nbytes()

        # -------- core pack / unpack work -------- #
        def pack_tensor(activation: torch.Tensor) -> int:
            # activations are passed in during forward pass - from here we take over and return a unique id
            if self.is_first_forward_call:
                if len(self.tracker) != 0:
                    raise ValueError("Backward pass should have cleared tracker of all tensors")

                # set training phase trackers
                self.is_first_forward_call = False
                self.is_first_backward_call = True
                # Reset deduplication map for new forward pass
                self.storage_to_tensor_id = {}

            # query for basic tensor info
            num_bytes = get_num_bytes_tensor(activation)
            tensor_id = get_tensor_id()

            # Check for tensor deduplication using storage pointer
            # If this storage is already being tracked, we still create a new tensor_id
            # but don't offload again (just keep the tensor in GPU)
            storage_key = _get_unique_tensor_key(activation)
            if storage_key in self.storage_to_tensor_id:
                # Storage already offloaded - don't offload again, just track the reference
                self.tracker[tensor_id] = (activation, False, None, None, None)  # Keep on GPU, don't offload
                return tensor_id

            # Check if tensor is on CPU (skip offloading)
            if activation.device.type not in ["cuda", "xpu", "npu"]:
                self.tracker[tensor_id] = (activation, False, None, None, None)
                return tensor_id

            # Check if tensor is too small
            if num_bytes < self.min_tensor_size_bytes:
                self.tracker[tensor_id] = (activation, False, None, None, None)
                return tensor_id

            # Check if tensor is a parameter or buffer
            if isinstance(activation, torch.nn.Parameter) or (
                hasattr(torch.nn, "Buffer") and isinstance(activation, torch.nn.Buffer)
            ):
                self.tracker[tensor_id] = (activation, False, None, None, None)
                return tensor_id

            # Check if tensor is an FP8 tensor (TorchAO) - skip offloading as they're already compressed
            tensor_class_name = type(activation).__name__
            if tensor_class_name in ["Float8TrainingTensor", "ScaledMMConfig", "LinearMMConfig"]:
                self.tracker[tensor_id] = (activation, False, None, None, None)
                return tensor_id

            # Check if tensor storage is a model parameter (for FSDP compatibility)
            try:
                # Extract actual tensor for DTensor
                check_tensor = activation
                if DTensor is not None and isinstance(activation, DTensor) and hasattr(activation, "_local_tensor"):
                    check_tensor = activation._local_tensor

                if check_tensor.untyped_storage().data_ptr() in self.param_storages:
                    self.tracker[tensor_id] = (activation, False, None, None, None)
                    return tensor_id
            except (RuntimeError, AttributeError):
                # If we can't get data_ptr, skip this check
                pass

            # Tensor qualifies for offloading
            if self.use_streams:
                # First, sync back and dereference previously offloaded tensors
                # as the offloading should be done sufficiently long ago.
                for id in list(self.fwd_stash.keys()):
                    if id <= tensor_id - self.max_fwd_stash_size:
                        _, ev = self.fwd_stash[id]
                        self.s0.wait_event(ev)
                        del self.fwd_stash[id]
                    else:
                        break

                # Sync in, offload, and add an event to sync back later
                self.s1.wait_stream(self.s0)

            stream = self.s1 if self.use_streams else self.s0
            if self.accelerator_type == "xpu":
                stream_ctx = torch.xpu.stream(stream)
            elif self.accelerator_type == "npu":
                stream_ctx = torch.npu.stream(stream)
            else:
                stream_ctx = torch.cuda.stream(stream)
            with stream_ctx:
                # Save original stride and shape information
                original_stride = activation.stride()
                original_storage_offset = activation.storage_offset()
                original_shape = activation.size()

                # Check if tensor has broadcast dimensions (stride == 0)
                # If so, copy the underlying storage directly instead of materializing the broadcast
                has_broadcast = 0 in original_stride

                if has_broadcast:
                    # Copy only the actual underlying storage, not the materialized broadcast
                    # Create CPU tensor with same storage size as original
                    storage_size = activation.untyped_storage().size()
                    cpu_storage = torch.empty(
                        storage_size // activation.element_size(),
                        dtype=activation.dtype,
                        pin_memory=self.use_pin_memory,
                        device="cpu",
                    )
                    # Copy the raw storage
                    cpu_storage_view = torch.as_strided(
                        activation, size=(storage_size // activation.element_size(),), stride=(1,), storage_offset=0
                    )
                    cpu_storage.copy_(cpu_storage_view, non_blocking=True)
                    cpu_tensor = cpu_storage
                else:
                    # Copy the full underlying storage, not just prod(shape) * itemsize bytes.
                    # The saved strides may reference storage beyond what `empty_like` would
                    # allocate (e.g. when `activation` is a narrow/slice of a wider tensor).
                    storage_numel = activation.untyped_storage().size() // activation.element_size()
                    cpu_storage_tensor = torch.empty(
                        storage_numel,
                        dtype=activation.dtype,
                        pin_memory=self.use_pin_memory,
                        device="cpu",
                    )
                    # View the GPU storage as a flat 1D tensor and copy it wholesale.
                    gpu_flat = torch.as_strided(
                        activation,
                        size=(storage_numel,),
                        stride=(1,),
                        storage_offset=0,
                    )
                    cpu_storage_tensor.copy_(gpu_flat, non_blocking=True)
                    cpu_tensor = cpu_storage_tensor

                # Store CPU tensor along with stride information
                self.tracker[tensor_id] = (
                    cpu_tensor,
                    True,  # True = (in future) modified
                    original_stride,  # Save original GPU stride
                    original_storage_offset,  # Save original storage offset
                    original_shape,  # Save original shape for broadcast restoration
                )

            if self.use_streams:
                event = self.s1.record_event()

                # Stash to keep activation alive til s1 is done
                self.fwd_stash[tensor_id] = (activation, event)

            # Track this storage for deduplication
            self.storage_to_tensor_id[storage_key] = tensor_id

            return tensor_id

        def unpack_tensor_single_stream(unpack_tensor_id: int) -> torch.Tensor:
            # backward pass - we are called with the tensor_id, which
            # we will use to retrieve the saved/offloaded tensor
            if self.is_first_backward_call:
                if self.is_first_forward_pass:
                    self.is_first_forward_pass = False
                    if self.use_pin_memory:
                        verify_sufficient_virtual_memory()

                self.is_first_backward_call = False

            if unpack_tensor_id not in self.tracker:
                raise ValueError(f"Untracked tensor with id {unpack_tensor_id}")

            (
                maybe_accelerator_tensor,
                modified,
                original_stride,
                original_storage_offset,
                original_shape,
            ) = self.tracker[unpack_tensor_id]

            if modified:
                # Restore tensor to GPU
                accelerator_tensor = maybe_accelerator_tensor.to(self.accelerator_type, non_blocking=True)
                # Restore original stride if we saved it (handles both broadcast and non-broadcast cases)
                if original_stride is not None:
                    accelerator_tensor = torch.as_strided(
                        accelerator_tensor,
                        size=original_shape,
                        stride=original_stride,
                        storage_offset=original_storage_offset,
                    )
                maybe_accelerator_tensor = accelerator_tensor

            # clear tensor from tracking
            del self.tracker[unpack_tensor_id]
            # Only set is_first_forward_call to True when all tensors have been unpacked
            if len(self.tracker) == 0:
                self.is_first_forward_call = True
            return maybe_accelerator_tensor

        def unpack_tensor_with_streams(unpack_tensor_id: int) -> torch.Tensor:
            # backward pass - we are called with the tensor_id, which
            # we will use to retrieve the saved/offloaded tensor
            if self.is_first_backward_call:
                self.curr_graph_id = torch._C._current_graph_task_id()

                def wait_and_del_remaining_references() -> None:
                    for id in list(self.bwd_tensor_stash.keys()):
                        if id in self.bwd_ev_stash:
                            event = self.bwd_ev_stash[id]
                            self.s1.wait_event(event)
                        del self.bwd_tensor_stash[id]

                # Register a callback to the end of autograd to clean everything up
                torch.autograd.variable.Variable._execution_engine.queue_callback(wait_and_del_remaining_references)

                if self.is_first_forward_pass:
                    self.is_first_forward_pass = False
                    if self.use_pin_memory:
                        verify_sufficient_virtual_memory()

                self.is_first_backward_call = False

            if unpack_tensor_id not in self.tracker:
                raise ValueError(f"untracked tensor with id {unpack_tensor_id}")

            (
                maybe_accelerator_tensor,
                modified,
                original_stride,
                original_storage_offset,
                original_shape,
            ) = self.tracker[unpack_tensor_id]

            if modified:
                # Get data on the current autograd node
                graph_id = torch._C._current_graph_task_id()
                node = torch._C._current_autograd_node()
                prev_node_ids = []

                # If we're on a new node, mark prev node's tensors to be freed later
                if graph_id == self.curr_graph_id and self.curr_autograd_node != node:
                    self.curr_autograd_node = node
                    prev_node_ids = list(self.bwd_tensor_stash.keys())

                brought_back_from_cpu = True
                if unpack_tensor_id in self.fwd_stash:
                    maybe_accelerator_tensor = self.fwd_stash[unpack_tensor_id][0]
                    brought_back_from_cpu = False
                else:
                    # Kick off the process to bring tensors back
                    if self.accelerator_type == "xpu":
                        stream_ctx = torch.xpu.stream(self.s1)
                    elif self.accelerator_type == "npu":
                        stream_ctx = torch.npu.stream(self.s1)
                    else:
                        stream_ctx = torch.cuda.stream(self.s1)
                    with stream_ctx:
                        # Restore tensor to GPU
                        accelerator_tensor = maybe_accelerator_tensor.to(self.accelerator_type, non_blocking=True)
                        # Restore original stride if we saved it (handles both broadcast and non-broadcast cases)
                        if original_stride is not None:
                            accelerator_tensor = torch.as_strided(
                                accelerator_tensor,
                                size=original_shape,
                                stride=original_stride,
                                storage_offset=original_storage_offset,
                            )
                        maybe_accelerator_tensor = accelerator_tensor

                    # Tell comp stream to wait for the info to be loaded before executing
                    self.s0.wait_stream(self.s1)

                    # Stash the tensor to keep memory alive until compute stream is complete
                    self.bwd_tensor_stash[unpack_tensor_id] = maybe_accelerator_tensor

                    # Note: [Track views of the unpacked]
                    # Why do we get the use count of the unpacked tensor here? We want an
                    # initial count to compare to later, during the post-hook of the
                    # backward node, when we need to decide whether we're allowed to free
                    # the tensor yet. In what obscure cases must we delay freeing the
                    # tensor (and thus call record_stream)?
                    # 1. Any of the outputs of the backward node is a view of the unpacked
                    #    tensor.
                    # 2. In the case that this unpacked tensor will be used in a
                    #    checkpointed region, if one of the recomputed saved tensors ends
                    #    up as a view of the unpacked tensor.
                    # 3. The user abuses the system somehow and manually relies on the
                    #    unpacked tensor to exist after the backward node has executed.
                    if self.accelerator_type == "npu":
                        storage_refcount = torch_npu._C._storage_Use_Count(
                            maybe_accelerator_tensor.untyped_storage()._cdata
                        )
                    else:
                        storage_refcount = torch._C._storage_Use_Count(
                            maybe_accelerator_tensor.untyped_storage()._cdata
                        )

                def hook(outputs, inputs):
                    # create events for the current node inputs/outputs if they were streamed in
                    if brought_back_from_cpu:
                        # See Note: [Track views of the unpacked]
                        # IF any of the outputs is a view of the tensor, OR if a view of
                        # the tensor has been saved as a part of checkpoint's recompute
                        # process, OR the user has abusedly incurred a reference on the
                        # unpacked tensor, THEN the tensor might be used later and we
                        # cannot presume to delete it after only the current node is
                        # done! So we use our frenemy, record_stream, to ensure the
                        # Tensor stays unmessed with until it's done getting used in the
                        # compute stream (s0 here). Note that the con here is we introduce
                        # non-deterministic (thus higher) memory usage, but this case
                        # should not happen often.
                        # Check if tensor still exists (might have been cleaned up by a previous node)
                        if unpack_tensor_id in self.bwd_tensor_stash:
                            unpacked_tensor = self.bwd_tensor_stash[unpack_tensor_id]
                            if self.accelerator_type == "npu":
                                storage_count = torch_npu._C._storage_Use_Count(
                                    unpacked_tensor.untyped_storage()._cdata
                                )
                            else:
                                storage_count = torch._C._storage_Use_Count(unpacked_tensor.untyped_storage()._cdata)
                            if storage_count > storage_refcount:
                                unpacked_tensor.record_stream(self.s0)
                                del self.bwd_tensor_stash[unpack_tensor_id]
                            else:
                                event = self.s0.record_event()
                                self.bwd_ev_stash[unpack_tensor_id] = event

                    # if there are still things in the fwd_stash, get rid of them as we're in bwd now
                    for id in list(self.fwd_stash.keys()):
                        _, ev = self.fwd_stash[id]
                        self.s0.wait_event(ev)
                        del self.fwd_stash[id]

                    # wait on prev node's events and del those
                    for id in prev_node_ids:
                        # Only wait on events that exist (some tensors may have used record_stream instead)
                        if id in self.bwd_ev_stash:
                            event = self.bwd_ev_stash[id]
                            self.s1.wait_event(event)
                            del self.bwd_ev_stash[id]
                        if id in self.bwd_tensor_stash:
                            del self.bwd_tensor_stash[id]

                    return outputs

                node.register_hook(hook)

            # clear tensor from tracking
            del self.tracker[unpack_tensor_id]
            # Only set is_first_forward_call to True when all tensors have been unpacked
            if len(self.tracker) == 0:
                self.is_first_forward_call = True
            return maybe_accelerator_tensor

        unpack_tensor = unpack_tensor_with_streams if self.use_streams else unpack_tensor_single_stream
        super().__init__(pack_tensor, unpack_tensor)

    def update_model_params(self, model: nn.Module):
        """
        Update the set of parameter storage pointers from the model. This allows filtering out model parameters during
        offloading, which is especially important for FSDP models where parameters may not be detected by isinstance
        checks.

        For FSDP v2, this method handles DTensor parameters which may be sharded across ranks and not have valid local
        storage on all ranks. We extract the local tensor from DTensors using _local_tensor when available.

        Args:
            model: The model whose parameters should be tracked
        """
        param_storages = set()

        for p in model.parameters():
            # For FSDP v2: extract local tensor from DTensor
            actual_tensor = p
            if DTensor is not None and isinstance(p, DTensor) and hasattr(p, "_local_tensor"):
                actual_tensor = p._local_tensor

            # Try to get storage pointer
            try:
                storage_ptr = actual_tensor.untyped_storage().data_ptr()
                if storage_ptr != 0:
                    param_storages.add(storage_ptr)
            except RuntimeError:
                # Parameter doesn't have accessible storage (e.g., FSDP v2 sharded without local shard, FP8 parameters)
                # These will be caught by other checks (isinstance for Parameter, class name for FP8)
                continue

        self.param_storages = param_storages


class NoOpManager(saved_tensors_hooks):
    """
    A `saved_tensors_hook` manager used to disable any other `saved_tensors_hook` manager applied before. This relies
    on the behavior that only the most recently registered `saved_tensors_hook` will run.

    One example usage is to opt a local region of code out of activations offloading, which is usually applied globally
    to best track state.
    """

    def __init__(self) -> None:
        def noop(tensor):
            return tensor

        super().__init__(noop, noop)


def get_act_offloading_ctx_manager(
    model: nn.Module,
    use_pin_memory: bool = True,
    use_streams: bool = True,
    min_offload_size: int = 1024,
    max_fwd_stash_size: int = 5,
    warn_if_no_head: bool = True,
) -> OffloadActivations:
    """
    Returns the activation offloading context manager for the model. All but the last output Linear in every step will
    be offloaded.

    If activation offloading is enabled, we return the OffloadActivations context manager. If activation offloading is
    disabled, we return a NoOpManager context manager.

    Args:
        model (`nn.Module`):
            Model to wrap with the activation offloading context manager.
        use_pin_memory (`bool`, *optional*, defaults to `True`):
            Whether to offloaded Tensor will be placed in pinned memory on the CPU. Pinned memory allows the Tensor to
            be moved back onto GPU more quickly but is a limited resource.
        use_streams (`bool`, *optional*, defaults to `True`):
            Whether to use streams for performance optimization where the communications get overlapped with the
            computation. Requires a torch build after torch-2.5.0.
        min_offload_size (`int`, *optional*, defaults to `1024`):
            Minimum number of bytes a Tensor must be in order to qualify for offloading. If the tensor is too small, we
            do not want to waste bandwidth and resources moving it to CPU and back.
        max_fwd_stash_size (`int`, *optional*, defaults to `5`):
            Maximum size of the forward stash, or the maximum number of consecutive activations to keep alive during
            the forward pass. This number must be at least 1. Keeping alive more activations will potentially allow
            more overlap between the communication and compute streams at the cost of increasing memory usage. Keeping
            alive fewer activations will conserve memory, but may cause poor overlap between the streams, increasing
            runtime.
        warn_if_no_head (`bool`, *optional*, defaults to `True`):
            Whether to warn if no output head is detected. If set to `False`, no warning will be raised if no output
            head is detected.

    Returns:
        `contextlib.ContextDecorator`:
            Activation offloading context manager for the model.
    """
    activations_handling_ctx = OffloadActivations(
        use_pin_memory=use_pin_memory,
        use_streams=use_streams,
        min_offload_size=min_offload_size,
        max_fwd_stash_size=max_fwd_stash_size,
    )

    # Update parameter storages to filter them during offloading (important for FSDP)
    activations_handling_ctx.update_model_params(model)

    # Below is our hack to disable offloading the last output Linear in every
    # step, as the cost for offloading the activation and then soon after bringing
    # it back is expensive.
    output_head_detected = False
    noop_ctx = NoOpManager()

    # Try to get the actual model if it's wrapped
    unwrapped_model = model
    if hasattr(unwrapped_model, "module"):
        unwrapped_model = unwrapped_model.module
    # check for PEFT models
    if hasattr(unwrapped_model, "base_model") and hasattr(unwrapped_model, "peft_config"):
        unwrapped_model = unwrapped_model.base_model

    # Check for different types of output heads
    if hasattr(unwrapped_model, "output"):
        if isinstance(unwrapped_model.output, nn.Module):
            unwrapped_model.output.register_forward_pre_hook(lambda *args: noop_ctx.__enter__())
            unwrapped_model.output.register_forward_hook(lambda *args: noop_ctx.__exit__(), always_call=True)
            output_head_detected = True
        elif hasattr(unwrapped_model.output, "linear") and isinstance(unwrapped_model.output.linear, nn.Module):
            unwrapped_model.output.linear.register_forward_pre_hook(lambda *args: noop_ctx.__enter__())
            unwrapped_model.output.linear.register_forward_hook(lambda *args: noop_ctx.__exit__(), always_call=True)
            output_head_detected = True

    # Check for HuggingFace model output heads
    elif hasattr(unwrapped_model, "lm_head"):
        unwrapped_model.lm_head.register_forward_pre_hook(lambda *args: noop_ctx.__enter__())
        unwrapped_model.lm_head.register_forward_hook(lambda *args: noop_ctx.__exit__(), always_call=True)
        output_head_detected = True

    # Check for decoder-based models
    elif hasattr(unwrapped_model, "decoder"):
        decoder = unwrapped_model.decoder
        if hasattr(decoder, "output"):
            decoder.output.register_forward_pre_hook(lambda *args: noop_ctx.__enter__())
            decoder.output.register_forward_hook(lambda *args: noop_ctx.__exit__(), always_call=True)
            output_head_detected = True
        # Some models have lm_head in the decoder
        elif hasattr(decoder, "lm_head"):
            decoder.lm_head.register_forward_pre_hook(lambda *args: noop_ctx.__enter__())
            decoder.lm_head.register_forward_hook(lambda *args: noop_ctx.__exit__(), always_call=True)
            output_head_detected = True

    # Check for transformer models with final layer norm
    elif hasattr(unwrapped_model, "final_layer_norm") or hasattr(unwrapped_model, "ln_f"):
        final_norm = getattr(unwrapped_model, "final_layer_norm", None) or unwrapped_model.ln_f
        final_norm.register_forward_pre_hook(lambda *args: noop_ctx.__enter__())
        final_norm.register_forward_hook(lambda *args: noop_ctx.__exit__(), always_call=True)
        output_head_detected = True

    # Check for models with head module
    elif hasattr(unwrapped_model, "head") and isinstance(unwrapped_model.head, nn.Module):
        unwrapped_model.head.register_forward_pre_hook(lambda *args: noop_ctx.__enter__())
        unwrapped_model.head.register_forward_hook(lambda *args: noop_ctx.__exit__(), always_call=True)
        output_head_detected = True

    if not output_head_detected and warn_if_no_head:
        logger.warning(
            "During activation offloading, no output head was detected. If your model has an output head, it will be "
            "offloaded. This usually greatly slows training, given the large vocabulary size. To change this "
            "behavior, set your output head as model.output and make it an nn.Module. You can disable this warning by "
            "passing `warn_if_no_head=False`."
        )

    # Disable offloading for any Liger modules
    for name, module in unwrapped_model.named_modules():
        if "liger" in name.lower():
            module.register_forward_pre_hook(lambda *args: noop_ctx.__enter__())
            module.register_forward_hook(lambda *args: noop_ctx.__exit__(), always_call=True)

    return activations_handling_ctx


# ---------------------------------------------------------------------------
# Reporting
# ---------------------------------------------------------------------------

@torch.no_grad()
def memory_report(
    *,
    model: Optional[nn.Module] = None,
    optimizer: Optional[torch.optim.Optimizer] = None,
    inactive_modules: Optional[dict[str, nn.Module]] = None,
) -> dict[str, float]:
    out: dict[str, float] = {}

    if model is not None:
        out["model_mib"] = module_nbytes(model) / (1024 ** 2)
        out["model_params_only_mib"] = module_nbytes(
            model,
            include_grad=False,
            include_buffers=False,
        ) / (1024 ** 2)

    if optimizer is not None:
        out["optimizer_state_mib"] = optimizer_state_nbytes(optimizer) / (1024 ** 2)

    if inactive_modules:
        for name, module in inactive_modules.items():
            out[f"{name}_mib"] = module_nbytes(module) / (1024 ** 2)

    return out