Spaces:
Running
Running
Commit
Β·
6414c6a
1
Parent(s):
438fb10
Reorginize lenses (#32)
Browse files- reorginized lenses (02a3e822d0a0d80d92d6f4741359286d77f4597c)
- lens/{gpt-neox-20b β EleutherAI/gpt-neox-20b}/config.json +0 -0
- lens/{gpt-neox-20b β EleutherAI/gpt-neox-20b}/params.pt +0 -0
- lens/{pythia-1.4b-deduped-v0 β EleutherAI/pythia-1.4b-deduped-v0}/config.json +0 -0
- lens/{pythia-1.4b-deduped-v0 β EleutherAI/pythia-1.4b-deduped-v0}/params.pt +0 -0
- lens/{pythia-12b-deduped-v0 β EleutherAI/pythia-12b-deduped-v0}/config.json +0 -0
- lens/{pythia-12b-deduped-v0 β EleutherAI/pythia-12b-deduped-v0}/params.pt +0 -0
- lens/{pythia-160m-deduped-v0 β EleutherAI/pythia-160m-deduped-v0}/config.json +0 -0
- lens/{pythia-160m-deduped-v0 β EleutherAI/pythia-160m-deduped-v0}/params.pt +0 -0
- lens/{pythia-1b-deduped-v0 β EleutherAI/pythia-1b-deduped-v0}/config.json +0 -0
- lens/{pythia-1b-deduped-v0 β EleutherAI/pythia-1b-deduped-v0}/params.pt +0 -0
- lens/{pythia-410m-deduped-v0 β EleutherAI/pythia-410m-deduped-v0}/config.json +0 -0
- lens/{pythia-410m-deduped-v0 β EleutherAI/pythia-410m-deduped-v0}/params.pt +0 -0
- lens/{pythia-6.9b-deduped-v0 β EleutherAI/pythia-6.9b-deduped-v0}/config.json +0 -0
- lens/{pythia-6.9b-deduped-v0 β EleutherAI/pythia-6.9b-deduped-v0}/params.pt +0 -0
- lens/{pythia-70m-deduped-v0 β EleutherAI/pythia-70m-deduped-v0}/config.json +0 -0
- lens/{pythia-70m-deduped-v0 β EleutherAI/pythia-70m-deduped-v0}/params.pt +0 -0
- lens/{opt-1.3b β facebook/opt-1.3b}/config.json +0 -0
- lens/{opt-1.3b β facebook/opt-1.3b}/params.pt +0 -0
- lens/{opt-125m β facebook/opt-125m}/config.json +0 -0
- lens/{opt-125m β facebook/opt-125m}/params.pt +0 -0
- lens/{opt-6.7b β facebook/opt-6.7b}/config.json +0 -0
- lens/{opt-6.7b β facebook/opt-6.7b}/params.pt +0 -0
- lens_migration.py +0 -384
- migrate.sh +0 -12
lens/{gpt-neox-20b β EleutherAI/gpt-neox-20b}/config.json
RENAMED
|
File without changes
|
lens/{gpt-neox-20b β EleutherAI/gpt-neox-20b}/params.pt
RENAMED
|
File without changes
|
lens/{pythia-1.4b-deduped-v0 β EleutherAI/pythia-1.4b-deduped-v0}/config.json
RENAMED
|
File without changes
|
lens/{pythia-1.4b-deduped-v0 β EleutherAI/pythia-1.4b-deduped-v0}/params.pt
RENAMED
|
File without changes
|
lens/{pythia-12b-deduped-v0 β EleutherAI/pythia-12b-deduped-v0}/config.json
RENAMED
|
File without changes
|
lens/{pythia-12b-deduped-v0 β EleutherAI/pythia-12b-deduped-v0}/params.pt
RENAMED
|
File without changes
|
lens/{pythia-160m-deduped-v0 β EleutherAI/pythia-160m-deduped-v0}/config.json
RENAMED
|
File without changes
|
lens/{pythia-160m-deduped-v0 β EleutherAI/pythia-160m-deduped-v0}/params.pt
RENAMED
|
File without changes
|
lens/{pythia-1b-deduped-v0 β EleutherAI/pythia-1b-deduped-v0}/config.json
RENAMED
|
File without changes
|
lens/{pythia-1b-deduped-v0 β EleutherAI/pythia-1b-deduped-v0}/params.pt
RENAMED
|
File without changes
|
lens/{pythia-410m-deduped-v0 β EleutherAI/pythia-410m-deduped-v0}/config.json
RENAMED
|
File without changes
|
lens/{pythia-410m-deduped-v0 β EleutherAI/pythia-410m-deduped-v0}/params.pt
RENAMED
|
File without changes
|
lens/{pythia-6.9b-deduped-v0 β EleutherAI/pythia-6.9b-deduped-v0}/config.json
RENAMED
|
File without changes
|
lens/{pythia-6.9b-deduped-v0 β EleutherAI/pythia-6.9b-deduped-v0}/params.pt
RENAMED
|
File without changes
|
lens/{pythia-70m-deduped-v0 β EleutherAI/pythia-70m-deduped-v0}/config.json
RENAMED
|
File without changes
|
lens/{pythia-70m-deduped-v0 β EleutherAI/pythia-70m-deduped-v0}/params.pt
RENAMED
|
File without changes
|
lens/{opt-1.3b β facebook/opt-1.3b}/config.json
RENAMED
|
File without changes
|
lens/{opt-1.3b β facebook/opt-1.3b}/params.pt
RENAMED
|
File without changes
|
lens/{opt-125m β facebook/opt-125m}/config.json
RENAMED
|
File without changes
|
lens/{opt-125m β facebook/opt-125m}/params.pt
RENAMED
|
File without changes
|
lens/{opt-6.7b β facebook/opt-6.7b}/config.json
RENAMED
|
File without changes
|
lens/{opt-6.7b β facebook/opt-6.7b}/params.pt
RENAMED
|
File without changes
|
lens_migration.py
DELETED
|
@@ -1,384 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
from huggingface_hub import model_info
|
| 3 |
-
import argparse
|
| 4 |
-
from copy import deepcopy
|
| 5 |
-
import inspect
|
| 6 |
-
from logging import warn
|
| 7 |
-
from pathlib import Path
|
| 8 |
-
from tqdm import tqdm
|
| 9 |
-
import json
|
| 10 |
-
|
| 11 |
-
from tuned_lens.model_surgery import get_final_norm, get_transformer_layers
|
| 12 |
-
from tuned_lens.load_artifacts import load_lens_artifacts
|
| 13 |
-
from tuned_lens.nn import TunedLens
|
| 14 |
-
from transformers.models.bloom.modeling_bloom import BloomBlock
|
| 15 |
-
from transformers import PreTrainedModel, AutoModelForCausalLM
|
| 16 |
-
from typing import Optional, Generator, Union
|
| 17 |
-
import torch as th
|
| 18 |
-
|
| 19 |
-
from tuned_lens.stats.distance import js_divergence
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
def instantiate_layer(model_config, layer_idx: int, model_type: str) -> th.nn.Module:
|
| 23 |
-
if model_type == "bloom":
|
| 24 |
-
from transformers.models.bloom.modeling_bloom import BloomBlock
|
| 25 |
-
|
| 26 |
-
return _BloomBlockWrapper(BloomBlock(model_config)) # type: ignore[arg-type]
|
| 27 |
-
if model_type == "gpt_neo":
|
| 28 |
-
from transformers.models.gpt_neo.modeling_gpt_neo import GPTNeoBlock
|
| 29 |
-
|
| 30 |
-
return GPTNeoBlock(model_config, layer_idx)
|
| 31 |
-
if model_type == "gpt_neox":
|
| 32 |
-
from transformers.models.gpt_neox.modeling_gpt_neox import (
|
| 33 |
-
GPTNeoXLayer,
|
| 34 |
-
)
|
| 35 |
-
|
| 36 |
-
return GPTNeoXLayer(model_config) # type: ignore[arg-type]
|
| 37 |
-
if model_type == "gpt2":
|
| 38 |
-
from transformers.models.gpt2.modeling_gpt2 import GPT2Block
|
| 39 |
-
|
| 40 |
-
return GPT2Block(model_config, layer_idx) # type: ignore[arg-type]
|
| 41 |
-
if model_type == "opt":
|
| 42 |
-
from transformers.models.opt.modeling_opt import OPTDecoderLayer
|
| 43 |
-
|
| 44 |
-
return OPTDecoderLayer(model_config) # type: ignore[arg-type]
|
| 45 |
-
else:
|
| 46 |
-
raise ValueError(f"Unknown model type '{model_type}'")
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
def maybe_wrap(layer: th.nn.Module) -> th.nn.Module:
|
| 50 |
-
return _BloomBlockWrapper(layer) if isinstance(layer, BloomBlock) else layer
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
# Very annoying that we have to do this. See https://bit.ly/3XSQ7W6 for context on
|
| 54 |
-
# what we're doing here.
|
| 55 |
-
class _BloomBlockWrapper(th.nn.Module):
|
| 56 |
-
def __init__(self, block: BloomBlock):
|
| 57 |
-
super().__init__()
|
| 58 |
-
self.block = block
|
| 59 |
-
|
| 60 |
-
def forward(self, x: th.Tensor) -> th.Tensor:
|
| 61 |
-
from transformers.models.bloom.modeling_bloom import (
|
| 62 |
-
BloomModel,
|
| 63 |
-
build_alibi_tensor,
|
| 64 |
-
)
|
| 65 |
-
|
| 66 |
-
batch_size, seq_len, _ = x.shape
|
| 67 |
-
dummy_mask = x.new_ones([batch_size, seq_len])
|
| 68 |
-
|
| 69 |
-
# Causal mask isn't created inside the block itself, so we have to do it here.
|
| 70 |
-
# Weirdly _prepare_attn_mask doesn't depend on `self` at all but is still an
|
| 71 |
-
# instance method for some reason, so we pass `None` as the first argument.
|
| 72 |
-
causal_mask = BloomModel._prepare_attn_mask(
|
| 73 |
-
None, dummy_mask, (batch_size, seq_len), 0 # type: ignore[arg-type]
|
| 74 |
-
)
|
| 75 |
-
alibi = build_alibi_tensor(dummy_mask, self.block.num_heads, x.dtype)
|
| 76 |
-
h, *_ = self.block(x, alibi, causal_mask)
|
| 77 |
-
return h
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
class TunedLensOld(th.nn.Module):
|
| 81 |
-
"""A tuned lens for decoding hidden states into logits."""
|
| 82 |
-
|
| 83 |
-
layer_norm: th.nn.LayerNorm
|
| 84 |
-
unembedding: th.nn.Linear
|
| 85 |
-
extra_layers: th.nn.Sequential
|
| 86 |
-
layer_translators: th.nn.ModuleList
|
| 87 |
-
|
| 88 |
-
def __init__(
|
| 89 |
-
self,
|
| 90 |
-
model: Optional[PreTrainedModel] = None,
|
| 91 |
-
*,
|
| 92 |
-
bias: bool = True,
|
| 93 |
-
extra_layers: int = 0,
|
| 94 |
-
include_input: bool = True,
|
| 95 |
-
reuse_unembedding: bool = True,
|
| 96 |
-
# Used when saving and loading the lens
|
| 97 |
-
model_config: Optional[dict] = None,
|
| 98 |
-
d_model: Optional[int] = None,
|
| 99 |
-
num_layers: Optional[int] = None,
|
| 100 |
-
vocab_size: Optional[int] = None,
|
| 101 |
-
):
|
| 102 |
-
"""Create a TunedLensOld.
|
| 103 |
-
|
| 104 |
-
Args:
|
| 105 |
-
model : A pertained model from the transformers library you wish to inspect.
|
| 106 |
-
bias : Whether to include a bias term in the translator layers.
|
| 107 |
-
extra_layers : The number of extra layers to apply to the hidden states
|
| 108 |
-
before decoding into logits.
|
| 109 |
-
|
| 110 |
-
include_input : Whether to include a lens that decodes the word embeddings.
|
| 111 |
-
reuse_unembedding : Weather to reuse the unembedding matrix from the model.
|
| 112 |
-
model_config : The config of the model. Used for saving and loading.
|
| 113 |
-
d_model : The models hidden size. Used for saving and loading.
|
| 114 |
-
num_layers : The number of layers in the model. Used for saving and loading.
|
| 115 |
-
vocab_size : The size of the vocabulary. Used for saving and loading.
|
| 116 |
-
|
| 117 |
-
Raises:
|
| 118 |
-
ValueError: if neither a model or d_model, num_layers, and vocab_size,
|
| 119 |
-
are provided.
|
| 120 |
-
"""
|
| 121 |
-
super().__init__()
|
| 122 |
-
|
| 123 |
-
self.extra_layers = th.nn.Sequential()
|
| 124 |
-
|
| 125 |
-
if (
|
| 126 |
-
model
|
| 127 |
-
is None
|
| 128 |
-
== (d_model is None or num_layers is None or vocab_size is None)
|
| 129 |
-
):
|
| 130 |
-
raise ValueError(
|
| 131 |
-
"Must provide either a model or d_model, num_layers, and vocab_size"
|
| 132 |
-
)
|
| 133 |
-
|
| 134 |
-
# Initializing from scratch without a model
|
| 135 |
-
if not model:
|
| 136 |
-
assert d_model and num_layers and vocab_size
|
| 137 |
-
self.layer_norm = th.nn.LayerNorm(d_model)
|
| 138 |
-
self.unembedding = th.nn.Linear(d_model, vocab_size, bias=False)
|
| 139 |
-
|
| 140 |
-
# Use HuggingFace methods to get decoder layers
|
| 141 |
-
else:
|
| 142 |
-
assert not (d_model or num_layers or vocab_size)
|
| 143 |
-
d_model = model.config.hidden_size
|
| 144 |
-
num_layers = model.config.num_hidden_layers
|
| 145 |
-
vocab_size = model.config.vocab_size
|
| 146 |
-
assert isinstance(d_model, int) and isinstance(vocab_size, int)
|
| 147 |
-
|
| 148 |
-
model_config = model.config.to_dict() # type: ignore[F841]
|
| 149 |
-
|
| 150 |
-
# Currently we convert the decoder to full precision
|
| 151 |
-
self.unembedding = deepcopy(model.get_output_embeddings()).float()
|
| 152 |
-
if ln := get_final_norm(model):
|
| 153 |
-
self.layer_norm = deepcopy(ln).float()
|
| 154 |
-
else:
|
| 155 |
-
self.layer_norm = th.nn.Identity()
|
| 156 |
-
|
| 157 |
-
if extra_layers:
|
| 158 |
-
_, layers = get_transformer_layers(model)
|
| 159 |
-
self.extra_layers.extend(
|
| 160 |
-
[maybe_wrap(layer) for layer in layers[-extra_layers:]]
|
| 161 |
-
)
|
| 162 |
-
|
| 163 |
-
# Save config for later
|
| 164 |
-
config_keys = set(inspect.getfullargspec(TunedLensOld).kwonlyargs)
|
| 165 |
-
self.config = {k: v for k, v in locals().items() if k in config_keys}
|
| 166 |
-
del model_config
|
| 167 |
-
|
| 168 |
-
# Try to prevent finetuning the decoder
|
| 169 |
-
assert d_model and num_layers
|
| 170 |
-
self.layer_norm.requires_grad_(False)
|
| 171 |
-
self.unembedding.requires_grad_(False)
|
| 172 |
-
|
| 173 |
-
out_features = d_model if reuse_unembedding else vocab_size
|
| 174 |
-
translator = th.nn.Linear(d_model, out_features, bias=bias)
|
| 175 |
-
if not reuse_unembedding:
|
| 176 |
-
translator.weight.data = self.unembedding.weight.data.clone()
|
| 177 |
-
translator.bias.data.zero_()
|
| 178 |
-
else:
|
| 179 |
-
translator.weight.data.zero_()
|
| 180 |
-
translator.bias.data.zero_()
|
| 181 |
-
|
| 182 |
-
self.add_module("input_translator", translator if include_input else None)
|
| 183 |
-
# Don't include the final layer
|
| 184 |
-
num_layers -= 1
|
| 185 |
-
|
| 186 |
-
self.layer_translators = th.nn.ModuleList(
|
| 187 |
-
[deepcopy(translator) for _ in range(num_layers)]
|
| 188 |
-
)
|
| 189 |
-
|
| 190 |
-
def __getitem__(self, item: int) -> th.nn.Module:
|
| 191 |
-
"""Get the probe module at the given index."""
|
| 192 |
-
if isinstance(self.input_translator, th.nn.Module):
|
| 193 |
-
if item == 0:
|
| 194 |
-
return self.input_translator
|
| 195 |
-
else:
|
| 196 |
-
item -= 1
|
| 197 |
-
|
| 198 |
-
return self.layer_translators[item]
|
| 199 |
-
|
| 200 |
-
def __iter__(self) -> Generator[th.nn.Module, None, None]:
|
| 201 |
-
"""Get iterator over the translators within the lens."""
|
| 202 |
-
if isinstance(self.input_translator, th.nn.Module):
|
| 203 |
-
yield self.input_translator
|
| 204 |
-
|
| 205 |
-
yield from self.layer_translators
|
| 206 |
-
|
| 207 |
-
@classmethod
|
| 208 |
-
def load(cls, resource_id: str, **kwargs) -> "TunedLensOld":
|
| 209 |
-
"""Load a tuned lens from a or hugging face hub.
|
| 210 |
-
|
| 211 |
-
Args:
|
| 212 |
-
resource_id : The path to the directory containing the config and checkpoint
|
| 213 |
-
or the name of the model on the hugging face hub.
|
| 214 |
-
**kwargs : Additional arguments to pass to torch.load.
|
| 215 |
-
|
| 216 |
-
Returns:
|
| 217 |
-
A TunedLensOld instance.
|
| 218 |
-
"""
|
| 219 |
-
config_path, ckpt_path = load_lens_artifacts(resource_id)
|
| 220 |
-
# Load config
|
| 221 |
-
with open(config_path, "r") as f:
|
| 222 |
-
config = json.load(f)
|
| 223 |
-
|
| 224 |
-
# Load parameters
|
| 225 |
-
state = th.load(ckpt_path, **kwargs)
|
| 226 |
-
|
| 227 |
-
# Backwards compatibility we really need to stop renaming things
|
| 228 |
-
keys = list(state.keys())
|
| 229 |
-
for key in keys:
|
| 230 |
-
for old_key in ["probe", "adapter"]:
|
| 231 |
-
if old_key in key:
|
| 232 |
-
warn(
|
| 233 |
-
f"Loading a checkpoint with a '{old_key}' key. "
|
| 234 |
-
"This is deprecated and may be removed in a future version. "
|
| 235 |
-
)
|
| 236 |
-
new_key = key.replace(old_key, "translator")
|
| 237 |
-
state[new_key] = state.pop(key)
|
| 238 |
-
|
| 239 |
-
# Drop unrecognized config keys
|
| 240 |
-
unrecognized = set(config) - set(inspect.getfullargspec(cls).kwonlyargs)
|
| 241 |
-
for key in unrecognized:
|
| 242 |
-
warn(f"Ignoring config key '{key}'")
|
| 243 |
-
del config[key]
|
| 244 |
-
|
| 245 |
-
lens = cls(**config)
|
| 246 |
-
|
| 247 |
-
if num_extras := config.get("extra_layers"):
|
| 248 |
-
# This is sort of a hack but AutoConfig doesn't appear to have a from_dict
|
| 249 |
-
# for some reason.
|
| 250 |
-
from transformers.models.auto import CONFIG_MAPPING
|
| 251 |
-
|
| 252 |
-
model_conf_dict = config.get("model_config")
|
| 253 |
-
del model_conf_dict["torch_dtype"]
|
| 254 |
-
assert model_conf_dict, "Need a 'model_config' entry to load extra layers"
|
| 255 |
-
|
| 256 |
-
model_type = model_conf_dict["model_type"]
|
| 257 |
-
config_cls = CONFIG_MAPPING[model_type]
|
| 258 |
-
model_config = config_cls.from_dict(model_conf_dict)
|
| 259 |
-
|
| 260 |
-
lens.extra_layers = th.nn.Sequential(
|
| 261 |
-
*[
|
| 262 |
-
instantiate_layer(
|
| 263 |
-
model_config, model_config.num_hidden_layers - i - 1, model_type
|
| 264 |
-
)
|
| 265 |
-
for i in range(num_extras)
|
| 266 |
-
]
|
| 267 |
-
)
|
| 268 |
-
|
| 269 |
-
lens.load_state_dict(state)
|
| 270 |
-
return lens
|
| 271 |
-
|
| 272 |
-
def save(
|
| 273 |
-
self,
|
| 274 |
-
path: Union[Path, str],
|
| 275 |
-
ckpt: str = "params.pt",
|
| 276 |
-
config: str = "config.json",
|
| 277 |
-
) -> None:
|
| 278 |
-
"""Save the lens to a directory.
|
| 279 |
-
|
| 280 |
-
Args:
|
| 281 |
-
path : The path to the directory to save the lens to.
|
| 282 |
-
ckpt : The name of the checkpoint file to save the parameters to.
|
| 283 |
-
config : The name of the config file to save the config to.
|
| 284 |
-
"""
|
| 285 |
-
path = Path(path)
|
| 286 |
-
path.mkdir(exist_ok=True, parents=True)
|
| 287 |
-
th.save(self.state_dict(), path / ckpt)
|
| 288 |
-
|
| 289 |
-
with open(path / config, "w") as f:
|
| 290 |
-
json.dump(self.config, f)
|
| 291 |
-
|
| 292 |
-
def normalize_(self):
|
| 293 |
-
"""Canonicalize the transforms by centering their weights and biases."""
|
| 294 |
-
for linear in self:
|
| 295 |
-
assert isinstance(linear, th.nn.Linear)
|
| 296 |
-
|
| 297 |
-
A, b = linear.weight.data, linear.bias.data
|
| 298 |
-
A -= A.mean(dim=0, keepdim=True)
|
| 299 |
-
b -= b.mean()
|
| 300 |
-
|
| 301 |
-
def transform_hidden(self, h: th.Tensor, idx: int) -> th.Tensor:
|
| 302 |
-
"""Transform hidden state from layer `idx`."""
|
| 303 |
-
if not self.config["reuse_unembedding"]:
|
| 304 |
-
raise RuntimeError("TunedLensOld.transform_hidden requires reuse_unembedding")
|
| 305 |
-
|
| 306 |
-
# Note that we add the translator output residually, in contrast to the formula
|
| 307 |
-
# in the paper. By parametrizing it this way we ensure that weight decay
|
| 308 |
-
# regularizes the transform toward the identity, not the zero transformation.
|
| 309 |
-
return h + self[idx](h)
|
| 310 |
-
|
| 311 |
-
def to_logits(self, h: th.Tensor) -> th.Tensor:
|
| 312 |
-
"""Decode a hidden state into logits."""
|
| 313 |
-
h = self.extra_layers(h)
|
| 314 |
-
while isinstance(h, tuple):
|
| 315 |
-
h, *_ = h
|
| 316 |
-
|
| 317 |
-
return self.unembedding(self.layer_norm(h))
|
| 318 |
-
|
| 319 |
-
def forward(self, h: th.Tensor, idx: int) -> th.Tensor:
|
| 320 |
-
"""Transform and then decode the hidden states into logits."""
|
| 321 |
-
# Sanity check to make sure we don't finetune the decoder
|
| 322 |
-
# if any(p.requires_grad for p in self.parameters(recurse=False)):
|
| 323 |
-
# raise RuntimeError("Make sure to freeze the decoder")
|
| 324 |
-
|
| 325 |
-
# We're learning a separate unembedding for each layer
|
| 326 |
-
if not self.config["reuse_unembedding"]:
|
| 327 |
-
h_ = self.layer_norm(h)
|
| 328 |
-
return self[idx](h_)
|
| 329 |
-
|
| 330 |
-
h = self.transform_hidden(h, idx)
|
| 331 |
-
return self.to_logits(h)
|
| 332 |
-
|
| 333 |
-
def __len__(self) -> int:
|
| 334 |
-
"""Return the number of layer translators in the lens."""
|
| 335 |
-
N = len(self.layer_translators)
|
| 336 |
-
if self.input_translator:
|
| 337 |
-
N += 1
|
| 338 |
-
|
| 339 |
-
return N
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
if __name__ == "__main__":
|
| 343 |
-
parser = argparse.ArgumentParser()
|
| 344 |
-
parser.add_argument("--model", type=str, default="gpt2")
|
| 345 |
-
parser.add_argument("--resource-id", type=str, default="gpt2")
|
| 346 |
-
parser.add_argument("--output-dir", type=str, default="lens/gpt2")
|
| 347 |
-
args = parser.parse_args()
|
| 348 |
-
|
| 349 |
-
model = AutoModelForCausalLM.from_pretrained(args.model)
|
| 350 |
-
revision = model_info(args.model).sha
|
| 351 |
-
model.eval()
|
| 352 |
-
model.requires_grad_(False)
|
| 353 |
-
|
| 354 |
-
device = th.device("cuda:0" if th.cuda.is_available() else "cpu")
|
| 355 |
-
|
| 356 |
-
print("Loading old lens")
|
| 357 |
-
tuned_lens_old = TunedLensOld.load(args.resource_id, map_location=device)
|
| 358 |
-
|
| 359 |
-
print("Initializing new lens")
|
| 360 |
-
tuned_lens = TunedLens.from_model(
|
| 361 |
-
model, bias=tuned_lens_old.config['bias'], revision=revision
|
| 362 |
-
)
|
| 363 |
-
|
| 364 |
-
for i in tqdm(range(len(tuned_lens_old)), desc="Copying parameters"):
|
| 365 |
-
tuned_lens[i].load_state_dict(tuned_lens_old[i].state_dict())
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
tuned_lens = tuned_lens.to(device)
|
| 369 |
-
tuned_lens_old = tuned_lens_old.to(device)
|
| 370 |
-
model = model.to(device)
|
| 371 |
-
|
| 372 |
-
# Fuzz the new lens against the old one's
|
| 373 |
-
with th.no_grad():
|
| 374 |
-
for i in tqdm(range(len(tuned_lens)), desc="Fuzzing layers"):
|
| 375 |
-
for _ in range(10):
|
| 376 |
-
a = th.randn(1, 1, tuned_lens.config.d_model, device=device)
|
| 377 |
-
logits_new = tuned_lens(a, i)
|
| 378 |
-
logits_old = tuned_lens_old(a, i)
|
| 379 |
-
log_ps_new = logits_new.log_softmax(-1)
|
| 380 |
-
log_ps_old = logits_old.log_softmax(-1)
|
| 381 |
-
print("js div", js_divergence(log_ps_new, log_ps_old))
|
| 382 |
-
assert (th.allclose(log_ps_new, log_ps_old, atol=1e-4)), (log_ps_new - log_ps_old).abs().max()
|
| 383 |
-
print("Saving new l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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
migrate.sh
DELETED
|
@@ -1,12 +0,0 @@
|
|
| 1 |
-
#!/bin/bash
|
| 2 |
-
|
| 3 |
-
set -e
|
| 4 |
-
|
| 5 |
-
for i in pythia-70m-deduped-v0,EleutherAI/pythia-70m-deduped-v0
|
| 6 |
-
do
|
| 7 |
-
IFS=","
|
| 8 |
-
set -- $i
|
| 9 |
-
echo "migrating $2"
|
| 10 |
-
CUDA_VISIBLE_DEVICES=-1 python3 lens_migration.py --model $2 --resource-id $1 --output lens/$1
|
| 11 |
-
git commit -am "$1 migrated"
|
| 12 |
-
done
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|