kempnerforge.training.freeze¶
Parameter freezing helpers.
freeze_params is the primitive: toggle requires_grad on parameters
whose fully-qualified name matches any of the provided fnmatch patterns.
apply_freeze_specs consumes a list of FreezeSpec entries (e.g. from
VLMConfig.freeze) and resolves each spec’s module field against a
pattern map (typically DEFAULT_MODULE_PATTERNS or an arch-specific
override on the config). A raw fnmatch pattern is passed through unchanged
when it is not a known alias.
canonical_freeze_meta produces a stable, reorder-invariant
serialization of a freeze-spec list for checkpoint metadata, so a
checkpoint saved with [A, B] matches one loaded with [B, A] as
long as the effective mask is identical.
effective_freeze resolves the active freeze-spec list at a given
training step from a base list (always-on) and a list of
FreezeStage step-boundary transitions. Used at save (records the
post-transition state in metadata), at load (computes the expected
metadata for the compare), and at the training-loop hook site
(applies stage transitions when step reaches them).
freeze_meta_at_step composes the last two into the single expression
both the save and the resume path use.
trainable_during_run names every parameter that trains at some step of
a run, and trainable_for_the_run makes those parameters trainable while
the optimizer is built and a checkpoint’s optimizer state is loaded, so a
module that a stage unfreezes is in the optimizer from the start.
Functions
|
Apply a list of freeze specs to |
|
Return a sorted, deduplicated serialization of freeze specs. |
|
Compute the active freeze-spec list at |
|
Canonical freeze metadata for |
|
Toggle |
|
Return the names of the parameters of |
|
Make every parameter that trains at some step of the run require grad, then restore. |
|
Return the parameter patterns among |
- kempnerforge.training.freeze.freeze_params(model, patterns, *, frozen=True)[source]¶
Toggle
requires_gradon parameters matching any fnmatch pattern.Only parameters whose current state differs from the target are flipped, so calling this twice with the same arguments is idempotent. Returns the number of elements (
param.numel()summed) that were actually flipped. A parameter that its module names inalways_frozen, such as the sigmoid router’sexpert_bias, is never unfrozen. A model compiled withtorch.compileis matched through the module it wraps.- Parameters:
model (torch.nn.Module)
frozen (bool)
- Return type:
- kempnerforge.training.freeze.apply_freeze_specs(model, specs, pattern_map)[source]¶
Apply a list of freeze specs to
model.For each spec, the
modulefield is looked up inpattern_map; if present, its pattern list is used. Otherwisemoduleis treated as a raw fnmatch pattern. Returns{spec.module: n_params_flipped}.- Parameters:
model (torch.nn.Module)
specs (Iterable[FreezeSpec])
- Return type:
- kempnerforge.training.freeze.canonical_freeze_meta(specs)[source]¶
Return a sorted, deduplicated serialization of freeze specs.
The output is safe to JSON-encode and compare across runs: two semantically equivalent freeze-spec lists (same
(module, frozen)pairs, any order or duplicates) produce byte-equal JSON.
- kempnerforge.training.freeze.effective_freeze(step, base, schedule, valid_modules=None)[source]¶
Compute the active freeze-spec list at
step.Resolution rule:
Start from
base(build-time freeze list).For each
FreezeStagewithstart_step <= step, in ascendingstart_steporder, overridebaseentries on conflictingmodulekeys (last-write-wins). Stages withstart_step > stepare ignored.A key moves to the end of the list each time it is written, so the specs come in the order of their last write. Applied in that order, they leave each parameter as applying
baseand every stage up tostepone after another does, also when keys select overlapping parameters.
Module-key validation:
When
valid_modulesis provided, everyspec.modulereferenced inbaseor in any applied stage must appear in the set or be a parameter pattern (seeis_parameter_pattern), as the build accepts; otherwiseValueError. This catches typos at load time rather than at the next step boundary.
- Parameters:
step (int) – The step the freeze is wanted at.
base (Iterable[FreezeSpec]) – The build-time freeze list.
schedule (Iterable[FreezeStage]) – The freeze stages, in any order.
valid_modules (set[str] | None) – The module aliases a
spec.modulemay name besides a parameter pattern, orNoneto skip the check.
- Returns:
The active specs, one per module key, in the order of their last write.
- Raises:
ValueError – A spec names neither a module of
valid_modulesnor a parameter pattern.- Return type:
- kempnerforge.training.freeze.unmatched_patterns(model, specs, pattern_map)[source]¶
Return the parameter patterns among
specsthat match no parameter ofmodel.A spec whose
moduleis a key ofpattern_mapis an alias and is not checked, since an alias such asvision_encodercan name a module without parameters. Names are matched asfreeze_paramsmatches them.- Parameters:
model (torch.nn.Module) – The model the specs apply to.
specs (Iterable[FreezeSpec]) – The freeze specs to check.
pattern_map (Mapping[str, list[str]]) – The module aliases and their patterns.
- Returns:
The patterns, sorted and without repeats, that freeze or unfreeze nothing.
- Return type:
- kempnerforge.training.freeze.freeze_meta_at_step(step, config)[source]¶
Canonical freeze metadata for
configatstep.Save and resume must derive this identically — otherwise the
vlm_freeze_expectedcompare rejects checkpoints this code wrote — so both go through here. Passing the config’s alias set means a TOML typo raises instead of silently no-op’ing the freeze.
- kempnerforge.training.freeze.trainable_during_run(model, config)[source]¶
Return the names of the parameters of
modelthat train at some step of a run.Covers the build freeze, each
FreezeStagefrom itsstart_step, and the freeze a resume applies at any step. A parameter that its module names inalways_frozennever trains, so it is left out.modelis not changed.- Parameters:
model (torch.nn.Module) – The model, with each parameter’s
requires_gradas built.config (VLMConfig) – The run’s VLM config.
- Returns:
The names of the parameters that require grad at some step of the run.
- Return type:
- kempnerforge.training.freeze.trainable_for_the_run(model, config)[source]¶
Make every parameter that trains at some step of the run require grad, then restore.
Build the optimizer, and load a checkpoint, inside this context so that a parameter a
FreezeStageunfreezes later is in the optimizer from the start.- Parameters:
model (torch.nn.Module) – The model, compiled with
torch.compileor not.config (VLMConfig) – The run’s VLM config.
- Yields:
The names of the parameters it made require grad.
- Return type: