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:
| Type | Description |
|---|---|
Tensor
|
1D tensor of length input_dim. For each local input index, stores the |
Tensor
|
corresponding base-global index (flattened across base-model parameters |
Tensor
|
in param_map insertion order). |
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
_param_map_items
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
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 | |
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
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 | |
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
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 | |
prune
prune(*, topk=None, threshold=None, mask=None, part='decoder-weight', importance=None, 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
|
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
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 | |
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
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 | |
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. |