Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/source/content/migrating_to_v4.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@ verified against frozen `HookedTransformer` reference activations. Omit it to
work with raw HuggingFace weights (the equivalent of the old
`from_pretrained_no_processing`).

Legacy TransformerLens-format repos (`NeelNanda/*`, `ArthurConmy/*`,
`Baidicoot/*`, e.g. `gelu-2l` or `solu-1l`) have no HuggingFace `model_type`.
Load them with `TransformerBridge.boot_tl_legacy("NeelNanda/GELU_2L512W_C4_Code")`.
`boot_transformers` also accepts the known legacy repos and their aliases, but
routes them to `boot_tl_legacy` with a warning. Other repos in those namespaces
(e.g. `Baidicoot/Llama-3-8B-Instruct-LAT`) are HF-format and load normally.

## Removed names and their replacements

| Removed in 4.0 | Replacement |
Expand Down
7 changes: 7 additions & 0 deletions tests/integration/model_bridge/test_tl_legacy_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,3 +96,10 @@ def test_boot_transformers_stamps_checkpoint_metadata():
)
assert bridge.cfg.checkpoint_index == 2
assert bridge.cfg.checkpoint_value is not None


def test_boot_transformers_routes_the_alias_to_boot_tl_legacy(solu_bridge):
routed = TransformerBridge.boot_transformers("solu-1l", device="cpu")
tokens = torch.tensor([[1, 2, 3, 4]])
with torch.no_grad():
torch.testing.assert_close(routed(tokens), solu_bridge(tokens), atol=0, rtol=0)
122 changes: 122 additions & 0 deletions tests/unit/model_bridge/test_boot_tl_legacy_routing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
"""boot_transformers routes legacy TransformerLens-format repos to boot_tl_legacy."""

import logging
from unittest.mock import MagicMock, patch

import pytest
import torch
from transformers import GPT2Config, PreTrainedTokenizerBase

from transformer_lens.model_bridge.bridge import TransformerBridge
from transformer_lens.model_bridge.sources.tl_legacy import (
TL_LEGACY_MODEL_NAMES,
TL_LEGACY_PREFIXES,
)
from transformer_lens.model_bridge.sources.transformers import source

GELU_1L = "NeelNanda/GELU_1L512W_C4_Code"


class _TookHFPath(Exception):
"""Raised once boot() takes the HuggingFace loading path."""


@pytest.fixture
def legacy_boot():
sentinel = MagicMock(spec=TransformerBridge, name="legacy_bridge")
with patch.object(source, "_boot_tl_legacy", return_value=sentinel) as mock:
mock.sentinel = sentinel
yield mock


@pytest.mark.parametrize("name", ["gelu-1l", GELU_1L])
def test_alias_and_repo_id_route_to_boot_tl_legacy(legacy_boot, name, caplog):
with caplog.at_level(logging.WARNING):
bridge = source.boot(name, device="cpu")

assert bridge is legacy_boot.sentinel
legacy_boot.assert_called_once_with(
GELU_1L,
checkpoint_index=None,
checkpoint_value=None,
device="cpu",
dtype=torch.float32,
tokenizer=None,
)
assert f"TransformerBridge.boot_tl_legacy('{GELU_1L}')" in caplog.text


@pytest.mark.parametrize(
"checkpoint",
[{"checkpoint_index": 3}, {"checkpoint_value": 1024}],
ids=lambda checkpoint: next(iter(checkpoint)),
)
def test_supported_options_are_forwarded(legacy_boot, checkpoint):
tokenizer = MagicMock(spec=PreTrainedTokenizerBase, name="tokenizer")
source.boot(
GELU_1L,
device="cpu",
dtype=torch.float16,
tokenizer=tokenizer,
trust_remote_code=True, # irrelevant to .pth repos, so harmlessly ignored
**checkpoint,
)
legacy_boot.assert_called_once_with(
GELU_1L,
checkpoint_index=checkpoint.get("checkpoint_index"),
checkpoint_value=checkpoint.get("checkpoint_value"),
device="cpu",
dtype=torch.float16,
tokenizer=tokenizer,
)


