ParamMappedGradiendModel
Bases: GradiendModel
GRADIEND model with base-parameter mapping.
In addition to GradiendModel (only weights), this class stores a mapping from base-model parameters to the GRADIEND input space. This enables:
- extracting gradients from a base model into GRADIEND input tensor
- accepting dict-of-parameter gradients in forward/forward_encoder (same semantics as before)
- pruning (physically reducing input_dim) while remapping the param map consistently
Param map representation (in-memory):
`self.param_map` is a dict: param_name -> spec dict with:
- "shape": tuple[int,...] (required)
- "repr": "all" | "mask" | "indices"
- if repr == "mask": "mask": torch.BoolTensor (shape == param shape)
- if repr == "indices": "indices": 1D int tensor of flat indices in [0, numel)
Notes:
- repr="all" means full param selected; no mask/indices tensor needed.
- repr="indices" avoids huge bool masks for very large params with tiny selection.
- All mapping operations are defined by this spec; order is the insertion order of `self.param_map`.
Saving/loading:
- config.json includes mapping.mode ("all"|"mask"|"indices"|"mixed") and per-param entries with shapes.
- mapping_masks.* and mapping_indices.* are written only if needed.
- safetensors is preferred when available; otherwise torch.save/torch.load fallback is used.
Prune:
- prune() selects input dims via mask/threshold/topk and physically slices weights
AND updates the mapping spec accordingly.
Initialize a GRADIEND model with a parameter mapping.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_dim
|
int
|
Size of the GRADIEND input space (total selected gradient entries). |
required |
latent_dim
|
int
|
Size of the latent bottleneck. |
required |
param_map
|
Dict[str, Dict[str, Any]]
|
Mapping spec dict keyed by parameter name. Each value must include "shape" and "repr" ("all" | "mask" | "indices"), and any selection tensor required by the repr. |
required |
activation_encoder
|
str
|
Encoder activation name. |
'tanh'
|
activation_decoder
|
str
|
Decoder activation name. |
'id'
|
bias_decoder
|
bool
|
Whether the decoder linear layer uses a bias term. |
True
|
torch_dtype
|
dtype
|
dtype used for model parameters. |
float32
|
device
|
Optional[device]
|
Optional default device for both encoder and decoder when specific devices are not provided. |
None
|
device_encoder
|
Optional[device]
|
Device for encoder parameters. |
None
|
device_decoder
|
Optional[device]
|
Device for decoder parameters. |
None
|
lazy_init
|
bool
|
If True, do not create encoder/decoder weights; build on prune. |
False
|
**kwargs
|
Any
|
Stored in |
{}
|
Source code in gradiend/model/param_mapped.py
param_map_hash
property
Compute a stable hash of the current mapping spec.
The hash includes param names, shapes, repr types, and selection tensors. It is suitable for cache keys and change detection.
Returns:
| Type | Description |
|---|---|
str
|
Hex digest string (MD5) of the mapping spec. |
_build_base_global_index_map
Build a base-global index map for the current input space.
Returns:
1D tensor of length input_dim. For each local input index, stores the
corresponding base-global index (flattened across base-model parameters
in param_map insertion order).
Source code in gradiend/model/param_mapped.py
_compile_param_selectors
Source code in gradiend/model/param_mapped.py
_get_base_global_index_map
Return a cached base-global index map for the current input space.
The map is rebuilt when the param_map changes (e.g., after prune).
Source code in gradiend/model/param_mapped.py
_get_compiled_param_selectors
_invalidate_runtime_param_map_cache
_normalize_param_map_reprs
Normalize param_map representations without changing selected dimensions.
Source code in gradiend/model/param_mapped.py
_param_map_items
decode_base_global_index
Decode one base-global index into parameter-local coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base_global_index
|
int
|
Index in the flattened base-parameter space. |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dict with parameter name, shape, flat index within that parameter, and |
Dict[str, Any]
|
coordinate tuple/list. |
Source code in gradiend/model/param_mapped.py
decode_base_global_indices
Vectorized convenience wrapper around decode_base_global_index().
Source code in gradiend/model/param_mapped.py
extract_gradients
Extract gradients from a base model (copies).
Returns either:
- dict[param_name] -> gradient tensor shaped like the parameter, OR
- a single concatenated 1D tensor in GRADIEND input space
When target_device is set, gradient chunks are moved there incrementally during extraction, reducing peak memory on the base model GPU (avoids holding a full gradient copy there in addition to the concatenated result).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
Base model that has parameter gradients populated (after backward). |
required |
return_dict
|
bool
|
If True, return a dict of per-parameter gradients. If False, return a flattened 1D tensor in GRADIEND input space. |
False
|
target_device
|
Optional[device]
|
If set, move each gradient chunk to this device before concatenation. Use the encoder device to avoid 2x gradient peak on the base model GPU. |
None
|
Returns:
| Type | Description |
|---|---|
Union[Tensor, Dict[str, Tensor]]
|
If return_dict is True: Dict[param_name, grad_tensor] where each tensor matches the parameter shape. |
Union[Tensor, Dict[str, Tensor]]
|
If return_dict is False: 1D tensor containing only the selected entries (per param_map) concatenated in param_map order. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If any required parameter gradient is None. |
Source code in gradiend/model/param_mapped.py
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 | |
extract_gradients_streaming
Extract mapped base-model gradients while backward is running.
Hooks collect only the entries selected by param_map. On PyTorch versions
with register_post_accumulate_grad_hook, full p.grad tensors are cleared
as soon as each parameter finishes accumulating, reducing peak memory for large
frozen base models used only as gradient generators.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Module
|
Base model whose backward pass will populate gradients. |
required |
backward_fn
|
Callable[[], Any]
|
Callable that runs the base-model backward pass. |
required |
return_dict
|
bool
|
If True, return a per-parameter dict. Unselected entries are zero-filled for masked/indexed parameters. |
False
|
target_device
|
Optional[device]
|
Optional device to move selected chunks to immediately. |
None
|
Source code in gradiend/model/param_mapped.py
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 | |
flatten_gradient_dict
Flatten a per-param gradient dict into a single 1D tensor in GRADIEND input space. Uses the same param_map order and selection (all/mask/indices) as in forward().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
grad_dict
|
Dict[str, Tensor]
|
Dict of gradients keyed by parameter name with tensors shaped like the base model parameters. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
1D tensor in GRADIEND input space, concatenated in param_map order. |
Source code in gradiend/model/param_mapped.py
forward
Forward that accepts:
- tensor: already in GRADIEND input space
- dict: per-param gradient tensors (full tensors); selection is applied using mapping spec
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Union[Tensor, Dict[str, Tensor]]
|
Either a 1D tensor in GRADIEND input space or a dict of per-parameter gradient tensors. |
required |
return_encoded
|
bool
|
If True, also return the latent encoding. |
False
|
Returns:
| Type | Description |
|---|---|
Union[Tensor, Tuple[Tensor, Tensor], Dict[str, Tensor], Tuple[Dict[str, Tensor], Tensor]]
|
If input is a tensor: Same return contract as GradiendModel.forward. |
Union[Tensor, Tuple[Tensor, Tensor], Dict[str, Tensor], Tuple[Dict[str, Tensor], Tensor]]
|
If input is a dict: Decoded gradients as a dict with the same keys and shapes as input (values filled only at selected positions), and optionally the encoded tensor when return_encoded is True. |
Source code in gradiend/model/param_mapped.py
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 | |
forward_encoder
Encoder-only forward that accepts tensor or dict input.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Union[Tensor, Dict[str, Tensor]]
|
Either a 1D tensor in GRADIEND input space or a dict of per-parameter gradient tensors. |
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
Encoded tensor of shape (latent_dim,). |
Source code in gradiend/model/param_mapped.py
from_pretrained
classmethod
Load weights + config + mapping.
On load we reconstruct param_map specs. We do NOT require base model access because shapes are stored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
load_directory
|
str
|
Directory containing model files. |
required |
device_encoder
|
Optional[device]
|
Optional device override for encoder parameters. |
None
|
device_decoder
|
Optional[device]
|
Optional device override for decoder parameters. |
None
|
torch_dtype
|
Optional[dtype]
|
Optional dtype override. If None, uses dtype stored in config.json. |
None
|
Returns:
| Type | Description |
|---|---|
ParamMappedGradiendModel
|
Instantiated ParamMappedGradiendModel with loaded weights and mapping. |
Source code in gradiend/model/param_mapped.py
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 1253 1254 | |
prune
prune(*, topk=None, threshold=None, mask=None, part='decoder-weight', importance=None, keep_idx=None, keep_idx_sorted_unique=False, inplace=False, return_mask=False)
Physically prune the model (reduce input_dim) and remap mapping spec accordingly. The pruning is applied based on up to three criteria: a boolean mask, an importance threshold, and/or a top-k selection.
Selection order: mask -> threshold -> topk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
topk
|
Union[int, float, None]
|
int (absolute) or float in (0,1] (relative fraction among remaining dims). |
None
|
threshold
|
Optional[float]
|
keep dims with importance >= threshold. |
None
|
mask
|
Optional[Tensor]
|
optional bool tensor of shape (input_dim,) in current input space. |
None
|
part
|
str
|
'encoder-weight' | 'decoder-weight' | 'decoder-bias' | 'decoder-sum' (used when importance is None). |
'decoder-weight'
|
importance
|
Optional[Tensor]
|
optional 1D tensor of length input_dim (e.g. from gradient mean); used instead of get_weight_importance(part) when provided. |
None
|
keep_idx
|
Optional[Tensor]
|
optional 1D tensor of input-space indices to keep. Bypasses dense mask/importance materialization. |
None
|
inplace
|
bool
|
modify this instance if True, else return a deepcopy. |
False
|
return_mask
|
bool
|
if True, also return final combined_mask (original input space). |
False
|
Returns:
| Type | Description |
|---|---|
Union[ParamMappedGradiendModel, Tuple[ParamMappedGradiendModel, Tensor]]
|
If return_mask is False:
The pruned ParamMappedGradiendModel (self or a deepcopy depending on |
Union[ParamMappedGradiendModel, Tuple[ParamMappedGradiendModel, Tensor]]
|
If return_mask is True: Tuple (model, combined_mask) where combined_mask is a bool tensor of shape (old_input_dim,) indicating kept dimensions in the original input space. |
Source code in gradiend/model/param_mapped.py
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 | |
save_pretrained
Save weights + config + mapping.
Mapping save strategy:
- Always store shapes in config.
- Choose per-param representation:
- "all" if fully selected (k == numel)
-
else choose "indices" vs "mask" by estimated size:
indices_size ~ k * bytes_per_index(numel) mask_size ~ numel * 1 byte with a small safety margin to avoid flip-flopping.
Output:
- config.json
- mapping_indices.(safetensors|pth) if any param uses indices
- mapping_masks.(safetensors|pth) if any param uses mask
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_directory
|
str
|
Folder to write model files into. |
required |
use_safetensors
|
Optional[bool]
|
If True, require safetensors. If False, force PyTorch bin format. If None, prefer safetensors when available. |
None
|
**kwargs
|
Any
|
Extra metadata to store in config.json. If "training" is provided, it is written to training.json instead. |
{}
|
Returns:
| Type | Description |
|---|---|
None
|
None. |
Source code in gradiend/model/param_mapped.py
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 | |
unpruned_length
Compute the total number of entries in the original unpruned input space.
This is the sum of numel of all parameters in the mapping, regardless of selection.
Returns:
| Type | Description |
|---|---|
int
|
Total number of entries in the original input space before pruning. |