bridge.models.hf_pretrained.base#
Module Contents#
Classes#
Abstract base class for all pretrained models. |
Functions#
Summarize the state |
|
Data#
API#
- bridge.models.hf_pretrained.base.logger#
‘getLogger(…)’
- bridge.models.hf_pretrained.base._artifact_fingerprint(artifact: Any) str | None#
Summarize the state
save_pretrainedwrites for an artifact, to detect edits made after loading.Returns None when the artifact cannot be summarized; saving then re-serializes it.
- bridge.models.hf_pretrained.base._file_mtimes(path: pathlib.Path) Dict[str, int]#
- class bridge.models.hf_pretrained.base.PreTrainedBase(**kwargs)#
Bases:
abc.ABCAbstract base class for all pretrained models.
This class provides a generic mechanism for managing model artifacts (e.g., config, tokenizer) with lazy loading. Subclasses that are decorated with
@dataclasscan define artifacts as fields with metadata specifying a loader method. Themodelitself is handled via a dedicated property that relies on the abstract_load_modelmethod... rubric:: Example
@dataclass class MyModel(PreTrainedBase): config: AutoConfig = field( init=False, metadata=artifact(loader=”_load_config”) )
def _load_model(self) -> "PreTrainedModel": # Implementation for the loading logic ...Initialization
- model_name_or_path: Union[str, pathlib.Path]#
None
- ARTIFACTS: ClassVar[List[str]]#
[]
- OPTIONAL_ARTIFACTS: ClassVar[List[str]]#
[]
- SOURCE_ARTIFACT_FILES: ClassVar[Dict[str, List[str]]]#
None
- LOAD_ONLY_KWARGS: ClassVar[frozenset[str]]#
‘frozenset(…)’
- get_artifacts() Dict[str, str]#
Get the artifacts dictionary mapping artifact names to their attribute names.
- static _cleanup_hf_local_dir_cache(target_path: pathlib.Path) None#
Remove Hugging Face Hub metadata created by hf_hub_download(local_dir=…).
- static _copy_cached_hub_files(
- repo_id: str,
- target_path: pathlib.Path,
- patterns: List[str],
- *,
- revision: str | None,
Copy files matching patterns from the local Hugging Face cache snapshot of a Hub repository.
Used when the Hub cannot be listed, for example with HF_HUB_OFFLINE=1. Each pattern is resolved separately, so a pattern whose files are not all cached does not block the others. Files are matched and placed by their repository-relative paths, as Hub downloads are.
- Parameters:
repo_id – Hugging Face Hub repository ID.
target_path – Directory to copy the files into.
patterns – File names or glob patterns, matched against repository-relative paths.
revision – Hub revision to read from the cache; None uses the cached default branch.
- Returns:
List of copied repository-relative file names; empty if nothing matching is cached.
- _copy_custom_modeling_files(
- source_path: Union[str, pathlib.Path],
- target_path: Union[str, pathlib.Path],
- file_patterns: Optional[List[str]] = None,
- revision: str | None = None,
Copy files matching patterns from source to target directory.
This preserves custom modeling files that were used during model loading with trust_remote_code=True, or copies additional files specified by patterns.
- Parameters:
source_path – Source directory or HuggingFace Hub ID containing files
target_path – Target directory to copy files to
file_patterns – Optional list of file names or patterns to copy. Supports both exact file names (e.g., “vocab.json”) and glob patterns (e.g., “*.json”). If not provided, defaults to self.custom_file_patterns.
revision – Optional Hugging Face Hub revision to use for remote sources.
- Returns:
Source-relative names of the copied files, placed at the same relative paths in the target.
- _load_artifact(name: str) Any#
Load artifact
namewith_load_<name>and record it, so saving can copy its source files.
- _copies_source_files(name: str, artifact: Any) bool#
Whether saving copies
artifact’s source files: it was loaded from the source and is unchanged.
- _copy_source_artifact_files(
- save_path: pathlib.Path,
- artifacts: Dict[str, Any],
- mtimes: Dict[str, int],
- *,
- revision: str | None,
Copy the source files of unchanged
artifactsinstead of re-serializing them.save_pretrainedcan change these artifacts, e.g. dropvocab.json/merges.txtor switch a fast image processor to the slow one. An artifact the source has no files for is saved withsave_pretrained. Files written sincemtimesby another artifact’ssave_pretrainedare kept, so edits are not lost.
- save_artifacts(
- save_directory: Union[str, pathlib.Path],
- original_source_path: Optional[Union[str, pathlib.Path]] = None,
- additional_files: Optional[List[str]] = None,
Saves all loaded, generic artifacts that have a
save_pretrainedmethod to the specified directory. Note: This does not save themodelattribute.If the model was loaded with trust_remote_code=True, this method will also attempt to preserve any custom modeling files to ensure the saved model can be loaded properly.
- Parameters:
save_directory – Directory to save artifacts to
original_source_path – Optional path to the original source for custom modeling files
additional_files – Optional list of additional file names or patterns to download/copy from the source. Supports both exact file names (e.g., “vocab.json”) and glob patterns (e.g., “*.json”). These files will be copied from the source path.
- abstractmethod _load_model() transformers.PreTrainedModel#
Subclasses must implement this to load the main model.
- abstractmethod _load_config() transformers.AutoConfig#
Subclasses must implement this to load the model config.
- property model: transformers.PreTrainedModel#
Lazily loads and returns the underlying model.
- property config: transformers.AutoConfig#
Lazy load and return the model config.
- property state: megatron.bridge.models.hf_pretrained.state.StateDict#
Get the state dict accessor for pandas-like querying.
This accessor can be backed by either a fully loaded model in memory or a “.safetensors” checkpoint on disk, enabling lazy loading of tensors.
.. rubric:: Examples
import re
model.state() # Get full state dict model.state[“key”] # Get single entry model.state[[“key1”, “key2”]] # Get multiple entries model.state[”.weight”] # Glob pattern model.state[re.compile(r”..bias$”)] # Regex pattern