@pytest.mark.parametrize(
"kwargs",
[
{"hf_config_overrides": {"n_layer": 2}},
{"load_weights": False},
{"model_class": object},
{"n_ctx": 128},
{"revision": "main"},
{"code_revision": "main"},
{"device_map": "auto"},
{"n_devices": 2},
{"max_memory": {0: "1GB"}},
{"offload_folder": "/tmp/offload"},
],
ids=lambda kwargs: next(iter(kwargs)),
)
def test_unsupported_options_raise_instead_of_being_dropped(legacy_boot, kwargs):
with pytest.raises(ValueError, match=f"boot_tl_legacy.*{next(iter(kwargs))}"):
source.boot(GELU_1L, **kwargs)
legacy_boot.assert_not_called()


# The legacy namespaces also host HF-format models, which must not be routed.
@pytest.mark.parametrize("name", ["gpt2", "Baidicoot/Llama-3-8B-Instruct-LAT"])
def test_hf_format_repos_are_not_routed(legacy_boot, name):
with patch.object(source.AutoConfig, "from_pretrained", side_effect=_TookHFPath), pytest.raises(
_TookHFPath
):
source.boot(name, device="cpu")
legacy_boot.assert_not_called()


def test_legacy_list_matches_the_model_registry():
"""Every legacy-namespace model TL ships is routed, and nothing else is."""
from transformer_lens.supported_models import OFFICIAL_MODEL_NAMES

registry = {name for name in OFFICIAL_MODEL_NAMES if name.startswith(TL_LEGACY_PREFIXES)}
assert TL_LEGACY_MODEL_NAMES == registry


def test_preloaded_hf_model_is_not_routed(legacy_boot):
"""An hf_model is HF-format whatever its repo name; boot() reads its config."""
hf_model = MagicMock(name="hf_model")
hf_model.config = GPT2Config(n_layer=1)
with patch.object(
source, "build_bridge_config_from_hf", side_effect=_TookHFPath
), pytest.raises(_TookHFPath):
source.boot(GELU_1L, hf_model=hf_model, device="cpu")
legacy_boot.assert_not_called()
36 changes: 36 additions & 0 deletions transformer_lens/model_bridge/sources/tl_legacy.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,42 @@

TL_LEGACY_PREFIXES = ("NeelNanda/", "ArthurConmy/", "Baidicoot/")

# The known legacy TL-format repos. These namespaces also host ordinary HF-format
# models (e.g. Baidicoot/Llama-3-8B-Instruct-LAT), so boot_transformers routes on
# this exact list rather than on TL_LEGACY_PREFIXES.
TL_LEGACY_MODEL_NAMES = frozenset(
{
"ArthurConmy/redwood_attn_2l",
"Baidicoot/Othello-GPT-Transformer-Lens",
"NeelNanda/Attn-Only-2L512W-Shortformer-6B-big-lr",
"NeelNanda/Attn_Only_1L512W_C4_Code",
"NeelNanda/Attn_Only_2L512W_C4_Code",
"NeelNanda/Attn_Only_3L512W_C4_Code",
"NeelNanda/Attn_Only_4L512W_C4_Code",
"NeelNanda/GELU_1L512W_C4_Code",
"NeelNanda/GELU_2L512W_C4_Code",
"NeelNanda/GELU_3L512W_C4_Code",
"NeelNanda/GELU_4L512W_C4_Code",
"NeelNanda/SoLU_10L1280W_C4_Code",
"NeelNanda/SoLU_10L_v22_old",
"NeelNanda/SoLU_12L1536W_C4_Code",
"NeelNanda/SoLU_12L_v23_old",
"NeelNanda/SoLU_1L512W_C4_Code",
"NeelNanda/SoLU_1L512W_Wiki_Finetune",
"NeelNanda/SoLU_1L_v9_old",
"NeelNanda/SoLU_2L512W_C4_Code",
"NeelNanda/SoLU_2L_v10_old",
"NeelNanda/SoLU_3L512W_C4_Code",
"NeelNanda/SoLU_4L512W_C4_Code",
"NeelNanda/SoLU_4L512W_Wiki_Finetune",
"NeelNanda/SoLU_4L_v11_old",
"NeelNanda/SoLU_6L768W_C4_Code",
"NeelNanda/SoLU_6L_v13_old",
"NeelNanda/SoLU_8L1024W_C4_Code",
"NeelNanda/SoLU_8L_v21_old",
}
)


