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_freeze_specs(model, specs, pattern_map)

Apply a list of freeze specs to model.

canonical_freeze_meta(specs)

Return a sorted, deduplicated serialization of freeze specs.

effective_freeze(step, base, schedule[, ...])

Compute the active freeze-spec list at step.

freeze_meta_at_step(step, config)

Canonical freeze metadata for config at step.

freeze_params(model, patterns, *[, frozen])

Toggle requires_grad on parameters matching any fnmatch pattern.

trainable_during_run(model, config)

Return the names of the parameters of model that train at some step of a run.

trainable_for_the_run(model, config)

Make every parameter that trains at some step of the run require grad, then restore.

unmatched_patterns(model, specs, pattern_map)

Return the parameter patterns among specs that match no parameter of model.

kempnerforge.training.freeze.freeze_params(model, patterns, *, frozen=True)[source]

Toggle requires_grad on 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 in always_frozen, such as the sigmoid router’s expert_bias, is never unfrozen. A model compiled with torch.compile is matched through the module it wraps.

Parameters:
Return type:

int

kempnerforge.training.freeze.apply_freeze_specs(model, specs, pattern_map)[source]

Apply a list of freeze specs to model.

For each spec, the module field is looked up in pattern_map; if present, its pattern list is used. Otherwise module is treated as a raw fnmatch pattern. Returns {spec.module: n_params_flipped}.

Parameters:
Return type:

dict[str, int]

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.

Parameters:

specs (Iterable[FreezeSpec])

Return type:

list[dict[str, object]]

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 FreezeStage with start_step <= step, in ascending start_step order, override base entries on conflicting module keys (last-write-wins). Stages with start_step > step are 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 base and every stage up to step one after another does, also when keys select overlapping parameters.

Module-key validation:

  • When valid_modules is provided, every spec.module referenced in base or in any applied stage must appear in the set or be a parameter pattern (see is_parameter_pattern), as the build accepts; otherwise ValueError. 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.module may name besides a parameter pattern, or None to 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_modules nor a parameter pattern.

Return type:

list[FreezeSpec]

kempnerforge.training.freeze.unmatched_patterns(model, specs, pattern_map)[source]

Return the parameter patterns among specs that match no parameter of model.

A spec whose module is a key of pattern_map is an alias and is not checked, since an alias such as vision_encoder can name a module without parameters. Names are matched as freeze_params matches them.

Parameters:
Returns:

The patterns, sorted and without repeats, that freeze or unfreeze nothing.

Return type:

list[str]

kempnerforge.training.freeze.freeze_meta_at_step(step, config)[source]

Canonical freeze metadata for config at step.

Save and resume must derive this identically — otherwise the vlm_freeze_expected compare 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.

Parameters:
Return type:

list[dict[str, object]]

kempnerforge.training.freeze.trainable_during_run(model, config)[source]

Return the names of the parameters of model that train at some step of a run.

Covers the build freeze, each FreezeStage from its start_step, and the freeze a resume applies at any step. A parameter that its module names in always_frozen never trains, so it is left out. model is not changed.

Parameters:
  • model (torch.nn.Module) – The model, with each parameter’s requires_grad as 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:

set[str]

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 FreezeStage unfreezes later is in the optimizer from the start.

Parameters:
  • model (torch.nn.Module) – The model, compiled with torch.compile or not.

  • config (VLMConfig) – The run’s VLM config.

Yields:

The names of the parameters it made require grad.

Return type:

Iterator[list[str]]