def _fetch_json(repo_id: str, filename: str) -> dict:
from huggingface_hub import hf_hub_download
Expand Down
70 changes: 69 additions & 1 deletion transformer_lens/model_bridge/sources/transformers/source.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
from transformer_lens.model_bridge.sources._hf_format import (
determine_architecture_from_hf_config,
)
from transformer_lens.model_bridge.sources.tl_legacy import TL_LEGACY_MODEL_NAMES
from transformer_lens.model_bridge.sources.tl_legacy import boot as _boot_tl_legacy
from transformer_lens.tools.model_registry.registry_io import resolve_model_alias
from transformer_lens.utilities import get_device
from transformer_lens.utilities.attn_implementation import force_eager_attention
Expand All @@ -53,6 +55,44 @@
logging.getLogger("transformers").setLevel(logging.ERROR)


def _route_to_tl_legacy(
model_name: str,
*,
device: str | torch.device | None,
dtype: torch.dtype | None,
tokenizer: PreTrainedTokenizerBase | None,
checkpoint_index: int | None,
checkpoint_value: int | None,
unsupported: dict[str, Any],
) -> TransformerBridge:
"""Load a legacy TransformerLens-format repo via ``boot_tl_legacy``.

These repos have no HF ``model_type``, so ``AutoConfig`` can't read them.
Options ``boot_tl_legacy`` can't honor raise rather than being dropped.
"""
passed = sorted(name for name, value in unsupported.items() if value is not None)
if passed:
raise ValueError(
f"{model_name!r} is a legacy TransformerLens-format repo, loaded with "
f"TransformerBridge.boot_tl_legacy, which doesn't support: {', '.join(passed)}. "
"Remove these arguments or call boot_tl_legacy directly."
)
logging.warning(
f"{model_name!r} is a legacy TransformerLens-format repo, so boot_transformers is "
"loading it with TransformerBridge.boot_tl_legacy. Call "
f"TransformerBridge.boot_tl_legacy({model_name!r}) directly to avoid this warning."
)
return _boot_tl_legacy(
model_name,
checkpoint_index=checkpoint_index,
checkpoint_value=checkpoint_value,
device=device,
# boot_transformers' None means float32 for a fresh load, as here.
dtype=dtype if dtype is not None else torch.float32,
tokenizer=tokenizer,
)


def boot(
model_name: str,
hf_config_overrides: dict | None = None,
Expand Down Expand Up @@ -87,7 +127,13 @@ def boot(
shows ~1e-3 fp32 drift from kernel-level op reordering, not a bridge bug.

Args:
model_name: The name of the model to load.
model_name: The name of the model to load. The known legacy TransformerLens-format
repos (``TL_LEGACY_MODEL_NAMES``: e.g. ``NeelNanda/GELU_1L512W_C4_Code``) and their
aliases are loaded with ``boot_tl_legacy`` instead, with a warning. Other repos in
those namespaces load as ordinary HF models. Only ``device``, ``dtype``,
``tokenizer`` and the checkpoint arguments apply to them; HF loading options
(``device_map``, ``revision``, ``load_weights=False``, ...) raise. Passing
``hf_model`` skips this routing.
hf_config_overrides: Optional overrides applied to the HuggingFace config before model load.
device: The device to use. If None, will be determined automatically. Mutually exclusive
with ``device_map``.
Expand Down Expand Up @@ -150,6 +196,28 @@ def boot(
f"DEPRECATED: You are using a deprecated, model_name alias '{model_name}'. TransformerLens will now load the official transformers model name, '{official_name}' instead.\n Please update your code to use the official name by changing model_name from '{model_name}' to '{official_name}'.\nSince TransformerLens v3, all model names should be the official transformers model names.\nThe aliases may be removed in a future version of TransformerLens, so please do the update now."
)
model_name = official_name
# A pre-loaded hf_model is HF-format by construction, whatever its repo name.
if hf_model is None and model_name in TL_LEGACY_MODEL_NAMES:
return _route_to_tl_legacy(
model_name,
device=device,
dtype=dtype,
tokenizer=tokenizer,
checkpoint_index=checkpoint_index,
checkpoint_value=checkpoint_value,
unsupported={
"hf_config_overrides": hf_config_overrides,
"load_weights": None if load_weights else False,
"model_class": model_class,
"n_ctx": n_ctx,
"revision": revision,
"code_revision": code_revision,
"device_map": device_map,
"n_devices": n_devices,
"max_memory": max_memory,
"offload_folder": offload_folder,
},
)
if checkpoint_index is not None or checkpoint_value is not None:
if revision is not None:
raise ValueError(
Expand Down
Loading