| {"repo": "AlignmentResearch/tuned-lens", "n_pairs": 34, "version": "v2_function_scoped", "contexts": {"tests/plotting/test_token_formatter.py::12": {"resolved_imports": ["tuned_lens/plotting/token_formatter.py"], "used_names": [], "enclosing_function": "test_format_non_string", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_lenses.py::146": {"resolved_imports": ["tuned_lens/load_artifacts.py", "tuned_lens/nn/lenses.py", "tuned_lens/nn/unembed.py"], "used_names": ["TunedLens"], "enclosing_function": "test_tuned_lens_generate_smoke", "extracted_code": "# Source: tuned_lens/nn/lenses.py\nclass TunedLens(Lens):\n \"\"\"A tuned lens for decoding hidden states into logits.\"\"\"\n\n config: TunedLensConfig\n unembed: Unembed\n layer_translators: th.nn.ModuleList\n\n def __init__(\n self,\n unembed: Unembed,\n config: TunedLensConfig,\n ):\n \"\"\"Create a TunedLens.\n\n Args:\n unembed: The unembed operation to use.\n config: The configuration for this lens.\n \"\"\"\n super().__init__(unembed)\n\n self.config = config\n unembed_hash = unembed.unembedding_hash()\n config.unembed_hash = unembed_hash\n\n # The unembedding might be int8 if we're using bitsandbytes\n w = unembed.unembedding.weight\n dtype = w.dtype if th.is_floating_point(w) else th.float16\n\n translator = th.nn.Linear(\n config.d_model, config.d_model, bias=config.bias, dtype=dtype\n )\n translator.weight.data.zero_()\n translator.bias.data.zero_()\n\n # Don't include the final layer since it does not need a translator\n self.layer_translators = th.nn.ModuleList(\n [deepcopy(translator) for _ in range(self.config.num_hidden_layers)]\n )\n\n def __getitem__(self, item: int) -> th.nn.Module:\n \"\"\"Get the probe module at the given index.\"\"\"\n return self.layer_translators[item]\n\n def __iter__(self) -> Generator[th.nn.Module, None, None]:\n \"\"\"Get iterator over the translators within the lens.\"\"\"\n yield from self.layer_translators\n\n @classmethod\n def from_model(\n cls,\n model: PreTrainedModel,\n model_revision: Optional[str] = None,\n bias: bool = True,\n ) -> \"TunedLens\":\n \"\"\"Create a lens from a pretrained model.\n\n Args:\n model: The model to create the lens from.\n model_revision: The git revision of the model to used.\n bias: Whether to use a bias in the linear translators.\n\n Returns:\n A TunedLens instance.\n \"\"\"\n unembed = Unembed(model)\n config = TunedLensConfig(\n base_model_name_or_path=model.config.name_or_path,\n base_model_revision=model_revision,\n d_model=model.config.hidden_size,\n num_hidden_layers=model.config.num_hidden_layers,\n bias=bias,\n )\n\n return cls(unembed, config)\n\n @classmethod\n def from_model_and_pretrained(\n cls,\n model: PreTrainedModel,\n lens_resource_id: Optional[str] = None,\n **kwargs,\n ) -> \"TunedLens\":\n \"\"\"Load a tuned lens from a folder or hugging face hub.\n\n Args:\n model: The model to create the lens from.\n lens_resource_id: The resource id of the lens to load. Defaults to the\n model's name_or_path.\n **kwargs: Additional arguments to pass to\n :func:`tuned_lens.load_artifacts.load_lens_artifacts` and\n `th.load <https://pytorch.org/docs/stable/generated/torch.load.html>`_.\n\n Returns:\n A TunedLens instance whose unembedding is derived from the given model\n and whose layer translators are loaded from the given resource id.\n \"\"\"\n if lens_resource_id is None:\n lens_resource_id = model.config.name_or_path\n\n return cls.from_unembed_and_pretrained(\n Unembed(model), lens_resource_id, **kwargs\n )\n\n @classmethod\n def from_unembed_and_pretrained(\n cls,\n unembed: Unembed,\n lens_resource_id: str,\n **kwargs,\n ) -> \"TunedLens\":\n \"\"\"Load a tuned lens from a folder or hugging face hub.\n\n Args:\n unembed: The unembed operation to use for the lens.\n lens_resource_id: The resource id of the lens to load.\n **kwargs: Additional arguments to pass to\n :func:`tuned_lens.load_artifacts.load_lens_artifacts` and\n `th.load <https://pytorch.org/docs/stable/generated/torch.load.html>`_.\n\n Returns:\n A TunedLens instance.\n \"\"\"\n # Validate kwargs\n load_artifact_varnames = load_artifacts.load_lens_artifacts.__code__.co_varnames\n\n config_path, ckpt_path = load_artifacts.load_lens_artifacts(\n resource_id=lens_resource_id,\n **{k: v for k, v in kwargs.items() if k in load_artifact_varnames},\n )\n\n with open(config_path, \"r\") as f:\n config = TunedLensConfig.from_dict(json.load(f))\n\n # validate the unembed is the same as the one used to train the lens\n if config.unembed_hash and unembed.unembedding_hash() != config.unembed_hash:\n logger.warning(\n \"The unembedding matrix hash does not match the lens' hash.\"\n \"This lens may have been trained with a different unembedding.\"\n )\n\n # Create the lens\n lens = cls(unembed, config)\n\n th_load_kwargs = {\n **{k: v for k, v in kwargs.items() if k not in load_artifact_varnames}\n }\n # Load parameters\n state = th.load(ckpt_path, **th_load_kwargs)\n\n lens.layer_translators.load_state_dict(state)\n\n return lens\n\n def save(\n self,\n path: Union[Path, str],\n ckpt: str = \"params.pt\",\n config: str = \"config.json\",\n ) -> None:\n \"\"\"Save the lens to a directory.\n\n Args:\n path : The path to the directory to save the lens to.\n ckpt : The name of the checkpoint file to save the parameters to.\n config : The name of the config file to save the config to.\n \"\"\"\n path = Path(path)\n path.mkdir(exist_ok=True, parents=True)\n state_dict = self.layer_translators.state_dict()\n\n th.save(state_dict, path / ckpt)\n with open(path / config, \"w\") as f:\n json.dump(self.config.to_dict(), f)\n\n def transform_hidden(self, h: th.Tensor, idx: int) -> th.Tensor:\n \"\"\"Transform hidden state from layer `idx`.\"\"\"\n # Note that we add the translator output residually, in contrast to the formula\n # in the paper. By parametrizing it this way we ensure that weight decay\n # regularizes the transform toward the identity, not the zero transformation.\n return h + self[idx](h)\n\n def forward(self, h: th.Tensor, idx: int) -> th.Tensor:\n \"\"\"Transform and then decode the hidden states into logits.\"\"\"\n h = self.transform_hidden(h, idx)\n return self.unembed.forward(h)\n\n def __len__(self) -> int:\n \"\"\"Return the number of layer translators in the lens.\"\"\"\n return len(self.layer_translators)\n\n @th.inference_mode()\n def generate(\n self,\n model: PreTrainedModel,\n layer: int,\n input_ids: th.Tensor,\n do_sample: bool = True,\n temp: float = 1.0,\n max_new_tokens: int = 100,\n ) -> th.Tensor:\n \"\"\"Generate from the tuned lens at the given layer.\n\n Args:\n model: The base model the generate from. Usually the model this lens trained\n on.\n layer: The layer to generate from.\n input_ids: (batch x prompt_len) The input ids to generate from.\n do_sample: Whether to use sampling or greedy decoding.\n temp: The temperature to use for sampling.\n max_new_tokens: The maximum number of tokens to generate.\n\n Returns:\n The prompt concatenated with the newly generated tokens.\n \"\"\"\n eos_token = model.generation_config.eos_token_id\n\n tokens = input_ids\n if tokens.ndim == 1:\n tokens = tokens.unsqueeze(0)\n batch, prompt_len = tokens.shape\n del prompt_len\n past_key_values = None\n done = th.zeros(batch, dtype=th.bool)\n\n for _ in range(max_new_tokens):\n output = model(\n input_ids=tokens,\n output_hidden_states=True,\n use_cache=True,\n past_key_values=past_key_values,\n )\n past_key_values = output.past_key_values\n hidden = output.hidden_states[layer]\n new_hidden = hidden[:, -1, :]\n new_logits = self.forward(new_hidden, layer)\n if do_sample:\n new_logits = new_logits / temp\n probs = new_logits.softmax(dim=-1)\n new_tokens = th.multinomial(probs, num_samples=1)\n else:\n new_tokens = new_logits.argmax(dim=-1, keepdim=True)\n\n # Once a sequence has generated an EOS token, it should not generate any\n # other tokens.\n done = done | (new_tokens == eos_token)\n new_tokens = new_tokens.masked_fill(done, eos_token)\n tokens = th.cat([tokens, new_tokens], dim=-1)\n # Halt generation if all sequences have generated an EOS token.\n if done.all():\n break\n\n return tokens", "n_imports_parsed": 8, "n_files_resolved": 3, "n_chars_extracted": 8991}, "tests/scripts/test_integration.py::85": {"resolved_imports": ["tuned_lens/__main__.py"], "used_names": ["Path", "main", "pytest"], "enclosing_function": "test_train_subcommand_fails_when_not_enough_data_given", "extracted_code": "# Source: tuned_lens/__main__.py\ndef main(args: Optional[list[str]] = None):\n \"\"\"Entry point for the CLI.\"\"\"\n parser = ArgumentParser(conflict_resolution=ConflictResolution.EXPLICIT)\n parser.add_arguments(Main, dest=\"prog\")\n args = parser.parse_args(args=args)\n prog: Main = args.prog\n prog.execute()", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 318}, "tests/test_subspaces.py::21": {"resolved_imports": ["tuned_lens/causal/subspaces.py"], "used_names": ["pytest", "remove_subspace"], "enclosing_function": "test_remove_subspace", "extracted_code": "# Source: tuned_lens/causal/subspaces.py\ndef remove_subspace(\n u: th.Tensor,\n A: th.Tensor,\n mode: Literal[\"mean\", \"resample\", \"zero\"] = \"zero\",\n orthonormal: bool = False,\n) -> th.Tensor:\n \"\"\"Remove all information in `u` along the column space of `A`.\n\n This can be done by zero, mean, or resample ablation. With zero ablation,\n `u` is projected onto the orthogonal complement of col(`A`), so the resulting\n vectors are orthogonal to every column in `A`. With mean ablation, `u` is projected\n onto the subspace s.t. the angles between the resulting vectors and the columns of\n `A` are equal to their mean values. With resample ablation, the variation in `u`\n is shuffled across vectors.\n\n Args:\n u: The vectors to be projected.\n A: Either a 2D matrix whose column space is to be removed, or a 1D vector whose\n span is to be removed.\n mode: Which method to use for removing information along the subspace.\n Defaults to `\"zero\"`.\n orthonormal: Whether to assume `A` is orthonormal. Defaults to `False`.\n\n Returns:\n th.Tensor: The transformed vectors.\n \"\"\"\n if A.ndim == 1:\n A = A[..., None]\n\n d, _ = A.shape\n if u.shape[-1] != d:\n raise ValueError(f\"Last dimension of u must be {d}, but is {u.shape[-1]}\")\n\n # https://en.wikipedia.org/wiki/Projection_(linear_algebra)#Properties_and_special_cases\n if orthonormal:\n proj = A @ A.mT\n else:\n proj = A @ th.linalg.solve(A.mT @ A, A.mT)\n\n if mode == \"zero\":\n dummy = -u\n else:\n samples = u.flatten(0, -2)\n N = samples.shape[0]\n if N < 2:\n raise ValueError(\"Need at least 2 vectors for mean and resample ablation\")\n\n if mode == \"mean\":\n dummy = samples.mean(0) - u\n elif mode == \"resample\":\n # Shuffle the rows of `samples` without fixed points.\n dummy = derange(samples).view_as(u) - u\n else:\n raise ValueError(f\"Unknown mode {mode}\")\n\n return u + th.einsum(\"ij,...j->...i\", proj, dummy)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 2090}, "tests/test_distance.py::19": {"resolved_imports": ["tuned_lens/stats/distance.py"], "used_names": ["Categorical", "js_divergence", "kl_divergence"], "enclosing_function": "test_js_divergence", "extracted_code": "# Source: tuned_lens/stats/distance.py\ndef js_divergence(logit_p: th.Tensor, logit_q: th.Tensor, dim: int = -1) -> th.Tensor:\n \"\"\"Compute the Jensen-Shannon divergence between two sets of logits.\n\n Conceptually, the JSD is the info value of learning which of two distributions,\n P or Q, that a random variable is drawn from, starting from a uniform prior over\n P and Q. Since the entropy of a Bernoulli variable is at most ln(2), the JSD is\n guaranteed to be in the range [0, ln(2)]. It is also symmetric and finite even\n for distributions with disjoint supports.\n\n Mathematically, the JSD is simply [KL(P || M) + KL(Q || M)] / 2, where M\n is the mean of P and Q.\n \"\"\"\n log_p = logit_p.log_softmax(dim)\n log_q = logit_q.log_softmax(dim)\n\n # Mean of P and Q\n log_m = th.stack([log_p, log_q]).sub(math.log(2)).logsumexp(0)\n\n kl_p = th.sum(log_p.exp() * (log_p - log_m), dim)\n kl_q = th.sum(log_q.exp() * (log_q - log_m), dim)\n return 0.5 * (kl_p + kl_q)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 999}, "tests/plotting/test_trajectory_plotting.py::115": {"resolved_imports": ["tuned_lens/plotting/trajectory_plotting.py"], "used_names": ["TrajectoryStatistic"], "enclosing_function": "test_stride_method", "extracted_code": "# Source: tuned_lens/plotting/trajectory_plotting.py\nclass TrajectoryStatistic:\n \"\"\"This class represents a trajectory statistic that can be visualized.\n\n For example, the entropy of the lens predictions at each layer.\n \"\"\"\n\n name: str\n \"\"\"The name of the statistic. For example, \"entropy\".\"\"\"\n stats: NDArray[np.float32]\n \"\"\"(n_layers x sequence_length) value of the statistic across layer and position.\"\"\"\n sequence_labels: Optional[NDArray[np.str_]] = None\n \"\"\"(sequence_length) labels for the sequence dimension e.g. input tokens.\"\"\"\n trajectory_labels: Optional[TrajectoryLabels] = None\n \"\"\"Labels for each layer and position in the stream. For example, the top 1\n prediction from the lens at each layer.\"\"\"\n units: Optional[str] = None\n \"\"\"The units of the statistic.\"\"\"\n max: Optional[float] = None\n \"\"\"The maximum value of the statistic.\"\"\"\n min: Optional[float] = None\n \"\"\"The minimum value of the statistic.\"\"\"\n includes_output: bool = True\n \"\"\"Whether the statistic includes the final output layer.\"\"\"\n\n _layer_labels: Optional[NDArray[np.str_]] = None\n\n def __post_init__(self) -> None:\n \"\"\"Validate class invariants.\"\"\"\n assert len(self.stats.shape) == 2, f\"{self.stats.shape} != (n_layers, seq_len)\"\n\n assert self.trajectory_labels is None or (\n self.trajectory_labels.label_strings.shape == self.stats.shape\n ), f\"{self.trajectory_labels.label_strings.shape} != {self.stats.shape}\"\n\n assert self.sequence_labels is None or (\n self.sequence_labels.shape[-1] == self.stats.shape[-1]\n ), f\"{self.sequence_labels.shape[-1]} != {self.stats.shape[-1]}\"\n\n if self._layer_labels is None:\n if self.includes_output:\n self._layer_labels = np.array(\n [*map(str, range(self.stats.shape[0] - 1)), \"output\"]\n )\n else:\n self._layer_labels = np.array([*map(str, range(self.stats.shape[0]))])\n\n def clip(self, min: float, max: float) -> \"TrajectoryStatistic\":\n \"\"\"Return a new TrajectoryStatistic with the given min and max.\n\n Args:\n min : The minimum value to clip to.\n max : The maximum value to clip to.\n\n Returns:\n A new TrajectoryStatistic with the given min and max.\n \"\"\"\n assert min < max, f\"min must be less than max, got {min} >= {max}\"\n return replace(\n self,\n stats=np.clip(self.stats, min, max),\n max=max,\n min=min,\n )\n\n def stride(self, stride: int) -> \"TrajectoryStatistic\":\n \"\"\"Return a new TrajectoryStatistic with the given stride.\n\n Args:\n stride : The number of layers between each layer we keep.\n\n Returns:\n A new TrajectoryStatistic with the given stride.\n \"\"\"\n assert stride > 0, f\"stride must be positive, got {stride}\"\n assert self._layer_labels is not None\n return replace(\n self,\n stats=_stride_keep_last(self.stats, stride),\n trajectory_labels=None\n if self.trajectory_labels is None\n else self.trajectory_labels.stride(stride),\n _layer_labels=None\n if self._layer_labels is None\n else _stride_keep_last(self._layer_labels, stride),\n )\n\n def heatmap(\n self,\n colorscale: str = \"rdbu_r\",\n log_scale: bool = False,\n **kwargs,\n ) -> go.Heatmap:\n \"\"\"Returns a Plotly Heatmap object for this statistic.\n\n Args:\n colorscale : The colorscale to use for the heatmap.\n log_scale : Whether to use a log scale for the colorbar.\n **kwargs : Additional keyword arguments to pass to the Heatmap constructor.\n\n Returns:\n A plotly Heatmap where the x-axis is the sequence dimension, the y-axis is\n the layer dimension, and the color of each cell is the value of\n the statistic.\n \"\"\"\n max = self.max if self.max is not None else np.max(self.stats)\n min = self.min if self.min is not None else np.min(self.stats)\n heatmap_kwargs: Dict[str, Any] = dict(\n y=self._layer_labels,\n z=self.stats if not log_scale else np.log10(self.stats),\n colorbar=dict(\n title=f\"{self.name} ({self.units})\",\n titleside=\"right\",\n ),\n colorscale=colorscale,\n zmax=max if not log_scale else np.log10(max),\n zmin=min if not log_scale else np.log10(min),\n )\n\n if log_scale:\n smallest_tick = np.ceil(np.log10(min))\n biggest_tick = np.floor(np.log10(max))\n tickvals = np.arange(smallest_tick, biggest_tick + 1)\n heatmap_kwargs[\"colorbar\"] = dict(\n tickmode=\"array\",\n tickvals=tickvals,\n ticktext=[\"10^{}\".format(i) for i in tickvals],\n )\n\n if self.sequence_labels is not None:\n # Hack to ensure that Plotly doesn't de-duplicate the x-axis labels\n x_labels = [x + \"\\u200c\" * i for i, x in enumerate(self.sequence_labels)]\n heatmap_kwargs.update(x=x_labels)\n\n if self.trajectory_labels is not None:\n heatmap_kwargs.update(\n text=self.trajectory_labels.label_strings,\n texttemplate=\"<b>%{text}</b>\",\n )\n\n if self.trajectory_labels.hover_over_entries is not None:\n (\n hovertemplate,\n custom_data,\n ) = self.trajectory_labels.template_and_customdata()\n heatmap_kwargs.update(\n hoverlabel=dict(bgcolor=\"rgb(42, 42, 50)\", font_family=\"Monospace\"),\n customdata=custom_data,\n hovertemplate=hovertemplate,\n )\n\n heatmap_kwargs.update(kwargs)\n return go.Heatmap(**heatmap_kwargs)\n\n def figure(\n self,\n title: str = \"\",\n colorscale: str = \"rdbu_r\",\n token_width: int = 80,\n ) -> go.Figure:\n \"\"\"Produce a heatmap plot of the statistic.\n\n Args:\n title : The title of the plot.\n colorscale : The colorscale to use for the heatmap.\n token_width : The width of each token in the plot.\n\n Returns:\n The plotly heatmap figure.\n \"\"\"\n heatmap = self.heatmap(colorscale)\n figure_width = 200 + token_width * self.stats.shape[1]\n\n fig = go.Figure(heatmap).update_layout(\n title_text=title,\n title_x=0.5,\n width=figure_width,\n xaxis_title=\"Input\",\n yaxis_title=\"Layer\",\n )\n\n return fig", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 6803}, "tests/test_data.py::50": {"resolved_imports": ["tuned_lens/__init__.py", "tuned_lens/data.py"], "used_names": ["Dataset", "data", "math"], "enclosing_function": "test_compute_nats_to_bpb_ratio", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/plotting/test_trajectory_plotting.py::114": {"resolved_imports": ["tuned_lens/plotting/trajectory_plotting.py"], "used_names": ["TrajectoryStatistic"], "enclosing_function": "test_stride_method", "extracted_code": "# Source: tuned_lens/plotting/trajectory_plotting.py\nclass TrajectoryStatistic:\n \"\"\"This class represents a trajectory statistic that can be visualized.\n\n For example, the entropy of the lens predictions at each layer.\n \"\"\"\n\n name: str\n \"\"\"The name of the statistic. For example, \"entropy\".\"\"\"\n stats: NDArray[np.float32]\n \"\"\"(n_layers x sequence_length) value of the statistic across layer and position.\"\"\"\n sequence_labels: Optional[NDArray[np.str_]] = None\n \"\"\"(sequence_length) labels for the sequence dimension e.g. input tokens.\"\"\"\n trajectory_labels: Optional[TrajectoryLabels] = None\n \"\"\"Labels for each layer and position in the stream. For example, the top 1\n prediction from the lens at each layer.\"\"\"\n units: Optional[str] = None\n \"\"\"The units of the statistic.\"\"\"\n max: Optional[float] = None\n \"\"\"The maximum value of the statistic.\"\"\"\n min: Optional[float] = None\n \"\"\"The minimum value of the statistic.\"\"\"\n includes_output: bool = True\n \"\"\"Whether the statistic includes the final output layer.\"\"\"\n\n _layer_labels: Optional[NDArray[np.str_]] = None\n\n def __post_init__(self) -> None:\n \"\"\"Validate class invariants.\"\"\"\n assert len(self.stats.shape) == 2, f\"{self.stats.shape} != (n_layers, seq_len)\"\n\n assert self.trajectory_labels is None or (\n self.trajectory_labels.label_strings.shape == self.stats.shape\n ), f\"{self.trajectory_labels.label_strings.shape} != {self.stats.shape}\"\n\n assert self.sequence_labels is None or (\n self.sequence_labels.shape[-1] == self.stats.shape[-1]\n ), f\"{self.sequence_labels.shape[-1]} != {self.stats.shape[-1]}\"\n\n if self._layer_labels is None:\n if self.includes_output:\n self._layer_labels = np.array(\n [*map(str, range(self.stats.shape[0] - 1)), \"output\"]\n )\n else:\n self._layer_labels = np.array([*map(str, range(self.stats.shape[0]))])\n\n def clip(self, min: float, max: float) -> \"TrajectoryStatistic\":\n \"\"\"Return a new TrajectoryStatistic with the given min and max.\n\n Args:\n min : The minimum value to clip to.\n max : The maximum value to clip to.\n\n Returns:\n A new TrajectoryStatistic with the given min and max.\n \"\"\"\n assert min < max, f\"min must be less than max, got {min} >= {max}\"\n return replace(\n self,\n stats=np.clip(self.stats, min, max),\n max=max,\n min=min,\n )\n\n def stride(self, stride: int) -> \"TrajectoryStatistic\":\n \"\"\"Return a new TrajectoryStatistic with the given stride.\n\n Args:\n stride : The number of layers between each layer we keep.\n\n Returns:\n A new TrajectoryStatistic with the given stride.\n \"\"\"\n assert stride > 0, f\"stride must be positive, got {stride}\"\n assert self._layer_labels is not None\n return replace(\n self,\n stats=_stride_keep_last(self.stats, stride),\n trajectory_labels=None\n if self.trajectory_labels is None\n else self.trajectory_labels.stride(stride),\n _layer_labels=None\n if self._layer_labels is None\n else _stride_keep_last(self._layer_labels, stride),\n )\n\n def heatmap(\n self,\n colorscale: str = \"rdbu_r\",\n log_scale: bool = False,\n **kwargs,\n ) -> go.Heatmap:\n \"\"\"Returns a Plotly Heatmap object for this statistic.\n\n Args:\n colorscale : The colorscale to use for the heatmap.\n log_scale : Whether to use a log scale for the colorbar.\n **kwargs : Additional keyword arguments to pass to the Heatmap constructor.\n\n Returns:\n A plotly Heatmap where the x-axis is the sequence dimension, the y-axis is\n the layer dimension, and the color of each cell is the value of\n the statistic.\n \"\"\"\n max = self.max if self.max is not None else np.max(self.stats)\n min = self.min if self.min is not None else np.min(self.stats)\n heatmap_kwargs: Dict[str, Any] = dict(\n y=self._layer_labels,\n z=self.stats if not log_scale else np.log10(self.stats),\n colorbar=dict(\n title=f\"{self.name} ({self.units})\",\n titleside=\"right\",\n ),\n colorscale=colorscale,\n zmax=max if not log_scale else np.log10(max),\n zmin=min if not log_scale else np.log10(min),\n )\n\n if log_scale:\n smallest_tick = np.ceil(np.log10(min))\n biggest_tick = np.floor(np.log10(max))\n tickvals = np.arange(smallest_tick, biggest_tick + 1)\n heatmap_kwargs[\"colorbar\"] = dict(\n tickmode=\"array\",\n tickvals=tickvals,\n ticktext=[\"10^{}\".format(i) for i in tickvals],\n )\n\n if self.sequence_labels is not None:\n # Hack to ensure that Plotly doesn't de-duplicate the x-axis labels\n x_labels = [x + \"\\u200c\" * i for i, x in enumerate(self.sequence_labels)]\n heatmap_kwargs.update(x=x_labels)\n\n if self.trajectory_labels is not None:\n heatmap_kwargs.update(\n text=self.trajectory_labels.label_strings,\n texttemplate=\"<b>%{text}</b>\",\n )\n\n if self.trajectory_labels.hover_over_entries is not None:\n (\n hovertemplate,\n custom_data,\n ) = self.trajectory_labels.template_and_customdata()\n heatmap_kwargs.update(\n hoverlabel=dict(bgcolor=\"rgb(42, 42, 50)\", font_family=\"Monospace\"),\n customdata=custom_data,\n hovertemplate=hovertemplate,\n )\n\n heatmap_kwargs.update(kwargs)\n return go.Heatmap(**heatmap_kwargs)\n\n def figure(\n self,\n title: str = \"\",\n colorscale: str = \"rdbu_r\",\n token_width: int = 80,\n ) -> go.Figure:\n \"\"\"Produce a heatmap plot of the statistic.\n\n Args:\n title : The title of the plot.\n colorscale : The colorscale to use for the heatmap.\n token_width : The width of each token in the plot.\n\n Returns:\n The plotly heatmap figure.\n \"\"\"\n heatmap = self.heatmap(colorscale)\n figure_width = 200 + token_width * self.stats.shape[1]\n\n fig = go.Figure(heatmap).update_layout(\n title_text=title,\n title_x=0.5,\n width=figure_width,\n xaxis_title=\"Input\",\n yaxis_title=\"Layer\",\n )\n\n return fig", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 6803}, "tests/test_model_surgery.py::23": {"resolved_imports": ["tuned_lens/__init__.py", "tuned_lens/model_surgery.py"], "used_names": ["PreTrainedModel", "model_surgery"], "enclosing_function": "test_get_layers_from_model", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/plotting/test_trajectory_plotting.py::28": {"resolved_imports": ["tuned_lens/plotting/trajectory_plotting.py"], "used_names": ["TrajectoryLabels", "TrajectoryStatistic", "pytest"], "enclosing_function": "test_trajectory_statistic_post_init", "extracted_code": "# Source: tuned_lens/plotting/trajectory_plotting.py\nclass TrajectoryLabels:\n \"\"\"Contains sets of labels for each layer and position in the residual stream.\"\"\"\n\n label_strings: NDArray[np.str_]\n \"\"\"(n_layers x sequence_length) label for each layer and position in the stream.\"\"\"\n hover_over_entries: Optional[NDArray[np.str_]] = None\n \"\"\"(n_layers x sequence_length x rows x cols) table of strings to display when\n hovering over a cell. For example, the top k prediction from the lens.\"\"\"\n\n def stride(self, stride: int) -> \"TrajectoryLabels\":\n \"\"\"Return a new TrajectoryLabels with the given stride.\n\n Args:\n stride : The number of layers between each layer we keep.\n\n Returns:\n A new TrajectoryLabels with the given stride.\n \"\"\"\n assert stride > 0, f\"stride must be positive, got {stride}\"\n return replace(\n self,\n label_strings=_stride_keep_last(self.label_strings, stride),\n hover_over_entries=None\n if self.hover_over_entries is None\n else _stride_keep_last(self.hover_over_entries, stride),\n )\n\n def template_and_customdata(\n self, col_width_limit: int = 10\n ) -> Tuple[str, NDArray[np.str_]]:\n \"\"\"Construct a template for use with Plotly's hovertemplate.\"\"\"\n assert self.hover_over_entries is not None\n n_rows, n_cols = self.hover_over_entries.shape[-2:]\n\n vec_str_len = np.vectorize(len)\n lengths = vec_str_len(self.hover_over_entries)\n max_col_lens = np.max(lengths, axis=(0, 1, 2), keepdims=True)\n max_col_lens = np.minimum(max_col_lens + 1, col_width_limit)\n\n vec_truncate = np.vectorize(trunc_string_left)\n truncated_entries = vec_truncate(self.hover_over_entries, max_col_lens)\n\n html_table = \"\"\n for row in range(n_rows):\n for col in range(n_cols):\n html_table += f\"%{{customdata[{row*n_cols + col}]}}\"\n html_table += \"<br>\"\n html_table += \"<extra></extra>\"\n customdata = truncated_entries.reshape(\n self.hover_over_entries.shape[:2] + (-1,)\n )\n return html_table, customdata\n\nclass TrajectoryStatistic:\n \"\"\"This class represents a trajectory statistic that can be visualized.\n\n For example, the entropy of the lens predictions at each layer.\n \"\"\"\n\n name: str\n \"\"\"The name of the statistic. For example, \"entropy\".\"\"\"\n stats: NDArray[np.float32]\n \"\"\"(n_layers x sequence_length) value of the statistic across layer and position.\"\"\"\n sequence_labels: Optional[NDArray[np.str_]] = None\n \"\"\"(sequence_length) labels for the sequence dimension e.g. input tokens.\"\"\"\n trajectory_labels: Optional[TrajectoryLabels] = None\n \"\"\"Labels for each layer and position in the stream. For example, the top 1\n prediction from the lens at each layer.\"\"\"\n units: Optional[str] = None\n \"\"\"The units of the statistic.\"\"\"\n max: Optional[float] = None\n \"\"\"The maximum value of the statistic.\"\"\"\n min: Optional[float] = None\n \"\"\"The minimum value of the statistic.\"\"\"\n includes_output: bool = True\n \"\"\"Whether the statistic includes the final output layer.\"\"\"\n\n _layer_labels: Optional[NDArray[np.str_]] = None\n\n def __post_init__(self) -> None:\n \"\"\"Validate class invariants.\"\"\"\n assert len(self.stats.shape) == 2, f\"{self.stats.shape} != (n_layers, seq_len)\"\n\n assert self.trajectory_labels is None or (\n self.trajectory_labels.label_strings.shape == self.stats.shape\n ), f\"{self.trajectory_labels.label_strings.shape} != {self.stats.shape}\"\n\n assert self.sequence_labels is None or (\n self.sequence_labels.shape[-1] == self.stats.shape[-1]\n ), f\"{self.sequence_labels.shape[-1]} != {self.stats.shape[-1]}\"\n\n if self._layer_labels is None:\n if self.includes_output:\n self._layer_labels = np.array(\n [*map(str, range(self.stats.shape[0] - 1)), \"output\"]\n )\n else:\n self._layer_labels = np.array([*map(str, range(self.stats.shape[0]))])\n\n def clip(self, min: float, max: float) -> \"TrajectoryStatistic\":\n \"\"\"Return a new TrajectoryStatistic with the given min and max.\n\n Args:\n min : The minimum value to clip to.\n max : The maximum value to clip to.\n\n Returns:\n A new TrajectoryStatistic with the given min and max.\n \"\"\"\n assert min < max, f\"min must be less than max, got {min} >= {max}\"\n return replace(\n self,\n stats=np.clip(self.stats, min, max),\n max=max,\n min=min,\n )\n\n def stride(self, stride: int) -> \"TrajectoryStatistic\":\n \"\"\"Return a new TrajectoryStatistic with the given stride.\n\n Args:\n stride : The number of layers between each layer we keep.\n\n Returns:\n A new TrajectoryStatistic with the given stride.\n \"\"\"\n assert stride > 0, f\"stride must be positive, got {stride}\"\n assert self._layer_labels is not None\n return replace(\n self,\n stats=_stride_keep_last(self.stats, stride),\n trajectory_labels=None\n if self.trajectory_labels is None\n else self.trajectory_labels.stride(stride),\n _layer_labels=None\n if self._layer_labels is None\n else _stride_keep_last(self._layer_labels, stride),\n )\n\n def heatmap(\n self,\n colorscale: str = \"rdbu_r\",\n log_scale: bool = False,\n **kwargs,\n ) -> go.Heatmap:\n \"\"\"Returns a Plotly Heatmap object for this statistic.\n\n Args:\n colorscale : The colorscale to use for the heatmap.\n log_scale : Whether to use a log scale for the colorbar.\n **kwargs : Additional keyword arguments to pass to the Heatmap constructor.\n\n Returns:\n A plotly Heatmap where the x-axis is the sequence dimension, the y-axis is\n the layer dimension, and the color of each cell is the value of\n the statistic.\n \"\"\"\n max = self.max if self.max is not None else np.max(self.stats)\n min = self.min if self.min is not None else np.min(self.stats)\n heatmap_kwargs: Dict[str, Any] = dict(\n y=self._layer_labels,\n z=self.stats if not log_scale else np.log10(self.stats),\n colorbar=dict(\n title=f\"{self.name} ({self.units})\",\n titleside=\"right\",\n ),\n colorscale=colorscale,\n zmax=max if not log_scale else np.log10(max),\n zmin=min if not log_scale else np.log10(min),\n )\n\n if log_scale:\n smallest_tick = np.ceil(np.log10(min))\n biggest_tick = np.floor(np.log10(max))\n tickvals = np.arange(smallest_tick, biggest_tick + 1)\n heatmap_kwargs[\"colorbar\"] = dict(\n tickmode=\"array\",\n tickvals=tickvals,\n ticktext=[\"10^{}\".format(i) for i in tickvals],\n )\n\n if self.sequence_labels is not None:\n # Hack to ensure that Plotly doesn't de-duplicate the x-axis labels\n x_labels = [x + \"\\u200c\" * i for i, x in enumerate(self.sequence_labels)]\n heatmap_kwargs.update(x=x_labels)\n\n if self.trajectory_labels is not None:\n heatmap_kwargs.update(\n text=self.trajectory_labels.label_strings,\n texttemplate=\"<b>%{text}</b>\",\n )\n\n if self.trajectory_labels.hover_over_entries is not None:\n (\n hovertemplate,\n custom_data,\n ) = self.trajectory_labels.template_and_customdata()\n heatmap_kwargs.update(\n hoverlabel=dict(bgcolor=\"rgb(42, 42, 50)\", font_family=\"Monospace\"),\n customdata=custom_data,\n hovertemplate=hovertemplate,\n )\n\n heatmap_kwargs.update(kwargs)\n return go.Heatmap(**heatmap_kwargs)\n\n def figure(\n self,\n title: str = \"\",\n colorscale: str = \"rdbu_r\",\n token_width: int = 80,\n ) -> go.Figure:\n \"\"\"Produce a heatmap plot of the statistic.\n\n Args:\n title : The title of the plot.\n colorscale : The colorscale to use for the heatmap.\n token_width : The width of each token in the plot.\n\n Returns:\n The plotly heatmap figure.\n \"\"\"\n heatmap = self.heatmap(colorscale)\n figure_width = 200 + token_width * self.stats.shape[1]\n\n fig = go.Figure(heatmap).update_layout(\n title_text=title,\n title_x=0.5,\n width=figure_width,\n xaxis_title=\"Input\",\n yaxis_title=\"Layer\",\n )\n\n return fig", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 8958}, "tests/test_data.py::22": {"resolved_imports": ["tuned_lens/__init__.py", "tuned_lens/data.py"], "used_names": ["Dataset", "data"], "enclosing_function": "test_chunk_and_tokenize", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/plotting/test_prediction_trajectory.py::151": {"resolved_imports": ["tuned_lens/nn/lenses.py", "tuned_lens/plotting/prediction_trajectory.py"], "used_names": ["PredictionTrajectory"], "enclosing_function": "test_rank_smoke", "extracted_code": "# Source: tuned_lens/plotting/prediction_trajectory.py\nclass PredictionTrajectory:\n \"\"\"Contains the trajectory predictions for a sequence of tokens.\n\n A prediction trajectory is the set of next token predictions produced by the\n conjunction of a lens and a model when evaluated on a specific sequence of tokens.\n This class include multiple methods for visualizing different\n aspects of the trajectory.\n \"\"\"\n\n log_probs: NDArray[np.float32]\n \"\"\"(..., n_layers, seq_len, vocab_size) The log probabilities of the predictions\n for each hidden layer + the models logits\"\"\"\n\n input_ids: NDArray[np.int64]\n \"\"\"(..., seq_len)\"\"\"\n\n targets: Optional[NDArray[np.int64]] = None\n \"\"\"(..., seq_len)\"\"\"\n\n anti_targets: Optional[NDArray[np.int64]] = None\n \"\"\"(..., seq_len)\"\"\"\n\n tokenizer: Optional[Tokenizer] = None\n\n def __post_init__(self) -> None:\n \"\"\"Validate class invariants.\"\"\"\n assert (\n self.log_probs.shape[:-3] == self.input_ids.shape[:-1]\n ), \"Batch shapes do not match log_probs.shape: {}, input_ids.shape: {}\".format(\n self.log_probs.shape, self.input_ids.shape\n )\n\n assert (\n self.log_probs.shape[-2] == self.input_ids.shape[-1]\n ), \"seq_len doesn't match log_probs.shape: {}, input_ids.shape: {}\".format(\n self.log_probs.shape, self.input_ids.shape\n )\n\n assert (\n self.targets is None or self.targets.shape == self.input_ids.shape\n ), \"Shapes don't match targets.shape: {}, input_ids.shape: {}\".format(\n self.targets.shape, self.input_ids.shape\n )\n\n assert (\n self.anti_targets is None or self.anti_targets.shape == self.input_ids.shape\n ), \"Shapes don't match anti_targets.shape: {}, input_ids.shape: {}\".format(\n self.anti_targets.shape, self.input_ids.shape\n )\n\n @property\n def n_batch_axis(self) -> int:\n \"\"\"Returns the number of batch dimensions.\"\"\"\n return len(self.batch_axes)\n\n @property\n def batch_axes(self) -> Sequence[int]:\n \"\"\"Returns the batch axes for the trajectory.\"\"\"\n return tuple(range(len(self.log_probs.shape) - 3))\n\n @property\n def batch_shape(self) -> Sequence[int]:\n \"\"\"Returns the batch shape of the trajectory.\"\"\"\n return self.log_probs.shape[:-3]\n\n @property\n def num_layers(self) -> int:\n \"\"\"Returns the number of layers in the stream not including the model output.\"\"\"\n return self.log_probs.shape[-3] - 1\n\n @property\n def num_tokens(self) -> int:\n \"\"\"Returns the number of tokens in this slice of the sequence.\"\"\"\n return self.log_probs.shape[-2]\n\n @property\n def vocab_size(self) -> int:\n \"\"\"Returns the size of the vocabulary.\"\"\"\n return self.log_probs.shape[-1]\n\n @property\n def model_log_probs(self) -> NDArray[np.float32]:\n \"\"\"Returns the log probs of the model (..., seq_len, vocab_size).\"\"\"\n return self.log_probs[..., -1, :, :]\n\n @property\n def probs(self) -> NDArray[np.float32]:\n \"\"\"Returns the probabilities of the predictions.\"\"\"\n return np.exp(self.log_probs)\n\n @classmethod\n def from_lens_and_cache(\n cls,\n lens: Lens,\n input_ids: th.Tensor,\n cache: \"tl.ActivationCache\",\n model_logits: th.Tensor,\n targets: Optional[th.Tensor] = None,\n anti_targets: Optional[th.Tensor] = None,\n residual_component: ResidualComponent = \"resid_pre\",\n mask_input: bool = False,\n ) -> \"PredictionTrajectory\":\n \"\"\"Construct a prediction trajectory from a set of residual stream vectors.\n\n Args:\n lens: A lens to use to produce the predictions.\n cache: the activation cache produced by running the model.\n input_ids: (..., seq_len) Ids that where input into the model.\n model_logits: (..., seq_len x d_vocab) the models final output logits.\n targets: (..., seq_len) the targets the model is should predict. Used\n for :meth:`cross_entropy` and :meth:`log_prob_diff` visualization.\n anti_targets: (..., seq_len) the incorrect label the model should not\n predict. Used for :meth:`log_prob_diff` visualization.\n residual_component: Name of the stream vector being visualized.\n mask_input: Whether to mask the input ids when computing the log probs.\n\n Returns:\n PredictionTrajectory constructed from the residual stream vectors.\n \"\"\"\n tokenizer = cache.model.tokenizer\n traj_log_probs = []\n for layer in range(cache.model.cfg.n_layers):\n hidden = cache[residual_component, layer]\n if input_ids.shape[-1] != hidden.shape[-2]:\n raise ValueError(\n f\"Length of input ids {input_ids.shape[-1]} does \"\n f\"not match cache sequence length {hidden.shape[-2]}.\"\n )\n\n logits = lens.forward(hidden, layer)\n\n if mask_input:\n logits[..., input_ids] = -th.finfo(hidden.dtype).max\n\n traj_log_probs.append(\n logits.log_softmax(dim=-1).detach().cpu().float().numpy()\n )\n\n model_log_probs = model_logits.log_softmax(-1).detach().cpu().float().numpy()\n\n traj_log_probs.append(model_log_probs)\n\n return cls(\n tokenizer=tokenizer,\n log_probs=np.stack(traj_log_probs, axis=-3),\n input_ids=input_ids.cpu().numpy(),\n targets=None if targets is None else targets.cpu().numpy(),\n anti_targets=None if anti_targets is None else anti_targets.cpu().numpy(),\n )\n\n @classmethod\n def from_lens_and_model(\n cls,\n lens: Lens,\n model: PreTrainedModel,\n input_ids: Sequence[int],\n tokenizer: Optional[Tokenizer] = None,\n targets: Optional[Sequence[int]] = None,\n anti_targets: Optional[Sequence[int]] = None,\n mask_input: bool = False,\n ) -> \"PredictionTrajectory\":\n \"\"\"Construct a prediction trajectory from a set of residual stream vectors.\n\n Args:\n lens: A lens to use to produce the predictions. Note this should be\n compatible with the model.\n model: A Hugging Face causal language model to use to produce\n the predictions.\n tokenizer: The tokenizer to use for decoding the input ids.\n input_ids: (seq_len) Ids that where input into the model.\n targets: (seq_len) the targets the model is should predict. Used\n for :meth:`cross_entropy` and :meth:`log_prob_diff` visualization.\n anti_targets: (seq_len) the incorrect label the model should not\n predict. Used for :meth:`log_prob_diff` visualization.\n residual_component: Name of the stream vector being visualized.\n mask_input: Whether to mask the input ids when computing the log probs.\n\n Returns:\n PredictionTrajectory constructed from the residual stream vectors.\n \"\"\"\n with th.no_grad():\n input_ids_th = th.tensor(input_ids, dtype=th.int64, device=model.device)\n outputs = model(input_ids_th.unsqueeze(0), output_hidden_states=True)\n\n # Slice arrays the specified range\n model_log_probs = (\n outputs.logits[..., :]\n .log_softmax(-1)\n .squeeze()\n .detach()\n .cpu()\n .float()\n .numpy()\n )\n stream = list(outputs.hidden_states)\n\n input_ids_np = np.array(input_ids)\n targets_np = np.array(targets) if targets is not None else None\n anti_targets_np = np.array(anti_targets) if anti_targets is not None else None\n\n # Create the stream of log probabilities from the lens\n traj_log_probs = []\n for i, h in enumerate(stream[:-1]):\n logits = lens.forward(h, i)\n\n if mask_input:\n logits[..., input_ids_np] = -th.finfo(h.dtype).max\n\n traj_log_probs.append(\n logits.log_softmax(dim=-1).squeeze().detach().cpu().float().numpy()\n )\n\n # Add model predictions\n traj_log_probs.append(model_log_probs)\n\n return cls(\n tokenizer=tokenizer,\n log_probs=np.array(traj_log_probs),\n targets=targets_np,\n input_ids=input_ids_np,\n anti_targets=anti_targets_np,\n )\n\n def _get_sequence_labels(\n self, token_formatter: Optional[TokenFormatter] = None\n ) -> Optional[NDArray[np.str_]]:\n \"\"\"Get the input labels from a batch of input ids.\"\"\"\n if self.tokenizer is None:\n return None\n\n if token_formatter is None:\n token_formatter = TokenFormatter()\n\n return _consolidate_labels_from_batch(\n tokens=token_formatter.vectorized_format(\n _ids_to_tokens(self.input_ids, self.tokenizer)\n ),\n n_batch_axes=self.n_batch_axis,\n )\n\n def _get_topk_tokens_and_values(\n self,\n k: int,\n sort_by: NDArray[np.float32],\n values: NDArray[np.float32],\n ) -> tuple[NDArray[np.str_], NDArray[np.float32]]:\n \"\"\"Get the top-k tokens according to sort_by for each layer and position.\n\n Args:\n k: The number of top tokens to get.\n sort_by: (..., n_layers, seq_len) the values to sort by to get the top-k\n values: (..., n_layers, seq_len) the values to get the top-k tokens for.\n\n Returns:\n * (..., n_layers, seq_len, k) the top-k tokens for each layer and position.\n * (..., n_layers, seq_len, k) the top-k values for each layer and position.\n \"\"\"\n assert self.tokenizer is not None\n\n # Get the top-k tokens & probabilities for each\n topk_inds = np.argpartition(sort_by, -k, axis=-1)[..., -k:]\n topk_sort_by = np.take_along_axis(sort_by, topk_inds, axis=-1)\n topk_values = np.take_along_axis(values, topk_inds, axis=-1)\n\n # Ensure that the top-k tokens are sorted by probability\n sorted_top_k_inds = np.argsort(-topk_sort_by, axis=-1)\n topk_inds = np.take_along_axis(topk_inds, sorted_top_k_inds, axis=-1)\n topk_values = np.take_along_axis(topk_values, sorted_top_k_inds, axis=-1)\n\n topk_tokens = _ids_to_tokens(topk_inds, self.tokenizer)\n\n return topk_tokens, topk_values\n\n def _hover_over_entries(\n self,\n topk_tokens: NDArray[np.str_],\n topk_values: NDArray[np.str_],\n max_entries_to_show: int = 3,\n ) -> NDArray[np.str_]:\n \"\"\"Get the hover over entries for the stream.\n\n Args:\n topk_tokens: (..., n_layers, seq_len, k) the top-k tokens for each layer and\n position.\n topk_values: (..., n_layers, seq_len, k) the top-k values associated with\n each token.\n max_entries_to_show: The maximum number of entries in the batch to show in\n the hover over menu.\n\n Returns:\n (n_layers, seq_len, batch, 2*k) the table of entries to show when hovering\n over the stream. Here `batch` is the minimum of the batch size and the\n `max_entries_to_show`.\n \"\"\"\n k = topk_tokens.shape[-1]\n topk_tokens = topk_tokens.reshape(-1, self.num_layers + 1, self.num_tokens, k)\n topk_values = topk_values.reshape(-1, self.num_layers + 1, self.num_tokens, k)\n topk_tokens = np.moveaxis(topk_tokens, 0, -1)\n topk_values = np.moveaxis(topk_values, 0, -1)\n hover_over_entries = np.empty(\n topk_tokens.shape[:-1] + (2 * topk_tokens.shape[-1],),\n dtype=topk_tokens.dtype,\n )\n hover_over_entries[..., 0::2] = topk_tokens\n hover_over_entries[..., 1::2] = topk_values\n return hover_over_entries[..., : 2 * max_entries_to_show]\n\n def _largest_prob_labels(\n self,\n formatter: Optional[TokenFormatter] = None,\n min_prob: float = 0,\n topk: int = 10,\n max_entries_to_show: int = 3,\n ) -> Optional[TrajectoryLabels]:\n \"\"\"Labels for the prediction trajectory based on the most probable tokens.\n\n Args:\n formatter : The formatter to use for formatting the tokens.\n min_prob : The minimum probability for a token to used as a label.\n topk : The number of top tokens to include in the hover over menu.\n max_entries_to_show : The number of items in the batch to show in the\n hover over menu.\n show_values : Whether to show the probability values in the hover over\n\n Returns:\n A set of stream labels that can be applied to a trajectory statistic or\n None if the tokenizer is not set.\n \"\"\"\n if self.tokenizer is None:\n return None\n\n if formatter is None:\n formatter = TokenFormatter()\n\n topk_tokens, topk_probs = self._get_topk_tokens_and_values(\n k=topk, sort_by=self.log_probs, values=self.probs\n )\n\n # Create the labels for the stream\n top_tokens = topk_tokens[..., 0]\n top_probs = topk_probs[..., 0]\n label_strings = _consolidate_labels_from_batch(\n tokens=formatter.vectorized_format(top_tokens),\n n_batch_axes=self.n_batch_axis,\n )\n label_strings = np.where((top_probs > min_prob).all(), label_strings, \"\")\n\n topk_probs_formatted = np.char.add(np.char.mod(\"%.2f\", topk_probs * 100), \"%\")\n topk_tokens_formatted = formatter.vectorized_format(topk_tokens)\n\n topk_probs_formatted = np.char.add(np.char.mod(\"%.2f\", topk_probs * 100), \"%\")\n topk_tokens_formatted = formatter.vectorized_format(topk_tokens)\n return TrajectoryLabels(\n label_strings=label_strings,\n hover_over_entries=self._hover_over_entries(\n topk_tokens=topk_tokens_formatted,\n topk_values=topk_probs_formatted,\n max_entries_to_show=max_entries_to_show,\n ),\n )\n\n def _largest_delta_in_prob_labels(\n self,\n other: \"PredictionTrajectory\",\n formatter: Optional[TokenFormatter] = None,\n min_prob_delta: float = 0,\n max_entries_to_show: int = 3,\n topk: int = 10,\n ) -> Optional[TrajectoryLabels]:\n \"\"\"Labels for a trajectory statistic based on the largest change in probability.\n\n Args:\n other : The other prediction trajectory to compare to.\n formatter : A TokenFormatter to use for formatting the labels.\n min_prob_delta : The minimum change in probability to include a label.\n topk : The number of top tokens to include in the hover over menu.\n max_entries_to_show: The maximum number of entries in the batch to show in\n the hover over menu.\n\n Returns:\n A set of stream labels that can be added to a trajectory statistic.\n \"\"\"\n if self.tokenizer is None:\n return None\n\n if formatter is None:\n formatter = TokenFormatter()\n\n deltas = other.probs - self.probs\n\n topk_tokens, topk_deltas = self._get_topk_tokens_and_values(\n k=topk, sort_by=np.abs(deltas), values=deltas\n )\n\n top_deltas = topk_deltas[..., 0]\n\n topk_tokens_formatted = formatter.vectorized_format(topk_tokens)\n top_tokens_formatted = topk_tokens_formatted[..., 0]\n topk_deltas_formatted = np.char.add(\n np.char.add(\"Δ\", np.char.mod(\"%.2f\", topk_deltas * 100)), \"%\"\n )\n\n label_strings = np.where(\n np.abs(top_deltas) > min_prob_delta,\n top_tokens_formatted,\n \"\",\n )\n\n label_strings = _consolidate_labels_from_batch(\n tokens=top_tokens_formatted,\n n_batch_axes=self.n_batch_axis,\n )\n return TrajectoryLabels(\n label_strings=label_strings,\n hover_over_entries=self._hover_over_entries(\n topk_tokens=topk_tokens_formatted,\n topk_values=topk_deltas_formatted,\n max_entries_to_show=max_entries_to_show,\n ),\n )\n\n def slice_sequence(self, slice: slice) -> \"PredictionTrajectory\":\n \"\"\"Create a slice of the prediction trajectory along the sequence dimension.\"\"\"\n return PredictionTrajectory(\n log_probs=self.log_probs[..., slice, :],\n input_ids=self.input_ids[..., slice],\n targets=self.targets[..., slice] if self.targets is not None else None,\n anti_targets=self.anti_targets[..., slice]\n if self.anti_targets is not None\n else None,\n tokenizer=self.tokenizer,\n )\n\n def cross_entropy(self, **kwargs) -> TrajectoryStatistic:\n \"\"\"The cross entropy of the predictions to the targets.\n\n Args:\n **kwargs: are passed to largest_prob_labels.\n\n Returns:\n A TrajectoryStatistic with the cross entropy of the predictions to the\n targets.\n \"\"\"\n if self.targets is None:\n raise ValueError(\"Cannot compute cross entropy without targets.\")\n\n stats = -_select_values_along_seq_axis(self.log_probs, self.targets)\n\n if self.n_batch_axis:\n stats = stats.mean(axis=self.batch_axes)\n\n return TrajectoryStatistic(\n name=\"Cross Entropy\",\n units=\"nats\",\n trajectory_labels=self._largest_prob_labels(**kwargs),\n sequence_labels=self._get_sequence_labels(),\n stats=stats,\n )\n\n def rank(self, show_ranks=False, **kwargs) -> TrajectoryStatistic:\n \"\"\"The rank of the targets among the predictions.\n\n That is, if the target is the most likely prediction, its rank is 1;\n the second most likely has rank 2, etc.\n\n Args:\n show_ranks: Whether to show the the rank of the target or the top token.\n **kwargs: are passed to largest_prob_labels.\n\n Returns:\n A TrajectoryStatistic with the rank of the targets among the predictions.\n \"\"\"\n if self.targets is None:\n raise ValueError(\"Cannot compute rank without targets.\")\n\n # Yes I know this is not the most efficient way to do this\n idx_of_kth_likeliest_token = np.argsort(-self.log_probs, axis=-1)\n ranks = np.argsort(idx_of_kth_likeliest_token, axis=-1) + 1\n targets_rank = _select_values_along_seq_axis(ranks, self.targets)\n\n if self.n_batch_axis:\n targets_rank = targets_rank.mean(axis=self.batch_axes)\n\n trajectory_labels = self._largest_prob_labels(**kwargs)\n\n if show_ranks and trajectory_labels is not None:\n trajectory_labels.label_strings = np.char.mod(\"%d\", targets_rank)\n\n return TrajectoryStatistic(\n name=\"Rank\",\n units=\"\",\n trajectory_labels=trajectory_labels,\n sequence_labels=self._get_sequence_labels(),\n stats=targets_rank,\n min=1,\n max=None if self.tokenizer is None else self.tokenizer.vocab_size,\n )\n\n def entropy(self, **kwargs) -> TrajectoryStatistic:\n \"\"\"The entropy of the predictions.\n\n Args:\n **kwargs: are passed to largest_prob_labels.\n\n Returns:\n A TrajectoryStatistic with the entropy of the predictions.\n \"\"\"\n stats = -np.sum(self.probs * self.log_probs, axis=-1)\n\n if self.n_batch_axis:\n stats = stats.mean(axis=self.batch_axes)\n\n return TrajectoryStatistic(\n name=\"Entropy\",\n units=\"nats\",\n trajectory_labels=self._largest_prob_labels(**kwargs),\n sequence_labels=self._get_sequence_labels(),\n stats=stats,\n )\n\n def forward_kl(self, **kwargs) -> TrajectoryStatistic:\n \"\"\"KL divergence of the lens predictions to the model predictions.\n\n Args:\n **kwargs: are passed to largest_prob_labels.\n\n Returns:\n A TrajectoryStatistic with the KL divergence of the lens predictions to the\n final output of the model.\n \"\"\"\n model_log_probs = self.model_log_probs[..., np.newaxis, :, :]\n stats = np.sum(\n np.exp(model_log_probs) * (model_log_probs - self.log_probs), axis=-1\n )\n\n if self.n_batch_axis:\n stats = stats.mean(axis=self.batch_axes)\n\n return TrajectoryStatistic(\n name=\"Forward KL\",\n units=\"nats\",\n trajectory_labels=self._largest_prob_labels(**kwargs),\n sequence_labels=self._get_sequence_labels(),\n stats=stats,\n )\n\n def log_prob_diff(self, delta: bool = False) -> TrajectoryStatistic:\n \"\"\"The difference in logits between two tokens.\n\n Returns:\n The difference between the log probabilities of the two tokens.\n \"\"\"\n # TODO implement this as a way to compare two distributions\n if self.targets is None or self.anti_targets is None:\n raise ValueError(\n \"Cannot compute log prob diff without targets\" \" and anti_targets.\"\n )\n\n targets_log_probs = _select_values_along_seq_axis(self.log_probs, self.targets)\n\n anti_targets_log_probs = _select_values_along_seq_axis(\n self.log_probs, self.anti_targets\n )\n\n stats = targets_log_probs - anti_targets_log_probs\n\n if delta:\n stats = stats[..., 1:, :] - stats[..., :-1, :]\n\n if self.n_batch_axis:\n stats = stats.mean(axis=self.batch_axes)\n\n return TrajectoryStatistic(\n name=\"Δ Log Prob Difference\" if delta else \"Log Prob Difference\",\n units=\"nats\",\n includes_output=not delta,\n sequence_labels=self._get_sequence_labels(),\n stats=stats,\n )\n\n def max_probability(self, **kwargs) -> TrajectoryStatistic:\n \"\"\"Max probability of the among the predictions.\n\n Args:\n **kwargs: are passed to largest_prob_labels.\n\n Returns:\n A TrajectoryStatistic with the max probability of the among the predictions.\n \"\"\"\n stats = np.exp(self.log_probs.max(-1))\n\n if self.n_batch_axis:\n stats = stats.mean(axis=self.batch_axes)\n\n return TrajectoryStatistic(\n name=\"Max Probability\",\n units=\"probs\",\n trajectory_labels=self._largest_prob_labels(**kwargs),\n sequence_labels=self._get_sequence_labels(),\n stats=stats,\n )\n\n def kl_divergence(\n self, other: \"PredictionTrajectory\", **kwargs\n ) -> TrajectoryStatistic:\n \"\"\"Compute the KL divergence between self and other prediction trajectory.\n\n Args:\n other : The other prediction trajectory to compare to.\n **kwargs: are passed to largest_delta_in_prob_labels.\n\n Returns:\n A TrajectoryStatistic with the KL divergence between self and other.\n \"\"\"\n kl_div = np.sum(self.probs * (self.log_probs - other.log_probs), axis=-1)\n\n if self.n_batch_axis:\n kl_div = kl_div.mean(axis=self.batch_axes)\n\n return TrajectoryStatistic(\n name=\"KL(Self | Other)\",\n units=\"nats\",\n stats=kl_div,\n trajectory_labels=self._largest_delta_in_prob_labels(other, **kwargs),\n sequence_labels=self._get_sequence_labels(),\n min=0,\n max=None,\n )\n\n def js_divergence(\n self, other: \"PredictionTrajectory\", **kwargs\n ) -> TrajectoryStatistic:\n \"\"\"Compute the JS divergence between self and other prediction trajectory.\n\n Args:\n other : The other prediction trajectory to compare to.\n **kwargs: are passed to largest_delta_in_prob_labels.\n\n Returns:\n A TrajectoryStatistic with the JS divergence between self and other.\n \"\"\"\n js_div = 0.5 * np.sum(\n self.probs * (self.log_probs - other.log_probs), axis=-1\n ) + 0.5 * np.sum(other.probs * (other.log_probs - self.log_probs), axis=-1)\n\n if self.n_batch_axis:\n js_div = js_div.mean(axis=self.batch_axes)\n\n return TrajectoryStatistic(\n name=\"JS(Self | Other)\",\n units=\"nats\",\n stats=js_div,\n trajectory_labels=self._largest_delta_in_prob_labels(other, **kwargs),\n sequence_labels=self._get_sequence_labels(),\n min=0,\n max=None,\n )\n\n def total_variation(\n self, other: \"PredictionTrajectory\", **kwargs\n ) -> TrajectoryStatistic:\n \"\"\"Total variation distance between self and other prediction trajectory.\n\n Args:\n other : The other prediction trajectory to compare to.\n **kwargs: are passed to largest_delta_in_prob_labels.\n\n Returns:\n A TrajectoryStatistic with the total variational distance between\n self and other.\n \"\"\"\n t_var = np.abs(self.probs - other.probs).max(axis=-1)\n\n if self.n_batch_axis:\n t_var = t_var.mean(axis=self.batch_axes)\n\n return TrajectoryStatistic(\n name=\"TV(Self | Other)\",\n units=\"probs\",\n stats=t_var,\n trajectory_labels=self._largest_delta_in_prob_labels(other, **kwargs),\n sequence_labels=self._get_sequence_labels(),\n min=0,\n max=1,\n )", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 25695}, "tests/test_lenses.py::145": {"resolved_imports": ["tuned_lens/load_artifacts.py", "tuned_lens/nn/lenses.py", "tuned_lens/nn/unembed.py"], "used_names": ["TunedLens"], "enclosing_function": "test_tuned_lens_generate_smoke", "extracted_code": "# Source: tuned_lens/nn/lenses.py\nclass TunedLens(Lens):\n \"\"\"A tuned lens for decoding hidden states into logits.\"\"\"\n\n config: TunedLensConfig\n unembed: Unembed\n layer_translators: th.nn.ModuleList\n\n def __init__(\n self,\n unembed: Unembed,\n config: TunedLensConfig,\n ):\n \"\"\"Create a TunedLens.\n\n Args:\n unembed: The unembed operation to use.\n config: The configuration for this lens.\n \"\"\"\n super().__init__(unembed)\n\n self.config = config\n unembed_hash = unembed.unembedding_hash()\n config.unembed_hash = unembed_hash\n\n # The unembedding might be int8 if we're using bitsandbytes\n w = unembed.unembedding.weight\n dtype = w.dtype if th.is_floating_point(w) else th.float16\n\n translator = th.nn.Linear(\n config.d_model, config.d_model, bias=config.bias, dtype=dtype\n )\n translator.weight.data.zero_()\n translator.bias.data.zero_()\n\n # Don't include the final layer since it does not need a translator\n self.layer_translators = th.nn.ModuleList(\n [deepcopy(translator) for _ in range(self.config.num_hidden_layers)]\n )\n\n def __getitem__(self, item: int) -> th.nn.Module:\n \"\"\"Get the probe module at the given index.\"\"\"\n return self.layer_translators[item]\n\n def __iter__(self) -> Generator[th.nn.Module, None, None]:\n \"\"\"Get iterator over the translators within the lens.\"\"\"\n yield from self.layer_translators\n\n @classmethod\n def from_model(\n cls,\n model: PreTrainedModel,\n model_revision: Optional[str] = None,\n bias: bool = True,\n ) -> \"TunedLens\":\n \"\"\"Create a lens from a pretrained model.\n\n Args:\n model: The model to create the lens from.\n model_revision: The git revision of the model to used.\n bias: Whether to use a bias in the linear translators.\n\n Returns:\n A TunedLens instance.\n \"\"\"\n unembed = Unembed(model)\n config = TunedLensConfig(\n base_model_name_or_path=model.config.name_or_path,\n base_model_revision=model_revision,\n d_model=model.config.hidden_size,\n num_hidden_layers=model.config.num_hidden_layers,\n bias=bias,\n )\n\n return cls(unembed, config)\n\n @classmethod\n def from_model_and_pretrained(\n cls,\n model: PreTrainedModel,\n lens_resource_id: Optional[str] = None,\n **kwargs,\n ) -> \"TunedLens\":\n \"\"\"Load a tuned lens from a folder or hugging face hub.\n\n Args:\n model: The model to create the lens from.\n lens_resource_id: The resource id of the lens to load. Defaults to the\n model's name_or_path.\n **kwargs: Additional arguments to pass to\n :func:`tuned_lens.load_artifacts.load_lens_artifacts` and\n `th.load <https://pytorch.org/docs/stable/generated/torch.load.html>`_.\n\n Returns:\n A TunedLens instance whose unembedding is derived from the given model\n and whose layer translators are loaded from the given resource id.\n \"\"\"\n if lens_resource_id is None:\n lens_resource_id = model.config.name_or_path\n\n return cls.from_unembed_and_pretrained(\n Unembed(model), lens_resource_id, **kwargs\n )\n\n @classmethod\n def from_unembed_and_pretrained(\n cls,\n unembed: Unembed,\n lens_resource_id: str,\n **kwargs,\n ) -> \"TunedLens\":\n \"\"\"Load a tuned lens from a folder or hugging face hub.\n\n Args:\n unembed: The unembed operation to use for the lens.\n lens_resource_id: The resource id of the lens to load.\n **kwargs: Additional arguments to pass to\n :func:`tuned_lens.load_artifacts.load_lens_artifacts` and\n `th.load <https://pytorch.org/docs/stable/generated/torch.load.html>`_.\n\n Returns:\n A TunedLens instance.\n \"\"\"\n # Validate kwargs\n load_artifact_varnames = load_artifacts.load_lens_artifacts.__code__.co_varnames\n\n config_path, ckpt_path = load_artifacts.load_lens_artifacts(\n resource_id=lens_resource_id,\n **{k: v for k, v in kwargs.items() if k in load_artifact_varnames},\n )\n\n with open(config_path, \"r\") as f:\n config = TunedLensConfig.from_dict(json.load(f))\n\n # validate the unembed is the same as the one used to train the lens\n if config.unembed_hash and unembed.unembedding_hash() != config.unembed_hash:\n logger.warning(\n \"The unembedding matrix hash does not match the lens' hash.\"\n \"This lens may have been trained with a different unembedding.\"\n )\n\n # Create the lens\n lens = cls(unembed, config)\n\n th_load_kwargs = {\n **{k: v for k, v in kwargs.items() if k not in load_artifact_varnames}\n }\n # Load parameters\n state = th.load(ckpt_path, **th_load_kwargs)\n\n lens.layer_translators.load_state_dict(state)\n\n return lens\n\n def save(\n self,\n path: Union[Path, str],\n ckpt: str = \"params.pt\",\n config: str = \"config.json\",\n ) -> None:\n \"\"\"Save the lens to a directory.\n\n Args:\n path : The path to the directory to save the lens to.\n ckpt : The name of the checkpoint file to save the parameters to.\n config : The name of the config file to save the config to.\n \"\"\"\n path = Path(path)\n path.mkdir(exist_ok=True, parents=True)\n state_dict = self.layer_translators.state_dict()\n\n th.save(state_dict, path / ckpt)\n with open(path / config, \"w\") as f:\n json.dump(self.config.to_dict(), f)\n\n def transform_hidden(self, h: th.Tensor, idx: int) -> th.Tensor:\n \"\"\"Transform hidden state from layer `idx`.\"\"\"\n # Note that we add the translator output residually, in contrast to the formula\n # in the paper. By parametrizing it this way we ensure that weight decay\n # regularizes the transform toward the identity, not the zero transformation.\n return h + self[idx](h)\n\n def forward(self, h: th.Tensor, idx: int) -> th.Tensor:\n \"\"\"Transform and then decode the hidden states into logits.\"\"\"\n h = self.transform_hidden(h, idx)\n return self.unembed.forward(h)\n\n def __len__(self) -> int:\n \"\"\"Return the number of layer translators in the lens.\"\"\"\n return len(self.layer_translators)\n\n @th.inference_mode()\n def generate(\n self,\n model: PreTrainedModel,\n layer: int,\n input_ids: th.Tensor,\n do_sample: bool = True,\n temp: float = 1.0,\n max_new_tokens: int = 100,\n ) -> th.Tensor:\n \"\"\"Generate from the tuned lens at the given layer.\n\n Args:\n model: The base model the generate from. Usually the model this lens trained\n on.\n layer: The layer to generate from.\n input_ids: (batch x prompt_len) The input ids to generate from.\n do_sample: Whether to use sampling or greedy decoding.\n temp: The temperature to use for sampling.\n max_new_tokens: The maximum number of tokens to generate.\n\n Returns:\n The prompt concatenated with the newly generated tokens.\n \"\"\"\n eos_token = model.generation_config.eos_token_id\n\n tokens = input_ids\n if tokens.ndim == 1:\n tokens = tokens.unsqueeze(0)\n batch, prompt_len = tokens.shape\n del prompt_len\n past_key_values = None\n done = th.zeros(batch, dtype=th.bool)\n\n for _ in range(max_new_tokens):\n output = model(\n input_ids=tokens,\n output_hidden_states=True,\n use_cache=True,\n past_key_values=past_key_values,\n )\n past_key_values = output.past_key_values\n hidden = output.hidden_states[layer]\n new_hidden = hidden[:, -1, :]\n new_logits = self.forward(new_hidden, layer)\n if do_sample:\n new_logits = new_logits / temp\n probs = new_logits.softmax(dim=-1)\n new_tokens = th.multinomial(probs, num_samples=1)\n else:\n new_tokens = new_logits.argmax(dim=-1, keepdim=True)\n\n # Once a sequence has generated an EOS token, it should not generate any\n # other tokens.\n done = done | (new_tokens == eos_token)\n new_tokens = new_tokens.masked_fill(done, eos_token)\n tokens = th.cat([tokens, new_tokens], dim=-1)\n # Halt generation if all sequences have generated an EOS token.\n if done.all():\n break\n\n return tokens", "n_imports_parsed": 8, "n_files_resolved": 3, "n_chars_extracted": 8991}, "tests/test_utils.py::11": {"resolved_imports": ["tuned_lens/utils.py"], "used_names": ["tensor_hash"], "enclosing_function": "test_tensor_hash", "extracted_code": "# Source: tuned_lens/utils.py\ndef tensor_hash(tensor: NDArray) -> str:\n \"\"\"Fast hash of a matrix that is robust to dtype and small perturbations.\n\n Note this relies on the ordering of the elements in the matrix, so it is\n if the matrix is in any way sorted this will not work well. In addition,\n this hash is intended for large tensors 64 + elements.\n \"\"\"\n return hashlib.sha256(str.encode(np.array_str(tensor, precision=1))).hexdigest()", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 455}, "tests/test_utils.py::10": {"resolved_imports": ["tuned_lens/utils.py"], "used_names": ["tensor_hash"], "enclosing_function": "test_tensor_hash", "extracted_code": "# Source: tuned_lens/utils.py\ndef tensor_hash(tensor: NDArray) -> str:\n \"\"\"Fast hash of a matrix that is robust to dtype and small perturbations.\n\n Note this relies on the ordering of the elements in the matrix, so it is\n if the matrix is in any way sorted this will not work well. In addition,\n this hash is intended for large tensors 64 + elements.\n \"\"\"\n return hashlib.sha256(str.encode(np.array_str(tensor, precision=1))).hexdigest()", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 455}, "tests/plotting/test_trajectory_plotting.py::45": {"resolved_imports": ["tuned_lens/plotting/trajectory_plotting.py"], "used_names": ["TrajectoryLabels", "TrajectoryStatistic", "pytest"], "enclosing_function": "test_trajectory_statistic_post_init", "extracted_code": "# Source: tuned_lens/plotting/trajectory_plotting.py\nclass TrajectoryLabels:\n \"\"\"Contains sets of labels for each layer and position in the residual stream.\"\"\"\n\n label_strings: NDArray[np.str_]\n \"\"\"(n_layers x sequence_length) label for each layer and position in the stream.\"\"\"\n hover_over_entries: Optional[NDArray[np.str_]] = None\n \"\"\"(n_layers x sequence_length x rows x cols) table of strings to display when\n hovering over a cell. For example, the top k prediction from the lens.\"\"\"\n\n def stride(self, stride: int) -> \"TrajectoryLabels\":\n \"\"\"Return a new TrajectoryLabels with the given stride.\n\n Args:\n stride : The number of layers between each layer we keep.\n\n Returns:\n A new TrajectoryLabels with the given stride.\n \"\"\"\n assert stride > 0, f\"stride must be positive, got {stride}\"\n return replace(\n self,\n label_strings=_stride_keep_last(self.label_strings, stride),\n hover_over_entries=None\n if self.hover_over_entries is None\n else _stride_keep_last(self.hover_over_entries, stride),\n )\n\n def template_and_customdata(\n self, col_width_limit: int = 10\n ) -> Tuple[str, NDArray[np.str_]]:\n \"\"\"Construct a template for use with Plotly's hovertemplate.\"\"\"\n assert self.hover_over_entries is not None\n n_rows, n_cols = self.hover_over_entries.shape[-2:]\n\n vec_str_len = np.vectorize(len)\n lengths = vec_str_len(self.hover_over_entries)\n max_col_lens = np.max(lengths, axis=(0, 1, 2), keepdims=True)\n max_col_lens = np.minimum(max_col_lens + 1, col_width_limit)\n\n vec_truncate = np.vectorize(trunc_string_left)\n truncated_entries = vec_truncate(self.hover_over_entries, max_col_lens)\n\n html_table = \"\"\n for row in range(n_rows):\n for col in range(n_cols):\n html_table += f\"%{{customdata[{row*n_cols + col}]}}\"\n html_table += \"<br>\"\n html_table += \"<extra></extra>\"\n customdata = truncated_entries.reshape(\n self.hover_over_entries.shape[:2] + (-1,)\n )\n return html_table, customdata\n\nclass TrajectoryStatistic:\n \"\"\"This class represents a trajectory statistic that can be visualized.\n\n For example, the entropy of the lens predictions at each layer.\n \"\"\"\n\n name: str\n \"\"\"The name of the statistic. For example, \"entropy\".\"\"\"\n stats: NDArray[np.float32]\n \"\"\"(n_layers x sequence_length) value of the statistic across layer and position.\"\"\"\n sequence_labels: Optional[NDArray[np.str_]] = None\n \"\"\"(sequence_length) labels for the sequence dimension e.g. input tokens.\"\"\"\n trajectory_labels: Optional[TrajectoryLabels] = None\n \"\"\"Labels for each layer and position in the stream. For example, the top 1\n prediction from the lens at each layer.\"\"\"\n units: Optional[str] = None\n \"\"\"The units of the statistic.\"\"\"\n max: Optional[float] = None\n \"\"\"The maximum value of the statistic.\"\"\"\n min: Optional[float] = None\n \"\"\"The minimum value of the statistic.\"\"\"\n includes_output: bool = True\n \"\"\"Whether the statistic includes the final output layer.\"\"\"\n\n _layer_labels: Optional[NDArray[np.str_]] = None\n\n def __post_init__(self) -> None:\n \"\"\"Validate class invariants.\"\"\"\n assert len(self.stats.shape) == 2, f\"{self.stats.shape} != (n_layers, seq_len)\"\n\n assert self.trajectory_labels is None or (\n self.trajectory_labels.label_strings.shape == self.stats.shape\n ), f\"{self.trajectory_labels.label_strings.shape} != {self.stats.shape}\"\n\n assert self.sequence_labels is None or (\n self.sequence_labels.shape[-1] == self.stats.shape[-1]\n ), f\"{self.sequence_labels.shape[-1]} != {self.stats.shape[-1]}\"\n\n if self._layer_labels is None:\n if self.includes_output:\n self._layer_labels = np.array(\n [*map(str, range(self.stats.shape[0] - 1)), \"output\"]\n )\n else:\n self._layer_labels = np.array([*map(str, range(self.stats.shape[0]))])\n\n def clip(self, min: float, max: float) -> \"TrajectoryStatistic\":\n \"\"\"Return a new TrajectoryStatistic with the given min and max.\n\n Args:\n min : The minimum value to clip to.\n max : The maximum value to clip to.\n\n Returns:\n A new TrajectoryStatistic with the given min and max.\n \"\"\"\n assert min < max, f\"min must be less than max, got {min} >= {max}\"\n return replace(\n self,\n stats=np.clip(self.stats, min, max),\n max=max,\n min=min,\n )\n\n def stride(self, stride: int) -> \"TrajectoryStatistic\":\n \"\"\"Return a new TrajectoryStatistic with the given stride.\n\n Args:\n stride : The number of layers between each layer we keep.\n\n Returns:\n A new TrajectoryStatistic with the given stride.\n \"\"\"\n assert stride > 0, f\"stride must be positive, got {stride}\"\n assert self._layer_labels is not None\n return replace(\n self,\n stats=_stride_keep_last(self.stats, stride),\n trajectory_labels=None\n if self.trajectory_labels is None\n else self.trajectory_labels.stride(stride),\n _layer_labels=None\n if self._layer_labels is None\n else _stride_keep_last(self._layer_labels, stride),\n )\n\n def heatmap(\n self,\n colorscale: str = \"rdbu_r\",\n log_scale: bool = False,\n **kwargs,\n ) -> go.Heatmap:\n \"\"\"Returns a Plotly Heatmap object for this statistic.\n\n Args:\n colorscale : The colorscale to use for the heatmap.\n log_scale : Whether to use a log scale for the colorbar.\n **kwargs : Additional keyword arguments to pass to the Heatmap constructor.\n\n Returns:\n A plotly Heatmap where the x-axis is the sequence dimension, the y-axis is\n the layer dimension, and the color of each cell is the value of\n the statistic.\n \"\"\"\n max = self.max if self.max is not None else np.max(self.stats)\n min = self.min if self.min is not None else np.min(self.stats)\n heatmap_kwargs: Dict[str, Any] = dict(\n y=self._layer_labels,\n z=self.stats if not log_scale else np.log10(self.stats),\n colorbar=dict(\n title=f\"{self.name} ({self.units})\",\n titleside=\"right\",\n ),\n colorscale=colorscale,\n zmax=max if not log_scale else np.log10(max),\n zmin=min if not log_scale else np.log10(min),\n )\n\n if log_scale:\n smallest_tick = np.ceil(np.log10(min))\n biggest_tick = np.floor(np.log10(max))\n tickvals = np.arange(smallest_tick, biggest_tick + 1)\n heatmap_kwargs[\"colorbar\"] = dict(\n tickmode=\"array\",\n tickvals=tickvals,\n ticktext=[\"10^{}\".format(i) for i in tickvals],\n )\n\n if self.sequence_labels is not None:\n # Hack to ensure that Plotly doesn't de-duplicate the x-axis labels\n x_labels = [x + \"\\u200c\" * i for i, x in enumerate(self.sequence_labels)]\n heatmap_kwargs.update(x=x_labels)\n\n if self.trajectory_labels is not None:\n heatmap_kwargs.update(\n text=self.trajectory_labels.label_strings,\n texttemplate=\"<b>%{text}</b>\",\n )\n\n if self.trajectory_labels.hover_over_entries is not None:\n (\n hovertemplate,\n custom_data,\n ) = self.trajectory_labels.template_and_customdata()\n heatmap_kwargs.update(\n hoverlabel=dict(bgcolor=\"rgb(42, 42, 50)\", font_family=\"Monospace\"),\n customdata=custom_data,\n hovertemplate=hovertemplate,\n )\n\n heatmap_kwargs.update(kwargs)\n return go.Heatmap(**heatmap_kwargs)\n\n def figure(\n self,\n title: str = \"\",\n colorscale: str = \"rdbu_r\",\n token_width: int = 80,\n ) -> go.Figure:\n \"\"\"Produce a heatmap plot of the statistic.\n\n Args:\n title : The title of the plot.\n colorscale : The colorscale to use for the heatmap.\n token_width : The width of each token in the plot.\n\n Returns:\n The plotly heatmap figure.\n \"\"\"\n heatmap = self.heatmap(colorscale)\n figure_width = 200 + token_width * self.stats.shape[1]\n\n fig = go.Figure(heatmap).update_layout(\n title_text=title,\n title_x=0.5,\n width=figure_width,\n xaxis_title=\"Input\",\n yaxis_title=\"Layer\",\n )\n\n return fig", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 8958}, "tests/scripts/test_integration.py::44": {"resolved_imports": ["tuned_lens/__main__.py"], "used_names": ["Path", "main", "pytest"], "enclosing_function": "test_eval_subcommand_fails_when_not_enough_data_given", "extracted_code": "# Source: tuned_lens/__main__.py\ndef main(args: Optional[list[str]] = None):\n \"\"\"Entry point for the CLI.\"\"\"\n parser = ArgumentParser(conflict_resolution=ConflictResolution.EXPLICIT)\n parser.add_arguments(Main, dest=\"prog\")\n args = parser.parse_args(args=args)\n prog: Main = args.prog\n prog.execute()", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 318}, "tests/plotting/test_prediction_trajectory.py::116": {"resolved_imports": ["tuned_lens/nn/lenses.py", "tuned_lens/plotting/prediction_trajectory.py"], "used_names": ["PredictionTrajectory"], "enclosing_function": "test_largest_prob_labels_smoke", "extracted_code": "# Source: tuned_lens/plotting/prediction_trajectory.py\nclass PredictionTrajectory:\n \"\"\"Contains the trajectory predictions for a sequence of tokens.\n\n A prediction trajectory is the set of next token predictions produced by the\n conjunction of a lens and a model when evaluated on a specific sequence of tokens.\n This class include multiple methods for visualizing different\n aspects of the trajectory.\n \"\"\"\n\n log_probs: NDArray[np.float32]\n \"\"\"(..., n_layers, seq_len, vocab_size) The log probabilities of the predictions\n for each hidden layer + the models logits\"\"\"\n\n input_ids: NDArray[np.int64]\n \"\"\"(..., seq_len)\"\"\"\n\n targets: Optional[NDArray[np.int64]] = None\n \"\"\"(..., seq_len)\"\"\"\n\n anti_targets: Optional[NDArray[np.int64]] = None\n \"\"\"(..., seq_len)\"\"\"\n\n tokenizer: Optional[Tokenizer] = None\n\n def __post_init__(self) -> None:\n \"\"\"Validate class invariants.\"\"\"\n assert (\n self.log_probs.shape[:-3] == self.input_ids.shape[:-1]\n ), \"Batch shapes do not match log_probs.shape: {}, input_ids.shape: {}\".format(\n self.log_probs.shape, self.input_ids.shape\n )\n\n assert (\n self.log_probs.shape[-2] == self.input_ids.shape[-1]\n ), \"seq_len doesn't match log_probs.shape: {}, input_ids.shape: {}\".format(\n self.log_probs.shape, self.input_ids.shape\n )\n\n assert (\n self.targets is None or self.targets.shape == self.input_ids.shape\n ), \"Shapes don't match targets.shape: {}, input_ids.shape: {}\".format(\n self.targets.shape, self.input_ids.shape\n )\n\n assert (\n self.anti_targets is None or self.anti_targets.shape == self.input_ids.shape\n ), \"Shapes don't match anti_targets.shape: {}, input_ids.shape: {}\".format(\n self.anti_targets.shape, self.input_ids.shape\n )\n\n @property\n def n_batch_axis(self) -> int:\n \"\"\"Returns the number of batch dimensions.\"\"\"\n return len(self.batch_axes)\n\n @property\n def batch_axes(self) -> Sequence[int]:\n \"\"\"Returns the batch axes for the trajectory.\"\"\"\n return tuple(range(len(self.log_probs.shape) - 3))\n\n @property\n def batch_shape(self) -> Sequence[int]:\n \"\"\"Returns the batch shape of the trajectory.\"\"\"\n return self.log_probs.shape[:-3]\n\n @property\n def num_layers(self) -> int:\n \"\"\"Returns the number of layers in the stream not including the model output.\"\"\"\n return self.log_probs.shape[-3] - 1\n\n @property\n def num_tokens(self) -> int:\n \"\"\"Returns the number of tokens in this slice of the sequence.\"\"\"\n return self.log_probs.shape[-2]\n\n @property\n def vocab_size(self) -> int:\n \"\"\"Returns the size of the vocabulary.\"\"\"\n return self.log_probs.shape[-1]\n\n @property\n def model_log_probs(self) -> NDArray[np.float32]:\n \"\"\"Returns the log probs of the model (..., seq_len, vocab_size).\"\"\"\n return self.log_probs[..., -1, :, :]\n\n @property\n def probs(self) -> NDArray[np.float32]:\n \"\"\"Returns the probabilities of the predictions.\"\"\"\n return np.exp(self.log_probs)\n\n @classmethod\n def from_lens_and_cache(\n cls,\n lens: Lens,\n input_ids: th.Tensor,\n cache: \"tl.ActivationCache\",\n model_logits: th.Tensor,\n targets: Optional[th.Tensor] = None,\n anti_targets: Optional[th.Tensor] = None,\n residual_component: ResidualComponent = \"resid_pre\",\n mask_input: bool = False,\n ) -> \"PredictionTrajectory\":\n \"\"\"Construct a prediction trajectory from a set of residual stream vectors.\n\n Args:\n lens: A lens to use to produce the predictions.\n cache: the activation cache produced by running the model.\n input_ids: (..., seq_len) Ids that where input into the model.\n model_logits: (..., seq_len x d_vocab) the models final output logits.\n targets: (..., seq_len) the targets the model is should predict. Used\n for :meth:`cross_entropy` and :meth:`log_prob_diff` visualization.\n anti_targets: (..., seq_len) the incorrect label the model should not\n predict. Used for :meth:`log_prob_diff` visualization.\n residual_component: Name of the stream vector being visualized.\n mask_input: Whether to mask the input ids when computing the log probs.\n\n Returns:\n PredictionTrajectory constructed from the residual stream vectors.\n \"\"\"\n tokenizer = cache.model.tokenizer\n traj_log_probs = []\n for layer in range(cache.model.cfg.n_layers):\n hidden = cache[residual_component, layer]\n if input_ids.shape[-1] != hidden.shape[-2]:\n raise ValueError(\n f\"Length of input ids {input_ids.shape[-1]} does \"\n f\"not match cache sequence length {hidden.shape[-2]}.\"\n )\n\n logits = lens.forward(hidden, layer)\n\n if mask_input:\n logits[..., input_ids] = -th.finfo(hidden.dtype).max\n\n traj_log_probs.append(\n logits.log_softmax(dim=-1).detach().cpu().float().numpy()\n )\n\n model_log_probs = model_logits.log_softmax(-1).detach().cpu().float().numpy()\n\n traj_log_probs.append(model_log_probs)\n\n return cls(\n tokenizer=tokenizer,\n log_probs=np.stack(traj_log_probs, axis=-3),\n input_ids=input_ids.cpu().numpy(),\n targets=None if targets is None else targets.cpu().numpy(),\n anti_targets=None if anti_targets is None else anti_targets.cpu().numpy(),\n )\n\n @classmethod\n def from_lens_and_model(\n cls,\n lens: Lens,\n model: PreTrainedModel,\n input_ids: Sequence[int],\n tokenizer: Optional[Tokenizer] = None,\n targets: Optional[Sequence[int]] = None,\n anti_targets: Optional[Sequence[int]] = None,\n mask_input: bool = False,\n ) -> \"PredictionTrajectory\":\n \"\"\"Construct a prediction trajectory from a set of residual stream vectors.\n\n Args:\n lens: A lens to use to produce the predictions. Note this should be\n compatible with the model.\n model: A Hugging Face causal language model to use to produce\n the predictions.\n tokenizer: The tokenizer to use for decoding the input ids.\n input_ids: (seq_len) Ids that where input into the model.\n targets: (seq_len) the targets the model is should predict. Used\n for :meth:`cross_entropy` and :meth:`log_prob_diff` visualization.\n anti_targets: (seq_len) the incorrect label the model should not\n predict. Used for :meth:`log_prob_diff` visualization.\n residual_component: Name of the stream vector being visualized.\n mask_input: Whether to mask the input ids when computing the log probs.\n\n Returns:\n PredictionTrajectory constructed from the residual stream vectors.\n \"\"\"\n with th.no_grad():\n input_ids_th = th.tensor(input_ids, dtype=th.int64, device=model.device)\n outputs = model(input_ids_th.unsqueeze(0), output_hidden_states=True)\n\n # Slice arrays the specified range\n model_log_probs = (\n outputs.logits[..., :]\n .log_softmax(-1)\n .squeeze()\n .detach()\n .cpu()\n .float()\n .numpy()\n )\n stream = list(outputs.hidden_states)\n\n input_ids_np = np.array(input_ids)\n targets_np = np.array(targets) if targets is not None else None\n anti_targets_np = np.array(anti_targets) if anti_targets is not None else None\n\n # Create the stream of log probabilities from the lens\n traj_log_probs = []\n for i, h in enumerate(stream[:-1]):\n logits = lens.forward(h, i)\n\n if mask_input:\n logits[..., input_ids_np] = -th.finfo(h.dtype).max\n\n traj_log_probs.append(\n logits.log_softmax(dim=-1).squeeze().detach().cpu().float().numpy()\n )\n\n # Add model predictions\n traj_log_probs.append(model_log_probs)\n\n return cls(\n tokenizer=tokenizer,\n log_probs=np.array(traj_log_probs),\n targets=targets_np,\n input_ids=input_ids_np,\n anti_targets=anti_targets_np,\n )\n\n def _get_sequence_labels(\n self, token_formatter: Optional[TokenFormatter] = None\n ) -> Optional[NDArray[np.str_]]:\n \"\"\"Get the input labels from a batch of input ids.\"\"\"\n if self.tokenizer is None:\n return None\n\n if token_formatter is None:\n token_formatter = TokenFormatter()\n\n return _consolidate_labels_from_batch(\n tokens=token_formatter.vectorized_format(\n _ids_to_tokens(self.input_ids, self.tokenizer)\n ),\n n_batch_axes=self.n_batch_axis,\n )\n\n def _get_topk_tokens_and_values(\n self,\n k: int,\n sort_by: NDArray[np.float32],\n values: NDArray[np.float32],\n ) -> tuple[NDArray[np.str_], NDArray[np.float32]]:\n \"\"\"Get the top-k tokens according to sort_by for each layer and position.\n\n Args:\n k: The number of top tokens to get.\n sort_by: (..., n_layers, seq_len) the values to sort by to get the top-k\n values: (..., n_layers, seq_len) the values to get the top-k tokens for.\n\n Returns:\n * (..., n_layers, seq_len, k) the top-k tokens for each layer and position.\n * (..., n_layers, seq_len, k) the top-k values for each layer and position.\n \"\"\"\n assert self.tokenizer is not None\n\n # Get the top-k tokens & probabilities for each\n topk_inds = np.argpartition(sort_by, -k, axis=-1)[..., -k:]\n topk_sort_by = np.take_along_axis(sort_by, topk_inds, axis=-1)\n topk_values = np.take_along_axis(values, topk_inds, axis=-1)\n\n # Ensure that the top-k tokens are sorted by probability\n sorted_top_k_inds = np.argsort(-topk_sort_by, axis=-1)\n topk_inds = np.take_along_axis(topk_inds, sorted_top_k_inds, axis=-1)\n topk_values = np.take_along_axis(topk_values, sorted_top_k_inds, axis=-1)\n\n topk_tokens = _ids_to_tokens(topk_inds, self.tokenizer)\n\n return topk_tokens, topk_values\n\n def _hover_over_entries(\n self,\n topk_tokens: NDArray[np.str_],\n topk_values: NDArray[np.str_],\n max_entries_to_show: int = 3,\n ) -> NDArray[np.str_]:\n \"\"\"Get the hover over entries for the stream.\n\n Args:\n topk_tokens: (..., n_layers, seq_len, k) the top-k tokens for each layer and\n position.\n topk_values: (..., n_layers, seq_len, k) the top-k values associated with\n each token.\n max_entries_to_show: The maximum number of entries in the batch to show in\n the hover over menu.\n\n Returns:\n (n_layers, seq_len, batch, 2*k) the table of entries to show when hovering\n over the stream. Here `batch` is the minimum of the batch size and the\n `max_entries_to_show`.\n \"\"\"\n k = topk_tokens.shape[-1]\n topk_tokens = topk_tokens.reshape(-1, self.num_layers + 1, self.num_tokens, k)\n topk_values = topk_values.reshape(-1, self.num_layers + 1, self.num_tokens, k)\n topk_tokens = np.moveaxis(topk_tokens, 0, -1)\n topk_values = np.moveaxis(topk_values, 0, -1)\n hover_over_entries = np.empty(\n topk_tokens.shape[:-1] + (2 * topk_tokens.shape[-1],),\n dtype=topk_tokens.dtype,\n )\n hover_over_entries[..., 0::2] = topk_tokens\n hover_over_entries[..., 1::2] = topk_values\n return hover_over_entries[..., : 2 * max_entries_to_show]\n\n def _largest_prob_labels(\n self,\n formatter: Optional[TokenFormatter] = None,\n min_prob: float = 0,\n topk: int = 10,\n max_entries_to_show: int = 3,\n ) -> Optional[TrajectoryLabels]:\n \"\"\"Labels for the prediction trajectory based on the most probable tokens.\n\n Args:\n formatter : The formatter to use for formatting the tokens.\n min_prob : The minimum probability for a token to used as a label.\n topk : The number of top tokens to include in the hover over menu.\n max_entries_to_show : The number of items in the batch to show in the\n hover over menu.\n show_values : Whether to show the probability values in the hover over\n\n Returns:\n A set of stream labels that can be applied to a trajectory statistic or\n None if the tokenizer is not set.\n \"\"\"\n if self.tokenizer is None:\n return None\n\n if formatter is None:\n formatter = TokenFormatter()\n\n topk_tokens, topk_probs = self._get_topk_tokens_and_values(\n k=topk, sort_by=self.log_probs, values=self.probs\n )\n\n # Create the labels for the stream\n top_tokens = topk_tokens[..., 0]\n top_probs = topk_probs[..., 0]\n label_strings = _consolidate_labels_from_batch(\n tokens=formatter.vectorized_format(top_tokens),\n n_batch_axes=self.n_batch_axis,\n )\n label_strings = np.where((top_probs > min_prob).all(), label_strings, \"\")\n\n topk_probs_formatted = np.char.add(np.char.mod(\"%.2f\", topk_probs * 100), \"%\")\n topk_tokens_formatted = formatter.vectorized_format(topk_tokens)\n\n topk_probs_formatted = np.char.add(np.char.mod(\"%.2f\", topk_probs * 100), \"%\")\n topk_tokens_formatted = formatter.vectorized_format(topk_tokens)\n return TrajectoryLabels(\n label_strings=label_strings,\n hover_over_entries=self._hover_over_entries(\n topk_tokens=topk_tokens_formatted,\n topk_values=topk_probs_formatted,\n max_entries_to_show=max_entries_to_show,\n ),\n )\n\n def _largest_delta_in_prob_labels(\n self,\n other: \"PredictionTrajectory\",\n formatter: Optional[TokenFormatter] = None,\n min_prob_delta: float = 0,\n max_entries_to_show: int = 3,\n topk: int = 10,\n ) -> Optional[TrajectoryLabels]:\n \"\"\"Labels for a trajectory statistic based on the largest change in probability.\n\n Args:\n other : The other prediction trajectory to compare to.\n formatter : A TokenFormatter to use for formatting the labels.\n min_prob_delta : The minimum change in probability to include a label.\n topk : The number of top tokens to include in the hover over menu.\n max_entries_to_show: The maximum number of entries in the batch to show in\n the hover over menu.\n\n Returns:\n A set of stream labels that can be added to a trajectory statistic.\n \"\"\"\n if self.tokenizer is None:\n return None\n\n if formatter is None:\n formatter = TokenFormatter()\n\n deltas = other.probs - self.probs\n\n topk_tokens, topk_deltas = self._get_topk_tokens_and_values(\n k=topk, sort_by=np.abs(deltas), values=deltas\n )\n\n top_deltas = topk_deltas[..., 0]\n\n topk_tokens_formatted = formatter.vectorized_format(topk_tokens)\n top_tokens_formatted = topk_tokens_formatted[..., 0]\n topk_deltas_formatted = np.char.add(\n np.char.add(\"Δ\", np.char.mod(\"%.2f\", topk_deltas * 100)), \"%\"\n )\n\n label_strings = np.where(\n np.abs(top_deltas) > min_prob_delta,\n top_tokens_formatted,\n \"\",\n )\n\n label_strings = _consolidate_labels_from_batch(\n tokens=top_tokens_formatted,\n n_batch_axes=self.n_batch_axis,\n )\n return TrajectoryLabels(\n label_strings=label_strings,\n hover_over_entries=self._hover_over_entries(\n topk_tokens=topk_tokens_formatted,\n topk_values=topk_deltas_formatted,\n max_entries_to_show=max_entries_to_show,\n ),\n )\n\n def slice_sequence(self, slice: slice) -> \"PredictionTrajectory\":\n \"\"\"Create a slice of the prediction trajectory along the sequence dimension.\"\"\"\n return PredictionTrajectory(\n log_probs=self.log_probs[..., slice, :],\n input_ids=self.input_ids[..., slice],\n targets=self.targets[..., slice] if self.targets is not None else None,\n anti_targets=self.anti_targets[..., slice]\n if self.anti_targets is not None\n else None,\n tokenizer=self.tokenizer,\n )\n\n def cross_entropy(self, **kwargs) -> TrajectoryStatistic:\n \"\"\"The cross entropy of the predictions to the targets.\n\n Args:\n **kwargs: are passed to largest_prob_labels.\n\n Returns:\n A TrajectoryStatistic with the cross entropy of the predictions to the\n targets.\n \"\"\"\n if self.targets is None:\n raise ValueError(\"Cannot compute cross entropy without targets.\")\n\n stats = -_select_values_along_seq_axis(self.log_probs, self.targets)\n\n if self.n_batch_axis:\n stats = stats.mean(axis=self.batch_axes)\n\n return TrajectoryStatistic(\n name=\"Cross Entropy\",\n units=\"nats\",\n trajectory_labels=self._largest_prob_labels(**kwargs),\n sequence_labels=self._get_sequence_labels(),\n stats=stats,\n )\n\n def rank(self, show_ranks=False, **kwargs) -> TrajectoryStatistic:\n \"\"\"The rank of the targets among the predictions.\n\n That is, if the target is the most likely prediction, its rank is 1;\n the second most likely has rank 2, etc.\n\n Args:\n show_ranks: Whether to show the the rank of the target or the top token.\n **kwargs: are passed to largest_prob_labels.\n\n Returns:\n A TrajectoryStatistic with the rank of the targets among the predictions.\n \"\"\"\n if self.targets is None:\n raise ValueError(\"Cannot compute rank without targets.\")\n\n # Yes I know this is not the most efficient way to do this\n idx_of_kth_likeliest_token = np.argsort(-self.log_probs, axis=-1)\n ranks = np.argsort(idx_of_kth_likeliest_token, axis=-1) + 1\n targets_rank = _select_values_along_seq_axis(ranks, self.targets)\n\n if self.n_batch_axis:\n targets_rank = targets_rank.mean(axis=self.batch_axes)\n\n trajectory_labels = self._largest_prob_labels(**kwargs)\n\n if show_ranks and trajectory_labels is not None:\n trajectory_labels.label_strings = np.char.mod(\"%d\", targets_rank)\n\n return TrajectoryStatistic(\n name=\"Rank\",\n units=\"\",\n trajectory_labels=trajectory_labels,\n sequence_labels=self._get_sequence_labels(),\n stats=targets_rank,\n min=1,\n max=None if self.tokenizer is None else self.tokenizer.vocab_size,\n )\n\n def entropy(self, **kwargs) -> TrajectoryStatistic:\n \"\"\"The entropy of the predictions.\n\n Args:\n **kwargs: are passed to largest_prob_labels.\n\n Returns:\n A TrajectoryStatistic with the entropy of the predictions.\n \"\"\"\n stats = -np.sum(self.probs * self.log_probs, axis=-1)\n\n if self.n_batch_axis:\n stats = stats.mean(axis=self.batch_axes)\n\n return TrajectoryStatistic(\n name=\"Entropy\",\n units=\"nats\",\n trajectory_labels=self._largest_prob_labels(**kwargs),\n sequence_labels=self._get_sequence_labels(),\n stats=stats,\n )\n\n def forward_kl(self, **kwargs) -> TrajectoryStatistic:\n \"\"\"KL divergence of the lens predictions to the model predictions.\n\n Args:\n **kwargs: are passed to largest_prob_labels.\n\n Returns:\n A TrajectoryStatistic with the KL divergence of the lens predictions to the\n final output of the model.\n \"\"\"\n model_log_probs = self.model_log_probs[..., np.newaxis, :, :]\n stats = np.sum(\n np.exp(model_log_probs) * (model_log_probs - self.log_probs), axis=-1\n )\n\n if self.n_batch_axis:\n stats = stats.mean(axis=self.batch_axes)\n\n return TrajectoryStatistic(\n name=\"Forward KL\",\n units=\"nats\",\n trajectory_labels=self._largest_prob_labels(**kwargs),\n sequence_labels=self._get_sequence_labels(),\n stats=stats,\n )\n\n def log_prob_diff(self, delta: bool = False) -> TrajectoryStatistic:\n \"\"\"The difference in logits between two tokens.\n\n Returns:\n The difference between the log probabilities of the two tokens.\n \"\"\"\n # TODO implement this as a way to compare two distributions\n if self.targets is None or self.anti_targets is None:\n raise ValueError(\n \"Cannot compute log prob diff without targets\" \" and anti_targets.\"\n )\n\n targets_log_probs = _select_values_along_seq_axis(self.log_probs, self.targets)\n\n anti_targets_log_probs = _select_values_along_seq_axis(\n self.log_probs, self.anti_targets\n )\n\n stats = targets_log_probs - anti_targets_log_probs\n\n if delta:\n stats = stats[..., 1:, :] - stats[..., :-1, :]\n\n if self.n_batch_axis:\n stats = stats.mean(axis=self.batch_axes)\n\n return TrajectoryStatistic(\n name=\"Δ Log Prob Difference\" if delta else \"Log Prob Difference\",\n units=\"nats\",\n includes_output=not delta,\n sequence_labels=self._get_sequence_labels(),\n stats=stats,\n )\n\n def max_probability(self, **kwargs) -> TrajectoryStatistic:\n \"\"\"Max probability of the among the predictions.\n\n Args:\n **kwargs: are passed to largest_prob_labels.\n\n Returns:\n A TrajectoryStatistic with the max probability of the among the predictions.\n \"\"\"\n stats = np.exp(self.log_probs.max(-1))\n\n if self.n_batch_axis:\n stats = stats.mean(axis=self.batch_axes)\n\n return TrajectoryStatistic(\n name=\"Max Probability\",\n units=\"probs\",\n trajectory_labels=self._largest_prob_labels(**kwargs),\n sequence_labels=self._get_sequence_labels(),\n stats=stats,\n )\n\n def kl_divergence(\n self, other: \"PredictionTrajectory\", **kwargs\n ) -> TrajectoryStatistic:\n \"\"\"Compute the KL divergence between self and other prediction trajectory.\n\n Args:\n other : The other prediction trajectory to compare to.\n **kwargs: are passed to largest_delta_in_prob_labels.\n\n Returns:\n A TrajectoryStatistic with the KL divergence between self and other.\n \"\"\"\n kl_div = np.sum(self.probs * (self.log_probs - other.log_probs), axis=-1)\n\n if self.n_batch_axis:\n kl_div = kl_div.mean(axis=self.batch_axes)\n\n return TrajectoryStatistic(\n name=\"KL(Self | Other)\",\n units=\"nats\",\n stats=kl_div,\n trajectory_labels=self._largest_delta_in_prob_labels(other, **kwargs),\n sequence_labels=self._get_sequence_labels(),\n min=0,\n max=None,\n )\n\n def js_divergence(\n self, other: \"PredictionTrajectory\", **kwargs\n ) -> TrajectoryStatistic:\n \"\"\"Compute the JS divergence between self and other prediction trajectory.\n\n Args:\n other : The other prediction trajectory to compare to.\n **kwargs: are passed to largest_delta_in_prob_labels.\n\n Returns:\n A TrajectoryStatistic with the JS divergence between self and other.\n \"\"\"\n js_div = 0.5 * np.sum(\n self.probs * (self.log_probs - other.log_probs), axis=-1\n ) + 0.5 * np.sum(other.probs * (other.log_probs - self.log_probs), axis=-1)\n\n if self.n_batch_axis:\n js_div = js_div.mean(axis=self.batch_axes)\n\n return TrajectoryStatistic(\n name=\"JS(Self | Other)\",\n units=\"nats\",\n stats=js_div,\n trajectory_labels=self._largest_delta_in_prob_labels(other, **kwargs),\n sequence_labels=self._get_sequence_labels(),\n min=0,\n max=None,\n )\n\n def total_variation(\n self, other: \"PredictionTrajectory\", **kwargs\n ) -> TrajectoryStatistic:\n \"\"\"Total variation distance between self and other prediction trajectory.\n\n Args:\n other : The other prediction trajectory to compare to.\n **kwargs: are passed to largest_delta_in_prob_labels.\n\n Returns:\n A TrajectoryStatistic with the total variational distance between\n self and other.\n \"\"\"\n t_var = np.abs(self.probs - other.probs).max(axis=-1)\n\n if self.n_batch_axis:\n t_var = t_var.mean(axis=self.batch_axes)\n\n return TrajectoryStatistic(\n name=\"TV(Self | Other)\",\n units=\"probs\",\n stats=t_var,\n trajectory_labels=self._largest_delta_in_prob_labels(other, **kwargs),\n sequence_labels=self._get_sequence_labels(),\n min=0,\n max=1,\n )", "n_imports_parsed": 8, "n_files_resolved": 2, "n_chars_extracted": 25695}, "tests/test_unembed.py::31": {"resolved_imports": ["tuned_lens/model_surgery.py", "tuned_lens/nn/unembed.py"], "used_names": ["Unembed", "get_final_norm"], "enclosing_function": "test_correctness", "extracted_code": "# Source: tuned_lens/model_surgery.py\ndef get_final_norm(model: Model) -> Norm:\n \"\"\"Get the final norm from a model.\n\n This isn't standardized across models, so this will need to be updated as\n we add new models.\n \"\"\"\n if _transformer_lens_available and isinstance(model, tl.HookedTransformer):\n return model.ln_final\n\n if not hasattr(model, \"base_model\"):\n raise ValueError(\"Model does not have a `base_model` attribute.\")\n\n base_model = model.base_model\n if isinstance(base_model, models.opt.modeling_opt.OPTModel):\n final_layer_norm = base_model.decoder.final_layer_norm\n elif isinstance(base_model, models.gpt_neox.modeling_gpt_neox.GPTNeoXModel):\n final_layer_norm = base_model.final_layer_norm\n elif isinstance(\n base_model,\n (\n models.bloom.modeling_bloom.BloomModel,\n models.gpt2.modeling_gpt2.GPT2Model,\n models.gpt_neo.modeling_gpt_neo.GPTNeoModel,\n models.gptj.modeling_gptj.GPTJModel,\n ),\n ):\n final_layer_norm = base_model.ln_f\n elif isinstance(base_model, models.llama.modeling_llama.LlamaModel):\n final_layer_norm = base_model.norm\n elif isinstance(base_model, models.mistral.modeling_mistral.MistralModel):\n final_layer_norm = base_model.norm\n elif isinstance(base_model, models.gemma.modeling_gemma.GemmaModel):\n final_layer_norm = base_model.norm\n else:\n raise NotImplementedError(f\"Unknown model type {type(base_model)}\")\n\n if final_layer_norm is None:\n raise ValueError(\"Model does not have a final layer norm.\")\n\n assert isinstance(final_layer_norm, Norm.__args__) # type: ignore\n\n return final_layer_norm\n\n\n# Source: tuned_lens/nn/unembed.py\nclass Unembed(th.nn.Module):\n \"\"\"Module that maps transformer hidden states to logits (and vice versa).\"\"\"\n\n final_norm: model_surgery.Norm\n unembedding: th.nn.Linear\n\n def __init__(\n self,\n model: model_surgery.Model,\n ):\n \"\"\"Initialize unmebed.\n\n Args:\n model: A HuggingFace model from which to extract the unembedding matrix.\n \"\"\"\n super().__init__()\n final_norm = model_surgery.get_final_norm(model)\n unembedding_matrix = model_surgery.get_unembedding_matrix(model)\n\n self.final_norm = copy.deepcopy(final_norm)\n self.unembedding = copy.deepcopy(unembedding_matrix)\n\n # In general we don't want to finetune the unembed operation.\n self.requires_grad_(False)\n\n def unembedding_hash(self) -> str:\n \"\"\"Hash the unmbedding matrix to identify the model.\"\"\"\n parameter = self.unembedding.weight.data.detach().cpu().float().numpy()\n return tensor_hash(parameter)\n\n def forward(self, h: th.Tensor) -> th.Tensor:\n \"\"\"Convert hidden states into logits.\"\"\"\n return self.unembedding(self.final_norm(h))\n\n def invert(\n self,\n logits: th.Tensor,\n *,\n h0: Optional[th.Tensor] = None,\n max_iter: int = 1000,\n optimizer: Literal[\"lbfgs\", \"sgd\"] = \"lbfgs\",\n prior_weight: float = 0.0,\n prior: Optional[Distribution] = None,\n step_size: float = 1.0,\n tol: float = 1e-3,\n weight: Optional[th.Tensor] = None,\n ) -> InversionOutput:\n \"\"\"Project logits onto the image of the unemebed operation.\n\n When the hidden state dimension is smaller than the vocabulary size, the\n unembed operation cannot perfectly represent arbitrary logits, since its image\n is restricted to a subspace; this phenomenon is known as the softmax bottleneck\n (cf. https://arxiv.org/abs/1711.03953). Because of this, the inverse can only\n be approximate in general. Here, we use gradient-based optimization to find a\n hidden state that minimizes the KL divergence from the target distribution p to\n unembeded logits q(h): h* = argmin_h KL(p || q(h)).\n\n Args:\n logits: Tensor of shape `[..., vocab_size]` containing logits to invert.\n h0: Initial guess for the hidden state. If `None`, the least-squares\n solution of the linear equation xU = logits is used, where U is the\n unembedding matrix.\n max_iter: Maximum number of iterations for the optimizer to take.\n optimizer: Optimization algorithm to use. Currently, only \"lbfgs\" and \"sgd\"\n are supported.\n prior_weight: The weight of the prior distribution is given in the loss.\n prior: Prior distribution over hidden states used to regularize\n the inversion.\n step_size: The step size for the optimizer.\n tol: Tolerance for the inversion objective.\n weight: Optional tensor of shape `[..., vocab_size]` containing weights\n for each vocabulary item. If `None`, all classes are weighted equally.\n \"\"\"\n d_model = cast(int, self.unembedding.in_features)\n leading_dims = logits.shape[:-1]\n\n if h0 is None:\n # Initialize with the Moore-Penrose pseudoinverse\n h0 = th.zeros((*leading_dims, d_model), device=logits.device)\n\n # Sanity check the shape of the initial hidden state. Can silently lead to\n # incorrect results due to broadcasting if we don't check this.\n elif h0.shape != (*leading_dims, d_model):\n raise ValueError(\n f\"Initial hidden state has shape {h0.shape} but should have shape \"\n f\"{(*leading_dims, d_model)} given logits shape {logits.shape}.\"\n )\n\n h_star = th.nn.Parameter(h0)\n if optimizer == \"lbfgs\":\n opt = th.optim.LBFGS(\n [h_star],\n line_search_fn=\"strong_wolfe\",\n lr=step_size,\n max_iter=max_iter,\n tolerance_change=tol,\n )\n elif optimizer == \"sgd\":\n opt = th.optim.SGD([h_star], lr=step_size)\n else:\n raise ValueError(f\"Unknown optimizer '{optimizer}'\")\n\n log_p = logits.log_softmax(dim=-1)\n p = log_p.exp()\n if weight is not None:\n p *= weight\n\n def compute_loss(h: th.Tensor) -> tuple[th.Tensor, th.Tensor]:\n log_q = self(h).log_softmax(-1)\n kl = th.sum(p * (log_p - log_q), dim=-1).nanmean()\n loss = kl.clone()\n\n if prior_weight and prior is not None:\n # We evaluate the prior density on the post-norm hidden state,\n # to prevent the pre-norm hidden from collapsing towards zero.\n h_ = self.final_norm(h)\n loss += prior_weight * -prior.log_prob(h_).mean()\n\n return loss, kl\n\n nfev = 0 # Number of function evals, like in scipy.optimize.minimize\n loss, kl = log_p.new_tensor(th.inf), log_p.new_tensor(th.inf)\n\n def closure():\n nonlocal nfev, loss, kl\n nfev += 1\n\n opt.zero_grad(set_to_none=False)\n loss, kl = compute_loss(h_star)\n\n if not loss.isfinite():\n raise RuntimeError(\"Inversion objective is not finite.\")\n\n loss.backward()\n return loss\n\n grad_norm = log_p.new_tensor(th.inf)\n while nfev < max_iter:\n opt.step(closure) # type: ignore\n\n final_grad = h_star.grad\n assert final_grad is not None\n\n grad_norm = final_grad.norm()\n if grad_norm < tol or loss < tol:\n break\n\n with th.no_grad():\n output = InversionOutput(\n preimage=self.final_norm(h_star.data),\n grad_norm=grad_norm,\n kl=kl.detach(),\n loss=loss.detach(),\n nfev=nfev,\n )\n\n return output", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 7834}, "tests/plotting/test_trajectory_plotting.py::80": {"resolved_imports": ["tuned_lens/plotting/trajectory_plotting.py"], "used_names": ["TrajectoryLabels"], "enclosing_function": "test_template_and_customdata", "extracted_code": "# Source: tuned_lens/plotting/trajectory_plotting.py\nclass TrajectoryLabels:\n \"\"\"Contains sets of labels for each layer and position in the residual stream.\"\"\"\n\n label_strings: NDArray[np.str_]\n \"\"\"(n_layers x sequence_length) label for each layer and position in the stream.\"\"\"\n hover_over_entries: Optional[NDArray[np.str_]] = None\n \"\"\"(n_layers x sequence_length x rows x cols) table of strings to display when\n hovering over a cell. For example, the top k prediction from the lens.\"\"\"\n\n def stride(self, stride: int) -> \"TrajectoryLabels\":\n \"\"\"Return a new TrajectoryLabels with the given stride.\n\n Args:\n stride : The number of layers between each layer we keep.\n\n Returns:\n A new TrajectoryLabels with the given stride.\n \"\"\"\n assert stride > 0, f\"stride must be positive, got {stride}\"\n return replace(\n self,\n label_strings=_stride_keep_last(self.label_strings, stride),\n hover_over_entries=None\n if self.hover_over_entries is None\n else _stride_keep_last(self.hover_over_entries, stride),\n )\n\n def template_and_customdata(\n self, col_width_limit: int = 10\n ) -> Tuple[str, NDArray[np.str_]]:\n \"\"\"Construct a template for use with Plotly's hovertemplate.\"\"\"\n assert self.hover_over_entries is not None\n n_rows, n_cols = self.hover_over_entries.shape[-2:]\n\n vec_str_len = np.vectorize(len)\n lengths = vec_str_len(self.hover_over_entries)\n max_col_lens = np.max(lengths, axis=(0, 1, 2), keepdims=True)\n max_col_lens = np.minimum(max_col_lens + 1, col_width_limit)\n\n vec_truncate = np.vectorize(trunc_string_left)\n truncated_entries = vec_truncate(self.hover_over_entries, max_col_lens)\n\n html_table = \"\"\n for row in range(n_rows):\n for col in range(n_cols):\n html_table += f\"%{{customdata[{row*n_cols + col}]}}\"\n html_table += \"<br>\"\n html_table += \"<extra></extra>\"\n customdata = truncated_entries.reshape(\n self.hover_over_entries.shape[:2] + (-1,)\n )\n return html_table, customdata", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 2206}, "tests/test_model_surgery.py::10": {"resolved_imports": ["tuned_lens/__init__.py", "tuned_lens/model_surgery.py"], "used_names": ["PreTrainedModel", "model_surgery", "pytest"], "enclosing_function": "test_get_final_layer_norm_raises", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_subspaces.py::17": {"resolved_imports": ["tuned_lens/causal/subspaces.py"], "used_names": ["pytest", "remove_subspace"], "enclosing_function": "test_remove_subspace", "extracted_code": "# Source: tuned_lens/causal/subspaces.py\ndef remove_subspace(\n u: th.Tensor,\n A: th.Tensor,\n mode: Literal[\"mean\", \"resample\", \"zero\"] = \"zero\",\n orthonormal: bool = False,\n) -> th.Tensor:\n \"\"\"Remove all information in `u` along the column space of `A`.\n\n This can be done by zero, mean, or resample ablation. With zero ablation,\n `u` is projected onto the orthogonal complement of col(`A`), so the resulting\n vectors are orthogonal to every column in `A`. With mean ablation, `u` is projected\n onto the subspace s.t. the angles between the resulting vectors and the columns of\n `A` are equal to their mean values. With resample ablation, the variation in `u`\n is shuffled across vectors.\n\n Args:\n u: The vectors to be projected.\n A: Either a 2D matrix whose column space is to be removed, or a 1D vector whose\n span is to be removed.\n mode: Which method to use for removing information along the subspace.\n Defaults to `\"zero\"`.\n orthonormal: Whether to assume `A` is orthonormal. Defaults to `False`.\n\n Returns:\n th.Tensor: The transformed vectors.\n \"\"\"\n if A.ndim == 1:\n A = A[..., None]\n\n d, _ = A.shape\n if u.shape[-1] != d:\n raise ValueError(f\"Last dimension of u must be {d}, but is {u.shape[-1]}\")\n\n # https://en.wikipedia.org/wiki/Projection_(linear_algebra)#Properties_and_special_cases\n if orthonormal:\n proj = A @ A.mT\n else:\n proj = A @ th.linalg.solve(A.mT @ A, A.mT)\n\n if mode == \"zero\":\n dummy = -u\n else:\n samples = u.flatten(0, -2)\n N = samples.shape[0]\n if N < 2:\n raise ValueError(\"Need at least 2 vectors for mean and resample ablation\")\n\n if mode == \"mean\":\n dummy = samples.mean(0) - u\n elif mode == \"resample\":\n # Shuffle the rows of `samples` without fixed points.\n dummy = derange(samples).view_as(u) - u\n else:\n raise ValueError(f\"Unknown mode {mode}\")\n\n return u + th.einsum(\"ij,...j->...i\", proj, dummy)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 2090}, "tests/test_utils.py::12": {"resolved_imports": ["tuned_lens/utils.py"], "used_names": ["tensor_hash"], "enclosing_function": "test_tensor_hash", "extracted_code": "# Source: tuned_lens/utils.py\ndef tensor_hash(tensor: NDArray) -> str:\n \"\"\"Fast hash of a matrix that is robust to dtype and small perturbations.\n\n Note this relies on the ordering of the elements in the matrix, so it is\n if the matrix is in any way sorted this will not work well. In addition,\n this hash is intended for large tensors 64 + elements.\n \"\"\"\n return hashlib.sha256(str.encode(np.array_str(tensor, precision=1))).hexdigest()", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 455}, "tests/test_stats.py::22": {"resolved_imports": ["tuned_lens/stats/logit_stats.py"], "used_names": ["Dirichlet", "LogitStats", "kl_divergence", "random"], "enclosing_function": "test_logit_stats_correctness", "extracted_code": "# Source: tuned_lens/stats/logit_stats.py\nclass LogitStats:\n \"\"\"Online MLE for the Dirichlet distribution from which logits are sampled.\n\n Shape and device are lazily inferred from the first stream that is passed to\n `update()`. Only a running mean of the log-likelihoods for each class is stored,\n so memory use is negligible and constant in the number of samples. The maximum\n likelihood distribution is computed on request using L-BFGS.\n \"\"\"\n\n n: Optional[th.Tensor]\n marginal_probs: Optional[th.Tensor]\n sufficient_stats: Optional[th.Tensor]\n\n def __init__(\n self,\n n: Optional[th.Tensor] = None,\n marginal_probs: Optional[th.Tensor] = None,\n sufficient_stats: Optional[th.Tensor] = None,\n ):\n \"\"\"Create a LogitStats object.\"\"\"\n self.n = None\n self.marginal_probs = marginal_probs\n self.sufficient_stats = sufficient_stats\n\n def all_reduce_(self):\n \"\"\"All-reduce the stats across all processes.\"\"\"\n if (\n self.sufficient_stats is not None\n and self.marginal_probs is not None\n and self.n is not None\n ):\n n_x_sufficient_stats = self.n * self.sufficient_stats\n n_x_marginal_probs = self.n * self.marginal_probs\n maybe_all_reduce(n_x_sufficient_stats, op=\"sum\")\n maybe_all_reduce(n_x_marginal_probs, op=\"sum\")\n maybe_all_reduce(self.n, op=\"sum\")\n self.sufficient_stats = n_x_sufficient_stats / self.n\n self.marginal_probs = n_x_marginal_probs / self.n\n else:\n raise ValueError(\"Attempting to reduce an uninitialized LogitStats object\")\n\n @th.no_grad()\n def update(self, logits: th.Tensor, assume_normalized: bool = False):\n \"\"\"Update the sufficient statistics with a new batch of logits.\"\"\"\n K = logits.shape[-1]\n logits = logits.reshape(-1, K).float()\n if not assume_normalized:\n logits = logits.log_softmax(dim=-1)\n\n N = logits.shape[0]\n if self.n is None:\n self.n = th.tensor(0, dtype=th.int64, device=logits.device)\n elif len(self.n.shape) > 0:\n raise ValueError(f\"Expected n to be a scalar but got {self.n.shape=}\")\n\n if self.marginal_probs is None:\n self.marginal_probs = logits.new_zeros(K)\n elif self.marginal_probs.shape[-1] != K:\n raise ValueError(f\"Expected {self.marginal_probs.shape[-1]} but got {K}\")\n\n if self.sufficient_stats is None:\n self.sufficient_stats = logits.new_zeros(K)\n\n # Online mean update for the marginal probabilities\n delta = logits.exp().mean(0) - self.marginal_probs\n self.n += N\n self.marginal_probs += delta * N / self.n\n\n # Online mean update for the sufficient statistics\n delta = logits.mean(0) - self.sufficient_stats\n self.sufficient_stats += delta * N / self.n\n\n def mle(self, max_iter: int = 100, tol: float = 1e-4) -> Dirichlet:\n \"\"\"Compute the MLE for the Dirichlet generating the logits seen so far.\"\"\"\n if self.sufficient_stats is None:\n raise ValueError(\"No sufficient statistics available\")\n\n log_alpha = th.nn.Parameter(th.zeros_like(self.sufficient_stats))\n opt = th.optim.LBFGS(\n [log_alpha],\n line_search_fn=\"strong_wolfe\",\n max_iter=max_iter,\n tolerance_change=tol,\n )\n\n def closure():\n opt.zero_grad(set_to_none=False)\n\n # See http://jonathan-huang.org/research/dirichlet/dirichlet.pdf,\n # page 5 for the formula\n alpha = log_alpha.exp()\n normalizer = alpha.sum().lgamma() - alpha.lgamma().sum()\n loss = -(normalizer + (alpha - 1) @ self.sufficient_stats)\n loss.backward()\n return loss\n\n opt.step(closure) # type: ignore\n return Dirichlet(log_alpha.data.exp())", "n_imports_parsed": 4, "n_files_resolved": 1, "n_chars_extracted": 3953}, "tests/test_lenses.py::118": {"resolved_imports": ["tuned_lens/load_artifacts.py", "tuned_lens/nn/lenses.py", "tuned_lens/nn/unembed.py"], "used_names": ["Path", "TunedLens", "Unembed", "load_lens_artifacts", "mock", "pytest"], "enclosing_function": "test_from_model_and_pretrained_propogates_kwargs", "extracted_code": "# Source: tuned_lens/load_artifacts.py\ndef load_lens_artifacts(\n resource_id: str,\n repo_id: Optional[str] = None,\n repo_type: Optional[str] = None,\n revision: str = \"main\",\n config_file: str = \"config.json\",\n ckpt_file: str = \"params.pt\",\n subfolder: str = \"lens\",\n cache_dir: Optional[str] = None,\n) -> tuple[Path, Path]:\n \"\"\"First checks for lens resource locally then tries to download it from the hub.\n\n Args:\n resource_id: The id of the lens resource.\n repo_id: The repository to download the lens from. Defaults to\n 'AlignmentResearch/tuned-lens'. However, this default can be overridden by\n setting the TUNED_LENS_REPO_ID environment variable.\n repo_type: The type of repository to download the lens from. Defaults to\n 'space'. However, this default can be overridden by setting the\n TUNED_LENS_REPO_TYPE environment variable.\n config_file: The name of the config file in the folder contain the lens.\n ckpt_file: The name of the checkpoint file in the folder contain the lens.\n revision: The revision of the lens to download.\n subfolder: The subfolder of the repository to download the lens from.\n cache_dir: The directory to cache the lens in.\n\n Returns:\n * The path to the config.json file\n * The path to the params.pt file\n\n Raises:\n ValueError: if the lens resource could not be found.\n \"\"\"\n if repo_id is None:\n if os.environ.get(\"TUNED_LENS_REPO_ID\"):\n repo_id = os.environ[\"TUNED_LENS_REPO_ID\"]\n else:\n repo_id = \"AlignmentResearch/tuned-lens\"\n\n if repo_type is None:\n if os.environ.get(\"TUNED_LENS_REPO_TYPE\"):\n repo_type = os.environ[\"TUNED_LENS_REPO_TYPE\"]\n else:\n repo_type = \"space\"\n\n # Fist check if the resource id is a path to a folder that exists\n local_path = Path(resource_id)\n if (local_path / config_file).exists() and (local_path / ckpt_file).exists():\n return local_path / config_file, local_path / ckpt_file\n\n resource_folder = \"/\".join((subfolder, resource_id))\n try:\n params_path = hf_hub_download(\n filename=ckpt_file,\n repo_id=repo_id,\n repo_type=repo_type,\n revision=revision,\n subfolder=resource_folder,\n cache_dir=cache_dir,\n )\n\n config_path = hf_hub_download(\n filename=config_file,\n repo_id=repo_id,\n repo_type=repo_type,\n revision=revision,\n subfolder=resource_folder,\n cache_dir=cache_dir,\n )\n except EntryNotFoundError:\n available_lenses = available_lens_artifacts(\n repo_id=repo_id,\n repo_type=repo_type,\n revision=revision,\n config_file=config_file,\n ckpt_file=ckpt_file,\n subfolder=subfolder,\n )\n message = (\n f\"Could not find lens at the specified resource id. Available lens\"\n f\"resources are: {', '.join(available_lenses)}\"\n )\n raise ValueError(message)\n\n if config_path is not None and params_path is not None:\n return Path(config_path), Path(params_path)\n\n raise ValueError(\"Could not find lens resource locally or on the hf hub.\")\n\n\n# Source: tuned_lens/nn/lenses.py\nclass TunedLens(Lens):\n \"\"\"A tuned lens for decoding hidden states into logits.\"\"\"\n\n config: TunedLensConfig\n unembed: Unembed\n layer_translators: th.nn.ModuleList\n\n def __init__(\n self,\n unembed: Unembed,\n config: TunedLensConfig,\n ):\n \"\"\"Create a TunedLens.\n\n Args:\n unembed: The unembed operation to use.\n config: The configuration for this lens.\n \"\"\"\n super().__init__(unembed)\n\n self.config = config\n unembed_hash = unembed.unembedding_hash()\n config.unembed_hash = unembed_hash\n\n # The unembedding might be int8 if we're using bitsandbytes\n w = unembed.unembedding.weight\n dtype = w.dtype if th.is_floating_point(w) else th.float16\n\n translator = th.nn.Linear(\n config.d_model, config.d_model, bias=config.bias, dtype=dtype\n )\n translator.weight.data.zero_()\n translator.bias.data.zero_()\n\n # Don't include the final layer since it does not need a translator\n self.layer_translators = th.nn.ModuleList(\n [deepcopy(translator) for _ in range(self.config.num_hidden_layers)]\n )\n\n def __getitem__(self, item: int) -> th.nn.Module:\n \"\"\"Get the probe module at the given index.\"\"\"\n return self.layer_translators[item]\n\n def __iter__(self) -> Generator[th.nn.Module, None, None]:\n \"\"\"Get iterator over the translators within the lens.\"\"\"\n yield from self.layer_translators\n\n @classmethod\n def from_model(\n cls,\n model: PreTrainedModel,\n model_revision: Optional[str] = None,\n bias: bool = True,\n ) -> \"TunedLens\":\n \"\"\"Create a lens from a pretrained model.\n\n Args:\n model: The model to create the lens from.\n model_revision: The git revision of the model to used.\n bias: Whether to use a bias in the linear translators.\n\n Returns:\n A TunedLens instance.\n \"\"\"\n unembed = Unembed(model)\n config = TunedLensConfig(\n base_model_name_or_path=model.config.name_or_path,\n base_model_revision=model_revision,\n d_model=model.config.hidden_size,\n num_hidden_layers=model.config.num_hidden_layers,\n bias=bias,\n )\n\n return cls(unembed, config)\n\n @classmethod\n def from_model_and_pretrained(\n cls,\n model: PreTrainedModel,\n lens_resource_id: Optional[str] = None,\n **kwargs,\n ) -> \"TunedLens\":\n \"\"\"Load a tuned lens from a folder or hugging face hub.\n\n Args:\n model: The model to create the lens from.\n lens_resource_id: The resource id of the lens to load. Defaults to the\n model's name_or_path.\n **kwargs: Additional arguments to pass to\n :func:`tuned_lens.load_artifacts.load_lens_artifacts` and\n `th.load <https://pytorch.org/docs/stable/generated/torch.load.html>`_.\n\n Returns:\n A TunedLens instance whose unembedding is derived from the given model\n and whose layer translators are loaded from the given resource id.\n \"\"\"\n if lens_resource_id is None:\n lens_resource_id = model.config.name_or_path\n\n return cls.from_unembed_and_pretrained(\n Unembed(model), lens_resource_id, **kwargs\n )\n\n @classmethod\n def from_unembed_and_pretrained(\n cls,\n unembed: Unembed,\n lens_resource_id: str,\n **kwargs,\n ) -> \"TunedLens\":\n \"\"\"Load a tuned lens from a folder or hugging face hub.\n\n Args:\n unembed: The unembed operation to use for the lens.\n lens_resource_id: The resource id of the lens to load.\n **kwargs: Additional arguments to pass to\n :func:`tuned_lens.load_artifacts.load_lens_artifacts` and\n `th.load <https://pytorch.org/docs/stable/generated/torch.load.html>`_.\n\n Returns:\n A TunedLens instance.\n \"\"\"\n # Validate kwargs\n load_artifact_varnames = load_artifacts.load_lens_artifacts.__code__.co_varnames\n\n config_path, ckpt_path = load_artifacts.load_lens_artifacts(\n resource_id=lens_resource_id,\n **{k: v for k, v in kwargs.items() if k in load_artifact_varnames},\n )\n\n with open(config_path, \"r\") as f:\n config = TunedLensConfig.from_dict(json.load(f))\n\n # validate the unembed is the same as the one used to train the lens\n if config.unembed_hash and unembed.unembedding_hash() != config.unembed_hash:\n logger.warning(\n \"The unembedding matrix hash does not match the lens' hash.\"\n \"This lens may have been trained with a different unembedding.\"\n )\n\n # Create the lens\n lens = cls(unembed, config)\n\n th_load_kwargs = {\n **{k: v for k, v in kwargs.items() if k not in load_artifact_varnames}\n }\n # Load parameters\n state = th.load(ckpt_path, **th_load_kwargs)\n\n lens.layer_translators.load_state_dict(state)\n\n return lens\n\n def save(\n self,\n path: Union[Path, str],\n ckpt: str = \"params.pt\",\n config: str = \"config.json\",\n ) -> None:\n \"\"\"Save the lens to a directory.\n\n Args:\n path : The path to the directory to save the lens to.\n ckpt : The name of the checkpoint file to save the parameters to.\n config : The name of the config file to save the config to.\n \"\"\"\n path = Path(path)\n path.mkdir(exist_ok=True, parents=True)\n state_dict = self.layer_translators.state_dict()\n\n th.save(state_dict, path / ckpt)\n with open(path / config, \"w\") as f:\n json.dump(self.config.to_dict(), f)\n\n def transform_hidden(self, h: th.Tensor, idx: int) -> th.Tensor:\n \"\"\"Transform hidden state from layer `idx`.\"\"\"\n # Note that we add the translator output residually, in contrast to the formula\n # in the paper. By parametrizing it this way we ensure that weight decay\n # regularizes the transform toward the identity, not the zero transformation.\n return h + self[idx](h)\n\n def forward(self, h: th.Tensor, idx: int) -> th.Tensor:\n \"\"\"Transform and then decode the hidden states into logits.\"\"\"\n h = self.transform_hidden(h, idx)\n return self.unembed.forward(h)\n\n def __len__(self) -> int:\n \"\"\"Return the number of layer translators in the lens.\"\"\"\n return len(self.layer_translators)\n\n @th.inference_mode()\n def generate(\n self,\n model: PreTrainedModel,\n layer: int,\n input_ids: th.Tensor,\n do_sample: bool = True,\n temp: float = 1.0,\n max_new_tokens: int = 100,\n ) -> th.Tensor:\n \"\"\"Generate from the tuned lens at the given layer.\n\n Args:\n model: The base model the generate from. Usually the model this lens trained\n on.\n layer: The layer to generate from.\n input_ids: (batch x prompt_len) The input ids to generate from.\n do_sample: Whether to use sampling or greedy decoding.\n temp: The temperature to use for sampling.\n max_new_tokens: The maximum number of tokens to generate.\n\n Returns:\n The prompt concatenated with the newly generated tokens.\n \"\"\"\n eos_token = model.generation_config.eos_token_id\n\n tokens = input_ids\n if tokens.ndim == 1:\n tokens = tokens.unsqueeze(0)\n batch, prompt_len = tokens.shape\n del prompt_len\n past_key_values = None\n done = th.zeros(batch, dtype=th.bool)\n\n for _ in range(max_new_tokens):\n output = model(\n input_ids=tokens,\n output_hidden_states=True,\n use_cache=True,\n past_key_values=past_key_values,\n )\n past_key_values = output.past_key_values\n hidden = output.hidden_states[layer]\n new_hidden = hidden[:, -1, :]\n new_logits = self.forward(new_hidden, layer)\n if do_sample:\n new_logits = new_logits / temp\n probs = new_logits.softmax(dim=-1)\n new_tokens = th.multinomial(probs, num_samples=1)\n else:\n new_tokens = new_logits.argmax(dim=-1, keepdim=True)\n\n # Once a sequence has generated an EOS token, it should not generate any\n # other tokens.\n done = done | (new_tokens == eos_token)\n new_tokens = new_tokens.masked_fill(done, eos_token)\n tokens = th.cat([tokens, new_tokens], dim=-1)\n # Halt generation if all sequences have generated an EOS token.\n if done.all():\n break\n\n return tokens\n\n\n# Source: tuned_lens/nn/unembed.py\nclass Unembed(th.nn.Module):\n \"\"\"Module that maps transformer hidden states to logits (and vice versa).\"\"\"\n\n final_norm: model_surgery.Norm\n unembedding: th.nn.Linear\n\n def __init__(\n self,\n model: model_surgery.Model,\n ):\n \"\"\"Initialize unmebed.\n\n Args:\n model: A HuggingFace model from which to extract the unembedding matrix.\n \"\"\"\n super().__init__()\n final_norm = model_surgery.get_final_norm(model)\n unembedding_matrix = model_surgery.get_unembedding_matrix(model)\n\n self.final_norm = copy.deepcopy(final_norm)\n self.unembedding = copy.deepcopy(unembedding_matrix)\n\n # In general we don't want to finetune the unembed operation.\n self.requires_grad_(False)\n\n def unembedding_hash(self) -> str:\n \"\"\"Hash the unmbedding matrix to identify the model.\"\"\"\n parameter = self.unembedding.weight.data.detach().cpu().float().numpy()\n return tensor_hash(parameter)\n\n def forward(self, h: th.Tensor) -> th.Tensor:\n \"\"\"Convert hidden states into logits.\"\"\"\n return self.unembedding(self.final_norm(h))\n\n def invert(\n self,\n logits: th.Tensor,\n *,\n h0: Optional[th.Tensor] = None,\n max_iter: int = 1000,\n optimizer: Literal[\"lbfgs\", \"sgd\"] = \"lbfgs\",\n prior_weight: float = 0.0,\n prior: Optional[Distribution] = None,\n step_size: float = 1.0,\n tol: float = 1e-3,\n weight: Optional[th.Tensor] = None,\n ) -> InversionOutput:\n \"\"\"Project logits onto the image of the unemebed operation.\n\n When the hidden state dimension is smaller than the vocabulary size, the\n unembed operation cannot perfectly represent arbitrary logits, since its image\n is restricted to a subspace; this phenomenon is known as the softmax bottleneck\n (cf. https://arxiv.org/abs/1711.03953). Because of this, the inverse can only\n be approximate in general. Here, we use gradient-based optimization to find a\n hidden state that minimizes the KL divergence from the target distribution p to\n unembeded logits q(h): h* = argmin_h KL(p || q(h)).\n\n Args:\n logits: Tensor of shape `[..., vocab_size]` containing logits to invert.\n h0: Initial guess for the hidden state. If `None`, the least-squares\n solution of the linear equation xU = logits is used, where U is the\n unembedding matrix.\n max_iter: Maximum number of iterations for the optimizer to take.\n optimizer: Optimization algorithm to use. Currently, only \"lbfgs\" and \"sgd\"\n are supported.\n prior_weight: The weight of the prior distribution is given in the loss.\n prior: Prior distribution over hidden states used to regularize\n the inversion.\n step_size: The step size for the optimizer.\n tol: Tolerance for the inversion objective.\n weight: Optional tensor of shape `[..., vocab_size]` containing weights\n for each vocabulary item. If `None`, all classes are weighted equally.\n \"\"\"\n d_model = cast(int, self.unembedding.in_features)\n leading_dims = logits.shape[:-1]\n\n if h0 is None:\n # Initialize with the Moore-Penrose pseudoinverse\n h0 = th.zeros((*leading_dims, d_model), device=logits.device)\n\n # Sanity check the shape of the initial hidden state. Can silently lead to\n # incorrect results due to broadcasting if we don't check this.\n elif h0.shape != (*leading_dims, d_model):\n raise ValueError(\n f\"Initial hidden state has shape {h0.shape} but should have shape \"\n f\"{(*leading_dims, d_model)} given logits shape {logits.shape}.\"\n )\n\n h_star = th.nn.Parameter(h0)\n if optimizer == \"lbfgs\":\n opt = th.optim.LBFGS(\n [h_star],\n line_search_fn=\"strong_wolfe\",\n lr=step_size,\n max_iter=max_iter,\n tolerance_change=tol,\n )\n elif optimizer == \"sgd\":\n opt = th.optim.SGD([h_star], lr=step_size)\n else:\n raise ValueError(f\"Unknown optimizer '{optimizer}'\")\n\n log_p = logits.log_softmax(dim=-1)\n p = log_p.exp()\n if weight is not None:\n p *= weight\n\n def compute_loss(h: th.Tensor) -> tuple[th.Tensor, th.Tensor]:\n log_q = self(h).log_softmax(-1)\n kl = th.sum(p * (log_p - log_q), dim=-1).nanmean()\n loss = kl.clone()\n\n if prior_weight and prior is not None:\n # We evaluate the prior density on the post-norm hidden state,\n # to prevent the pre-norm hidden from collapsing towards zero.\n h_ = self.final_norm(h)\n loss += prior_weight * -prior.log_prob(h_).mean()\n\n return loss, kl\n\n nfev = 0 # Number of function evals, like in scipy.optimize.minimize\n loss, kl = log_p.new_tensor(th.inf), log_p.new_tensor(th.inf)\n\n def closure():\n nonlocal nfev, loss, kl\n nfev += 1\n\n opt.zero_grad(set_to_none=False)\n loss, kl = compute_loss(h_star)\n\n if not loss.isfinite():\n raise RuntimeError(\"Inversion objective is not finite.\")\n\n loss.backward()\n return loss\n\n grad_norm = log_p.new_tensor(th.inf)\n while nfev < max_iter:\n opt.step(closure) # type: ignore\n\n final_grad = h_star.grad\n assert final_grad is not None\n\n grad_norm = final_grad.norm()\n if grad_norm < tol or loss < tol:\n break\n\n with th.no_grad():\n output = InversionOutput(\n preimage=self.final_norm(h_star.data),\n grad_norm=grad_norm,\n kl=kl.detach(),\n loss=loss.detach(),\n nfev=nfev,\n )\n\n return output", "n_imports_parsed": 8, "n_files_resolved": 3, "n_chars_extracted": 18453}, "tests/test_load_artifact.py::18": {"resolved_imports": ["tuned_lens/load_artifacts.py"], "used_names": ["available_lens_artifacts", "pytest"], "enclosing_function": "test_list_available_lens_artifacts_smoke", "extracted_code": "# Source: tuned_lens/load_artifacts.py\ndef available_lens_artifacts(\n repo_id: str,\n repo_type: str,\n revision: str = \"main\",\n config_file: str = \"config.json\",\n ckpt_file: str = \"params.pt\",\n subfolder: str = \"lens\",\n) -> set[str]:\n \"\"\"Get the available lens artifacts from the hub.\"\"\"\n fs = HfFileSystem()\n\n repo_type = repo_type + \"s\" if not repo_type.endswith(\"s\") else repo_type\n\n root = Path(repo_type, repo_id, subfolder)\n with_config = map(\n Path,\n fs.glob(\n (root / \"**\" / config_file).as_posix(), revision=revision # type: ignore\n ),\n )\n\n with_pt = map(\n Path,\n fs.glob(\n (root / \"**\" / ckpt_file).as_posix(), revision=revision # type: ignore\n ),\n )\n paths = {p.parent for p in with_pt}.intersection({p.parent for p in with_config})\n return {p.relative_to(root).as_posix() for p in paths}", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 912}, "tests/test_unembed.py::28": {"resolved_imports": ["tuned_lens/model_surgery.py", "tuned_lens/nn/unembed.py"], "used_names": ["Unembed", "get_final_norm"], "enclosing_function": "test_correctness", "extracted_code": "# Source: tuned_lens/model_surgery.py\ndef get_final_norm(model: Model) -> Norm:\n \"\"\"Get the final norm from a model.\n\n This isn't standardized across models, so this will need to be updated as\n we add new models.\n \"\"\"\n if _transformer_lens_available and isinstance(model, tl.HookedTransformer):\n return model.ln_final\n\n if not hasattr(model, \"base_model\"):\n raise ValueError(\"Model does not have a `base_model` attribute.\")\n\n base_model = model.base_model\n if isinstance(base_model, models.opt.modeling_opt.OPTModel):\n final_layer_norm = base_model.decoder.final_layer_norm\n elif isinstance(base_model, models.gpt_neox.modeling_gpt_neox.GPTNeoXModel):\n final_layer_norm = base_model.final_layer_norm\n elif isinstance(\n base_model,\n (\n models.bloom.modeling_bloom.BloomModel,\n models.gpt2.modeling_gpt2.GPT2Model,\n models.gpt_neo.modeling_gpt_neo.GPTNeoModel,\n models.gptj.modeling_gptj.GPTJModel,\n ),\n ):\n final_layer_norm = base_model.ln_f\n elif isinstance(base_model, models.llama.modeling_llama.LlamaModel):\n final_layer_norm = base_model.norm\n elif isinstance(base_model, models.mistral.modeling_mistral.MistralModel):\n final_layer_norm = base_model.norm\n elif isinstance(base_model, models.gemma.modeling_gemma.GemmaModel):\n final_layer_norm = base_model.norm\n else:\n raise NotImplementedError(f\"Unknown model type {type(base_model)}\")\n\n if final_layer_norm is None:\n raise ValueError(\"Model does not have a final layer norm.\")\n\n assert isinstance(final_layer_norm, Norm.__args__) # type: ignore\n\n return final_layer_norm\n\n\n# Source: tuned_lens/nn/unembed.py\nclass Unembed(th.nn.Module):\n \"\"\"Module that maps transformer hidden states to logits (and vice versa).\"\"\"\n\n final_norm: model_surgery.Norm\n unembedding: th.nn.Linear\n\n def __init__(\n self,\n model: model_surgery.Model,\n ):\n \"\"\"Initialize unmebed.\n\n Args:\n model: A HuggingFace model from which to extract the unembedding matrix.\n \"\"\"\n super().__init__()\n final_norm = model_surgery.get_final_norm(model)\n unembedding_matrix = model_surgery.get_unembedding_matrix(model)\n\n self.final_norm = copy.deepcopy(final_norm)\n self.unembedding = copy.deepcopy(unembedding_matrix)\n\n # In general we don't want to finetune the unembed operation.\n self.requires_grad_(False)\n\n def unembedding_hash(self) -> str:\n \"\"\"Hash the unmbedding matrix to identify the model.\"\"\"\n parameter = self.unembedding.weight.data.detach().cpu().float().numpy()\n return tensor_hash(parameter)\n\n def forward(self, h: th.Tensor) -> th.Tensor:\n \"\"\"Convert hidden states into logits.\"\"\"\n return self.unembedding(self.final_norm(h))\n\n def invert(\n self,\n logits: th.Tensor,\n *,\n h0: Optional[th.Tensor] = None,\n max_iter: int = 1000,\n optimizer: Literal[\"lbfgs\", \"sgd\"] = \"lbfgs\",\n prior_weight: float = 0.0,\n prior: Optional[Distribution] = None,\n step_size: float = 1.0,\n tol: float = 1e-3,\n weight: Optional[th.Tensor] = None,\n ) -> InversionOutput:\n \"\"\"Project logits onto the image of the unemebed operation.\n\n When the hidden state dimension is smaller than the vocabulary size, the\n unembed operation cannot perfectly represent arbitrary logits, since its image\n is restricted to a subspace; this phenomenon is known as the softmax bottleneck\n (cf. https://arxiv.org/abs/1711.03953). Because of this, the inverse can only\n be approximate in general. Here, we use gradient-based optimization to find a\n hidden state that minimizes the KL divergence from the target distribution p to\n unembeded logits q(h): h* = argmin_h KL(p || q(h)).\n\n Args:\n logits: Tensor of shape `[..., vocab_size]` containing logits to invert.\n h0: Initial guess for the hidden state. If `None`, the least-squares\n solution of the linear equation xU = logits is used, where U is the\n unembedding matrix.\n max_iter: Maximum number of iterations for the optimizer to take.\n optimizer: Optimization algorithm to use. Currently, only \"lbfgs\" and \"sgd\"\n are supported.\n prior_weight: The weight of the prior distribution is given in the loss.\n prior: Prior distribution over hidden states used to regularize\n the inversion.\n step_size: The step size for the optimizer.\n tol: Tolerance for the inversion objective.\n weight: Optional tensor of shape `[..., vocab_size]` containing weights\n for each vocabulary item. If `None`, all classes are weighted equally.\n \"\"\"\n d_model = cast(int, self.unembedding.in_features)\n leading_dims = logits.shape[:-1]\n\n if h0 is None:\n # Initialize with the Moore-Penrose pseudoinverse\n h0 = th.zeros((*leading_dims, d_model), device=logits.device)\n\n # Sanity check the shape of the initial hidden state. Can silently lead to\n # incorrect results due to broadcasting if we don't check this.\n elif h0.shape != (*leading_dims, d_model):\n raise ValueError(\n f\"Initial hidden state has shape {h0.shape} but should have shape \"\n f\"{(*leading_dims, d_model)} given logits shape {logits.shape}.\"\n )\n\n h_star = th.nn.Parameter(h0)\n if optimizer == \"lbfgs\":\n opt = th.optim.LBFGS(\n [h_star],\n line_search_fn=\"strong_wolfe\",\n lr=step_size,\n max_iter=max_iter,\n tolerance_change=tol,\n )\n elif optimizer == \"sgd\":\n opt = th.optim.SGD([h_star], lr=step_size)\n else:\n raise ValueError(f\"Unknown optimizer '{optimizer}'\")\n\n log_p = logits.log_softmax(dim=-1)\n p = log_p.exp()\n if weight is not None:\n p *= weight\n\n def compute_loss(h: th.Tensor) -> tuple[th.Tensor, th.Tensor]:\n log_q = self(h).log_softmax(-1)\n kl = th.sum(p * (log_p - log_q), dim=-1).nanmean()\n loss = kl.clone()\n\n if prior_weight and prior is not None:\n # We evaluate the prior density on the post-norm hidden state,\n # to prevent the pre-norm hidden from collapsing towards zero.\n h_ = self.final_norm(h)\n loss += prior_weight * -prior.log_prob(h_).mean()\n\n return loss, kl\n\n nfev = 0 # Number of function evals, like in scipy.optimize.minimize\n loss, kl = log_p.new_tensor(th.inf), log_p.new_tensor(th.inf)\n\n def closure():\n nonlocal nfev, loss, kl\n nfev += 1\n\n opt.zero_grad(set_to_none=False)\n loss, kl = compute_loss(h_star)\n\n if not loss.isfinite():\n raise RuntimeError(\"Inversion objective is not finite.\")\n\n loss.backward()\n return loss\n\n grad_norm = log_p.new_tensor(th.inf)\n while nfev < max_iter:\n opt.step(closure) # type: ignore\n\n final_grad = h_star.grad\n assert final_grad is not None\n\n grad_norm = final_grad.norm()\n if grad_norm < tol or loss < tol:\n break\n\n with th.no_grad():\n output = InversionOutput(\n preimage=self.final_norm(h_star.data),\n grad_norm=grad_norm,\n kl=kl.detach(),\n loss=loss.detach(),\n nfev=nfev,\n )\n\n return output", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 7834}, "tests/test_lenses.py::72": {"resolved_imports": ["tuned_lens/load_artifacts.py", "tuned_lens/nn/lenses.py", "tuned_lens/nn/unembed.py"], "used_names": ["TunedLens"], "enclosing_function": "test_tuned_lens_from_model", "extracted_code": "# Source: tuned_lens/nn/lenses.py\nclass TunedLens(Lens):\n \"\"\"A tuned lens for decoding hidden states into logits.\"\"\"\n\n config: TunedLensConfig\n unembed: Unembed\n layer_translators: th.nn.ModuleList\n\n def __init__(\n self,\n unembed: Unembed,\n config: TunedLensConfig,\n ):\n \"\"\"Create a TunedLens.\n\n Args:\n unembed: The unembed operation to use.\n config: The configuration for this lens.\n \"\"\"\n super().__init__(unembed)\n\n self.config = config\n unembed_hash = unembed.unembedding_hash()\n config.unembed_hash = unembed_hash\n\n # The unembedding might be int8 if we're using bitsandbytes\n w = unembed.unembedding.weight\n dtype = w.dtype if th.is_floating_point(w) else th.float16\n\n translator = th.nn.Linear(\n config.d_model, config.d_model, bias=config.bias, dtype=dtype\n )\n translator.weight.data.zero_()\n translator.bias.data.zero_()\n\n # Don't include the final layer since it does not need a translator\n self.layer_translators = th.nn.ModuleList(\n [deepcopy(translator) for _ in range(self.config.num_hidden_layers)]\n )\n\n def __getitem__(self, item: int) -> th.nn.Module:\n \"\"\"Get the probe module at the given index.\"\"\"\n return self.layer_translators[item]\n\n def __iter__(self) -> Generator[th.nn.Module, None, None]:\n \"\"\"Get iterator over the translators within the lens.\"\"\"\n yield from self.layer_translators\n\n @classmethod\n def from_model(\n cls,\n model: PreTrainedModel,\n model_revision: Optional[str] = None,\n bias: bool = True,\n ) -> \"TunedLens\":\n \"\"\"Create a lens from a pretrained model.\n\n Args:\n model: The model to create the lens from.\n model_revision: The git revision of the model to used.\n bias: Whether to use a bias in the linear translators.\n\n Returns:\n A TunedLens instance.\n \"\"\"\n unembed = Unembed(model)\n config = TunedLensConfig(\n base_model_name_or_path=model.config.name_or_path,\n base_model_revision=model_revision,\n d_model=model.config.hidden_size,\n num_hidden_layers=model.config.num_hidden_layers,\n bias=bias,\n )\n\n return cls(unembed, config)\n\n @classmethod\n def from_model_and_pretrained(\n cls,\n model: PreTrainedModel,\n lens_resource_id: Optional[str] = None,\n **kwargs,\n ) -> \"TunedLens\":\n \"\"\"Load a tuned lens from a folder or hugging face hub.\n\n Args:\n model: The model to create the lens from.\n lens_resource_id: The resource id of the lens to load. Defaults to the\n model's name_or_path.\n **kwargs: Additional arguments to pass to\n :func:`tuned_lens.load_artifacts.load_lens_artifacts` and\n `th.load <https://pytorch.org/docs/stable/generated/torch.load.html>`_.\n\n Returns:\n A TunedLens instance whose unembedding is derived from the given model\n and whose layer translators are loaded from the given resource id.\n \"\"\"\n if lens_resource_id is None:\n lens_resource_id = model.config.name_or_path\n\n return cls.from_unembed_and_pretrained(\n Unembed(model), lens_resource_id, **kwargs\n )\n\n @classmethod\n def from_unembed_and_pretrained(\n cls,\n unembed: Unembed,\n lens_resource_id: str,\n **kwargs,\n ) -> \"TunedLens\":\n \"\"\"Load a tuned lens from a folder or hugging face hub.\n\n Args:\n unembed: The unembed operation to use for the lens.\n lens_resource_id: The resource id of the lens to load.\n **kwargs: Additional arguments to pass to\n :func:`tuned_lens.load_artifacts.load_lens_artifacts` and\n `th.load <https://pytorch.org/docs/stable/generated/torch.load.html>`_.\n\n Returns:\n A TunedLens instance.\n \"\"\"\n # Validate kwargs\n load_artifact_varnames = load_artifacts.load_lens_artifacts.__code__.co_varnames\n\n config_path, ckpt_path = load_artifacts.load_lens_artifacts(\n resource_id=lens_resource_id,\n **{k: v for k, v in kwargs.items() if k in load_artifact_varnames},\n )\n\n with open(config_path, \"r\") as f:\n config = TunedLensConfig.from_dict(json.load(f))\n\n # validate the unembed is the same as the one used to train the lens\n if config.unembed_hash and unembed.unembedding_hash() != config.unembed_hash:\n logger.warning(\n \"The unembedding matrix hash does not match the lens' hash.\"\n \"This lens may have been trained with a different unembedding.\"\n )\n\n # Create the lens\n lens = cls(unembed, config)\n\n th_load_kwargs = {\n **{k: v for k, v in kwargs.items() if k not in load_artifact_varnames}\n }\n # Load parameters\n state = th.load(ckpt_path, **th_load_kwargs)\n\n lens.layer_translators.load_state_dict(state)\n\n return lens\n\n def save(\n self,\n path: Union[Path, str],\n ckpt: str = \"params.pt\",\n config: str = \"config.json\",\n ) -> None:\n \"\"\"Save the lens to a directory.\n\n Args:\n path : The path to the directory to save the lens to.\n ckpt : The name of the checkpoint file to save the parameters to.\n config : The name of the config file to save the config to.\n \"\"\"\n path = Path(path)\n path.mkdir(exist_ok=True, parents=True)\n state_dict = self.layer_translators.state_dict()\n\n th.save(state_dict, path / ckpt)\n with open(path / config, \"w\") as f:\n json.dump(self.config.to_dict(), f)\n\n def transform_hidden(self, h: th.Tensor, idx: int) -> th.Tensor:\n \"\"\"Transform hidden state from layer `idx`.\"\"\"\n # Note that we add the translator output residually, in contrast to the formula\n # in the paper. By parametrizing it this way we ensure that weight decay\n # regularizes the transform toward the identity, not the zero transformation.\n return h + self[idx](h)\n\n def forward(self, h: th.Tensor, idx: int) -> th.Tensor:\n \"\"\"Transform and then decode the hidden states into logits.\"\"\"\n h = self.transform_hidden(h, idx)\n return self.unembed.forward(h)\n\n def __len__(self) -> int:\n \"\"\"Return the number of layer translators in the lens.\"\"\"\n return len(self.layer_translators)\n\n @th.inference_mode()\n def generate(\n self,\n model: PreTrainedModel,\n layer: int,\n input_ids: th.Tensor,\n do_sample: bool = True,\n temp: float = 1.0,\n max_new_tokens: int = 100,\n ) -> th.Tensor:\n \"\"\"Generate from the tuned lens at the given layer.\n\n Args:\n model: The base model the generate from. Usually the model this lens trained\n on.\n layer: The layer to generate from.\n input_ids: (batch x prompt_len) The input ids to generate from.\n do_sample: Whether to use sampling or greedy decoding.\n temp: The temperature to use for sampling.\n max_new_tokens: The maximum number of tokens to generate.\n\n Returns:\n The prompt concatenated with the newly generated tokens.\n \"\"\"\n eos_token = model.generation_config.eos_token_id\n\n tokens = input_ids\n if tokens.ndim == 1:\n tokens = tokens.unsqueeze(0)\n batch, prompt_len = tokens.shape\n del prompt_len\n past_key_values = None\n done = th.zeros(batch, dtype=th.bool)\n\n for _ in range(max_new_tokens):\n output = model(\n input_ids=tokens,\n output_hidden_states=True,\n use_cache=True,\n past_key_values=past_key_values,\n )\n past_key_values = output.past_key_values\n hidden = output.hidden_states[layer]\n new_hidden = hidden[:, -1, :]\n new_logits = self.forward(new_hidden, layer)\n if do_sample:\n new_logits = new_logits / temp\n probs = new_logits.softmax(dim=-1)\n new_tokens = th.multinomial(probs, num_samples=1)\n else:\n new_tokens = new_logits.argmax(dim=-1, keepdim=True)\n\n # Once a sequence has generated an EOS token, it should not generate any\n # other tokens.\n done = done | (new_tokens == eos_token)\n new_tokens = new_tokens.masked_fill(done, eos_token)\n tokens = th.cat([tokens, new_tokens], dim=-1)\n # Halt generation if all sequences have generated an EOS token.\n if done.all():\n break\n\n return tokens", "n_imports_parsed": 8, "n_files_resolved": 3, "n_chars_extracted": 8991}, "tests/test_load_artifact.py::11": {"resolved_imports": ["tuned_lens/load_artifacts.py"], "used_names": ["load_lens_artifacts", "pytest"], "enclosing_function": "test_load_lens_artifact_raises_smoke", "extracted_code": "# Source: tuned_lens/load_artifacts.py\ndef load_lens_artifacts(\n resource_id: str,\n repo_id: Optional[str] = None,\n repo_type: Optional[str] = None,\n revision: str = \"main\",\n config_file: str = \"config.json\",\n ckpt_file: str = \"params.pt\",\n subfolder: str = \"lens\",\n cache_dir: Optional[str] = None,\n) -> tuple[Path, Path]:\n \"\"\"First checks for lens resource locally then tries to download it from the hub.\n\n Args:\n resource_id: The id of the lens resource.\n repo_id: The repository to download the lens from. Defaults to\n 'AlignmentResearch/tuned-lens'. However, this default can be overridden by\n setting the TUNED_LENS_REPO_ID environment variable.\n repo_type: The type of repository to download the lens from. Defaults to\n 'space'. However, this default can be overridden by setting the\n TUNED_LENS_REPO_TYPE environment variable.\n config_file: The name of the config file in the folder contain the lens.\n ckpt_file: The name of the checkpoint file in the folder contain the lens.\n revision: The revision of the lens to download.\n subfolder: The subfolder of the repository to download the lens from.\n cache_dir: The directory to cache the lens in.\n\n Returns:\n * The path to the config.json file\n * The path to the params.pt file\n\n Raises:\n ValueError: if the lens resource could not be found.\n \"\"\"\n if repo_id is None:\n if os.environ.get(\"TUNED_LENS_REPO_ID\"):\n repo_id = os.environ[\"TUNED_LENS_REPO_ID\"]\n else:\n repo_id = \"AlignmentResearch/tuned-lens\"\n\n if repo_type is None:\n if os.environ.get(\"TUNED_LENS_REPO_TYPE\"):\n repo_type = os.environ[\"TUNED_LENS_REPO_TYPE\"]\n else:\n repo_type = \"space\"\n\n # Fist check if the resource id is a path to a folder that exists\n local_path = Path(resource_id)\n if (local_path / config_file).exists() and (local_path / ckpt_file).exists():\n return local_path / config_file, local_path / ckpt_file\n\n resource_folder = \"/\".join((subfolder, resource_id))\n try:\n params_path = hf_hub_download(\n filename=ckpt_file,\n repo_id=repo_id,\n repo_type=repo_type,\n revision=revision,\n subfolder=resource_folder,\n cache_dir=cache_dir,\n )\n\n config_path = hf_hub_download(\n filename=config_file,\n repo_id=repo_id,\n repo_type=repo_type,\n revision=revision,\n subfolder=resource_folder,\n cache_dir=cache_dir,\n )\n except EntryNotFoundError:\n available_lenses = available_lens_artifacts(\n repo_id=repo_id,\n repo_type=repo_type,\n revision=revision,\n config_file=config_file,\n ckpt_file=ckpt_file,\n subfolder=subfolder,\n )\n message = (\n f\"Could not find lens at the specified resource id. Available lens\"\n f\"resources are: {', '.join(available_lenses)}\"\n )\n raise ValueError(message)\n\n if config_path is not None and params_path is not None:\n return Path(config_path), Path(params_path)\n\n raise ValueError(\"Could not find lens resource locally or on the hf hub.\")", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 3341}, "tests/test_lenses.py::116": {"resolved_imports": ["tuned_lens/load_artifacts.py", "tuned_lens/nn/lenses.py", "tuned_lens/nn/unembed.py"], "used_names": ["Path", "TunedLens", "Unembed", "load_lens_artifacts", "mock", "pytest"], "enclosing_function": "test_from_model_and_pretrained_propogates_kwargs", "extracted_code": "# Source: tuned_lens/load_artifacts.py\ndef load_lens_artifacts(\n resource_id: str,\n repo_id: Optional[str] = None,\n repo_type: Optional[str] = None,\n revision: str = \"main\",\n config_file: str = \"config.json\",\n ckpt_file: str = \"params.pt\",\n subfolder: str = \"lens\",\n cache_dir: Optional[str] = None,\n) -> tuple[Path, Path]:\n \"\"\"First checks for lens resource locally then tries to download it from the hub.\n\n Args:\n resource_id: The id of the lens resource.\n repo_id: The repository to download the lens from. Defaults to\n 'AlignmentResearch/tuned-lens'. However, this default can be overridden by\n setting the TUNED_LENS_REPO_ID environment variable.\n repo_type: The type of repository to download the lens from. Defaults to\n 'space'. However, this default can be overridden by setting the\n TUNED_LENS_REPO_TYPE environment variable.\n config_file: The name of the config file in the folder contain the lens.\n ckpt_file: The name of the checkpoint file in the folder contain the lens.\n revision: The revision of the lens to download.\n subfolder: The subfolder of the repository to download the lens from.\n cache_dir: The directory to cache the lens in.\n\n Returns:\n * The path to the config.json file\n * The path to the params.pt file\n\n Raises:\n ValueError: if the lens resource could not be found.\n \"\"\"\n if repo_id is None:\n if os.environ.get(\"TUNED_LENS_REPO_ID\"):\n repo_id = os.environ[\"TUNED_LENS_REPO_ID\"]\n else:\n repo_id = \"AlignmentResearch/tuned-lens\"\n\n if repo_type is None:\n if os.environ.get(\"TUNED_LENS_REPO_TYPE\"):\n repo_type = os.environ[\"TUNED_LENS_REPO_TYPE\"]\n else:\n repo_type = \"space\"\n\n # Fist check if the resource id is a path to a folder that exists\n local_path = Path(resource_id)\n if (local_path / config_file).exists() and (local_path / ckpt_file).exists():\n return local_path / config_file, local_path / ckpt_file\n\n resource_folder = \"/\".join((subfolder, resource_id))\n try:\n params_path = hf_hub_download(\n filename=ckpt_file,\n repo_id=repo_id,\n repo_type=repo_type,\n revision=revision,\n subfolder=resource_folder,\n cache_dir=cache_dir,\n )\n\n config_path = hf_hub_download(\n filename=config_file,\n repo_id=repo_id,\n repo_type=repo_type,\n revision=revision,\n subfolder=resource_folder,\n cache_dir=cache_dir,\n )\n except EntryNotFoundError:\n available_lenses = available_lens_artifacts(\n repo_id=repo_id,\n repo_type=repo_type,\n revision=revision,\n config_file=config_file,\n ckpt_file=ckpt_file,\n subfolder=subfolder,\n )\n message = (\n f\"Could not find lens at the specified resource id. Available lens\"\n f\"resources are: {', '.join(available_lenses)}\"\n )\n raise ValueError(message)\n\n if config_path is not None and params_path is not None:\n return Path(config_path), Path(params_path)\n\n raise ValueError(\"Could not find lens resource locally or on the hf hub.\")\n\n\n# Source: tuned_lens/nn/lenses.py\nclass TunedLens(Lens):\n \"\"\"A tuned lens for decoding hidden states into logits.\"\"\"\n\n config: TunedLensConfig\n unembed: Unembed\n layer_translators: th.nn.ModuleList\n\n def __init__(\n self,\n unembed: Unembed,\n config: TunedLensConfig,\n ):\n \"\"\"Create a TunedLens.\n\n Args:\n unembed: The unembed operation to use.\n config: The configuration for this lens.\n \"\"\"\n super().__init__(unembed)\n\n self.config = config\n unembed_hash = unembed.unembedding_hash()\n config.unembed_hash = unembed_hash\n\n # The unembedding might be int8 if we're using bitsandbytes\n w = unembed.unembedding.weight\n dtype = w.dtype if th.is_floating_point(w) else th.float16\n\n translator = th.nn.Linear(\n config.d_model, config.d_model, bias=config.bias, dtype=dtype\n )\n translator.weight.data.zero_()\n translator.bias.data.zero_()\n\n # Don't include the final layer since it does not need a translator\n self.layer_translators = th.nn.ModuleList(\n [deepcopy(translator) for _ in range(self.config.num_hidden_layers)]\n )\n\n def __getitem__(self, item: int) -> th.nn.Module:\n \"\"\"Get the probe module at the given index.\"\"\"\n return self.layer_translators[item]\n\n def __iter__(self) -> Generator[th.nn.Module, None, None]:\n \"\"\"Get iterator over the translators within the lens.\"\"\"\n yield from self.layer_translators\n\n @classmethod\n def from_model(\n cls,\n model: PreTrainedModel,\n model_revision: Optional[str] = None,\n bias: bool = True,\n ) -> \"TunedLens\":\n \"\"\"Create a lens from a pretrained model.\n\n Args:\n model: The model to create the lens from.\n model_revision: The git revision of the model to used.\n bias: Whether to use a bias in the linear translators.\n\n Returns:\n A TunedLens instance.\n \"\"\"\n unembed = Unembed(model)\n config = TunedLensConfig(\n base_model_name_or_path=model.config.name_or_path,\n base_model_revision=model_revision,\n d_model=model.config.hidden_size,\n num_hidden_layers=model.config.num_hidden_layers,\n bias=bias,\n )\n\n return cls(unembed, config)\n\n @classmethod\n def from_model_and_pretrained(\n cls,\n model: PreTrainedModel,\n lens_resource_id: Optional[str] = None,\n **kwargs,\n ) -> \"TunedLens\":\n \"\"\"Load a tuned lens from a folder or hugging face hub.\n\n Args:\n model: The model to create the lens from.\n lens_resource_id: The resource id of the lens to load. Defaults to the\n model's name_or_path.\n **kwargs: Additional arguments to pass to\n :func:`tuned_lens.load_artifacts.load_lens_artifacts` and\n `th.load <https://pytorch.org/docs/stable/generated/torch.load.html>`_.\n\n Returns:\n A TunedLens instance whose unembedding is derived from the given model\n and whose layer translators are loaded from the given resource id.\n \"\"\"\n if lens_resource_id is None:\n lens_resource_id = model.config.name_or_path\n\n return cls.from_unembed_and_pretrained(\n Unembed(model), lens_resource_id, **kwargs\n )\n\n @classmethod\n def from_unembed_and_pretrained(\n cls,\n unembed: Unembed,\n lens_resource_id: str,\n **kwargs,\n ) -> \"TunedLens\":\n \"\"\"Load a tuned lens from a folder or hugging face hub.\n\n Args:\n unembed: The unembed operation to use for the lens.\n lens_resource_id: The resource id of the lens to load.\n **kwargs: Additional arguments to pass to\n :func:`tuned_lens.load_artifacts.load_lens_artifacts` and\n `th.load <https://pytorch.org/docs/stable/generated/torch.load.html>`_.\n\n Returns:\n A TunedLens instance.\n \"\"\"\n # Validate kwargs\n load_artifact_varnames = load_artifacts.load_lens_artifacts.__code__.co_varnames\n\n config_path, ckpt_path = load_artifacts.load_lens_artifacts(\n resource_id=lens_resource_id,\n **{k: v for k, v in kwargs.items() if k in load_artifact_varnames},\n )\n\n with open(config_path, \"r\") as f:\n config = TunedLensConfig.from_dict(json.load(f))\n\n # validate the unembed is the same as the one used to train the lens\n if config.unembed_hash and unembed.unembedding_hash() != config.unembed_hash:\n logger.warning(\n \"The unembedding matrix hash does not match the lens' hash.\"\n \"This lens may have been trained with a different unembedding.\"\n )\n\n # Create the lens\n lens = cls(unembed, config)\n\n th_load_kwargs = {\n **{k: v for k, v in kwargs.items() if k not in load_artifact_varnames}\n }\n # Load parameters\n state = th.load(ckpt_path, **th_load_kwargs)\n\n lens.layer_translators.load_state_dict(state)\n\n return lens\n\n def save(\n self,\n path: Union[Path, str],\n ckpt: str = \"params.pt\",\n config: str = \"config.json\",\n ) -> None:\n \"\"\"Save the lens to a directory.\n\n Args:\n path : The path to the directory to save the lens to.\n ckpt : The name of the checkpoint file to save the parameters to.\n config : The name of the config file to save the config to.\n \"\"\"\n path = Path(path)\n path.mkdir(exist_ok=True, parents=True)\n state_dict = self.layer_translators.state_dict()\n\n th.save(state_dict, path / ckpt)\n with open(path / config, \"w\") as f:\n json.dump(self.config.to_dict(), f)\n\n def transform_hidden(self, h: th.Tensor, idx: int) -> th.Tensor:\n \"\"\"Transform hidden state from layer `idx`.\"\"\"\n # Note that we add the translator output residually, in contrast to the formula\n # in the paper. By parametrizing it this way we ensure that weight decay\n # regularizes the transform toward the identity, not the zero transformation.\n return h + self[idx](h)\n\n def forward(self, h: th.Tensor, idx: int) -> th.Tensor:\n \"\"\"Transform and then decode the hidden states into logits.\"\"\"\n h = self.transform_hidden(h, idx)\n return self.unembed.forward(h)\n\n def __len__(self) -> int:\n \"\"\"Return the number of layer translators in the lens.\"\"\"\n return len(self.layer_translators)\n\n @th.inference_mode()\n def generate(\n self,\n model: PreTrainedModel,\n layer: int,\n input_ids: th.Tensor,\n do_sample: bool = True,\n temp: float = 1.0,\n max_new_tokens: int = 100,\n ) -> th.Tensor:\n \"\"\"Generate from the tuned lens at the given layer.\n\n Args:\n model: The base model the generate from. Usually the model this lens trained\n on.\n layer: The layer to generate from.\n input_ids: (batch x prompt_len) The input ids to generate from.\n do_sample: Whether to use sampling or greedy decoding.\n temp: The temperature to use for sampling.\n max_new_tokens: The maximum number of tokens to generate.\n\n Returns:\n The prompt concatenated with the newly generated tokens.\n \"\"\"\n eos_token = model.generation_config.eos_token_id\n\n tokens = input_ids\n if tokens.ndim == 1:\n tokens = tokens.unsqueeze(0)\n batch, prompt_len = tokens.shape\n del prompt_len\n past_key_values = None\n done = th.zeros(batch, dtype=th.bool)\n\n for _ in range(max_new_tokens):\n output = model(\n input_ids=tokens,\n output_hidden_states=True,\n use_cache=True,\n past_key_values=past_key_values,\n )\n past_key_values = output.past_key_values\n hidden = output.hidden_states[layer]\n new_hidden = hidden[:, -1, :]\n new_logits = self.forward(new_hidden, layer)\n if do_sample:\n new_logits = new_logits / temp\n probs = new_logits.softmax(dim=-1)\n new_tokens = th.multinomial(probs, num_samples=1)\n else:\n new_tokens = new_logits.argmax(dim=-1, keepdim=True)\n\n # Once a sequence has generated an EOS token, it should not generate any\n # other tokens.\n done = done | (new_tokens == eos_token)\n new_tokens = new_tokens.masked_fill(done, eos_token)\n tokens = th.cat([tokens, new_tokens], dim=-1)\n # Halt generation if all sequences have generated an EOS token.\n if done.all():\n break\n\n return tokens\n\n\n# Source: tuned_lens/nn/unembed.py\nclass Unembed(th.nn.Module):\n \"\"\"Module that maps transformer hidden states to logits (and vice versa).\"\"\"\n\n final_norm: model_surgery.Norm\n unembedding: th.nn.Linear\n\n def __init__(\n self,\n model: model_surgery.Model,\n ):\n \"\"\"Initialize unmebed.\n\n Args:\n model: A HuggingFace model from which to extract the unembedding matrix.\n \"\"\"\n super().__init__()\n final_norm = model_surgery.get_final_norm(model)\n unembedding_matrix = model_surgery.get_unembedding_matrix(model)\n\n self.final_norm = copy.deepcopy(final_norm)\n self.unembedding = copy.deepcopy(unembedding_matrix)\n\n # In general we don't want to finetune the unembed operation.\n self.requires_grad_(False)\n\n def unembedding_hash(self) -> str:\n \"\"\"Hash the unmbedding matrix to identify the model.\"\"\"\n parameter = self.unembedding.weight.data.detach().cpu().float().numpy()\n return tensor_hash(parameter)\n\n def forward(self, h: th.Tensor) -> th.Tensor:\n \"\"\"Convert hidden states into logits.\"\"\"\n return self.unembedding(self.final_norm(h))\n\n def invert(\n self,\n logits: th.Tensor,\n *,\n h0: Optional[th.Tensor] = None,\n max_iter: int = 1000,\n optimizer: Literal[\"lbfgs\", \"sgd\"] = \"lbfgs\",\n prior_weight: float = 0.0,\n prior: Optional[Distribution] = None,\n step_size: float = 1.0,\n tol: float = 1e-3,\n weight: Optional[th.Tensor] = None,\n ) -> InversionOutput:\n \"\"\"Project logits onto the image of the unemebed operation.\n\n When the hidden state dimension is smaller than the vocabulary size, the\n unembed operation cannot perfectly represent arbitrary logits, since its image\n is restricted to a subspace; this phenomenon is known as the softmax bottleneck\n (cf. https://arxiv.org/abs/1711.03953). Because of this, the inverse can only\n be approximate in general. Here, we use gradient-based optimization to find a\n hidden state that minimizes the KL divergence from the target distribution p to\n unembeded logits q(h): h* = argmin_h KL(p || q(h)).\n\n Args:\n logits: Tensor of shape `[..., vocab_size]` containing logits to invert.\n h0: Initial guess for the hidden state. If `None`, the least-squares\n solution of the linear equation xU = logits is used, where U is the\n unembedding matrix.\n max_iter: Maximum number of iterations for the optimizer to take.\n optimizer: Optimization algorithm to use. Currently, only \"lbfgs\" and \"sgd\"\n are supported.\n prior_weight: The weight of the prior distribution is given in the loss.\n prior: Prior distribution over hidden states used to regularize\n the inversion.\n step_size: The step size for the optimizer.\n tol: Tolerance for the inversion objective.\n weight: Optional tensor of shape `[..., vocab_size]` containing weights\n for each vocabulary item. If `None`, all classes are weighted equally.\n \"\"\"\n d_model = cast(int, self.unembedding.in_features)\n leading_dims = logits.shape[:-1]\n\n if h0 is None:\n # Initialize with the Moore-Penrose pseudoinverse\n h0 = th.zeros((*leading_dims, d_model), device=logits.device)\n\n # Sanity check the shape of the initial hidden state. Can silently lead to\n # incorrect results due to broadcasting if we don't check this.\n elif h0.shape != (*leading_dims, d_model):\n raise ValueError(\n f\"Initial hidden state has shape {h0.shape} but should have shape \"\n f\"{(*leading_dims, d_model)} given logits shape {logits.shape}.\"\n )\n\n h_star = th.nn.Parameter(h0)\n if optimizer == \"lbfgs\":\n opt = th.optim.LBFGS(\n [h_star],\n line_search_fn=\"strong_wolfe\",\n lr=step_size,\n max_iter=max_iter,\n tolerance_change=tol,\n )\n elif optimizer == \"sgd\":\n opt = th.optim.SGD([h_star], lr=step_size)\n else:\n raise ValueError(f\"Unknown optimizer '{optimizer}'\")\n\n log_p = logits.log_softmax(dim=-1)\n p = log_p.exp()\n if weight is not None:\n p *= weight\n\n def compute_loss(h: th.Tensor) -> tuple[th.Tensor, th.Tensor]:\n log_q = self(h).log_softmax(-1)\n kl = th.sum(p * (log_p - log_q), dim=-1).nanmean()\n loss = kl.clone()\n\n if prior_weight and prior is not None:\n # We evaluate the prior density on the post-norm hidden state,\n # to prevent the pre-norm hidden from collapsing towards zero.\n h_ = self.final_norm(h)\n loss += prior_weight * -prior.log_prob(h_).mean()\n\n return loss, kl\n\n nfev = 0 # Number of function evals, like in scipy.optimize.minimize\n loss, kl = log_p.new_tensor(th.inf), log_p.new_tensor(th.inf)\n\n def closure():\n nonlocal nfev, loss, kl\n nfev += 1\n\n opt.zero_grad(set_to_none=False)\n loss, kl = compute_loss(h_star)\n\n if not loss.isfinite():\n raise RuntimeError(\"Inversion objective is not finite.\")\n\n loss.backward()\n return loss\n\n grad_norm = log_p.new_tensor(th.inf)\n while nfev < max_iter:\n opt.step(closure) # type: ignore\n\n final_grad = h_star.grad\n assert final_grad is not None\n\n grad_norm = final_grad.norm()\n if grad_norm < tol or loss < tol:\n break\n\n with th.no_grad():\n output = InversionOutput(\n preimage=self.final_norm(h_star.data),\n grad_norm=grad_norm,\n kl=kl.detach(),\n loss=loss.detach(),\n nfev=nfev,\n )\n\n return output", "n_imports_parsed": 8, "n_files_resolved": 3, "n_chars_extracted": 18453}, "tests/test_load_artifact.py::17": {"resolved_imports": ["tuned_lens/load_artifacts.py"], "used_names": ["available_lens_artifacts", "pytest"], "enclosing_function": "test_list_available_lens_artifacts_smoke", "extracted_code": "# Source: tuned_lens/load_artifacts.py\ndef available_lens_artifacts(\n repo_id: str,\n repo_type: str,\n revision: str = \"main\",\n config_file: str = \"config.json\",\n ckpt_file: str = \"params.pt\",\n subfolder: str = \"lens\",\n) -> set[str]:\n \"\"\"Get the available lens artifacts from the hub.\"\"\"\n fs = HfFileSystem()\n\n repo_type = repo_type + \"s\" if not repo_type.endswith(\"s\") else repo_type\n\n root = Path(repo_type, repo_id, subfolder)\n with_config = map(\n Path,\n fs.glob(\n (root / \"**\" / config_file).as_posix(), revision=revision # type: ignore\n ),\n )\n\n with_pt = map(\n Path,\n fs.glob(\n (root / \"**\" / ckpt_file).as_posix(), revision=revision # type: ignore\n ),\n )\n paths = {p.parent for p in with_pt}.intersection({p.parent for p in with_config})\n return {p.relative_to(root).as_posix() for p in paths}", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 912}, "tests/test_lenses.py::147": {"resolved_imports": ["tuned_lens/load_artifacts.py", "tuned_lens/nn/lenses.py", "tuned_lens/nn/unembed.py"], "used_names": ["TunedLens"], "enclosing_function": "test_tuned_lens_generate_smoke", "extracted_code": "# Source: tuned_lens/nn/lenses.py\nclass TunedLens(Lens):\n \"\"\"A tuned lens for decoding hidden states into logits.\"\"\"\n\n config: TunedLensConfig\n unembed: Unembed\n layer_translators: th.nn.ModuleList\n\n def __init__(\n self,\n unembed: Unembed,\n config: TunedLensConfig,\n ):\n \"\"\"Create a TunedLens.\n\n Args:\n unembed: The unembed operation to use.\n config: The configuration for this lens.\n \"\"\"\n super().__init__(unembed)\n\n self.config = config\n unembed_hash = unembed.unembedding_hash()\n config.unembed_hash = unembed_hash\n\n # The unembedding might be int8 if we're using bitsandbytes\n w = unembed.unembedding.weight\n dtype = w.dtype if th.is_floating_point(w) else th.float16\n\n translator = th.nn.Linear(\n config.d_model, config.d_model, bias=config.bias, dtype=dtype\n )\n translator.weight.data.zero_()\n translator.bias.data.zero_()\n\n # Don't include the final layer since it does not need a translator\n self.layer_translators = th.nn.ModuleList(\n [deepcopy(translator) for _ in range(self.config.num_hidden_layers)]\n )\n\n def __getitem__(self, item: int) -> th.nn.Module:\n \"\"\"Get the probe module at the given index.\"\"\"\n return self.layer_translators[item]\n\n def __iter__(self) -> Generator[th.nn.Module, None, None]:\n \"\"\"Get iterator over the translators within the lens.\"\"\"\n yield from self.layer_translators\n\n @classmethod\n def from_model(\n cls,\n model: PreTrainedModel,\n model_revision: Optional[str] = None,\n bias: bool = True,\n ) -> \"TunedLens\":\n \"\"\"Create a lens from a pretrained model.\n\n Args:\n model: The model to create the lens from.\n model_revision: The git revision of the model to used.\n bias: Whether to use a bias in the linear translators.\n\n Returns:\n A TunedLens instance.\n \"\"\"\n unembed = Unembed(model)\n config = TunedLensConfig(\n base_model_name_or_path=model.config.name_or_path,\n base_model_revision=model_revision,\n d_model=model.config.hidden_size,\n num_hidden_layers=model.config.num_hidden_layers,\n bias=bias,\n )\n\n return cls(unembed, config)\n\n @classmethod\n def from_model_and_pretrained(\n cls,\n model: PreTrainedModel,\n lens_resource_id: Optional[str] = None,\n **kwargs,\n ) -> \"TunedLens\":\n \"\"\"Load a tuned lens from a folder or hugging face hub.\n\n Args:\n model: The model to create the lens from.\n lens_resource_id: The resource id of the lens to load. Defaults to the\n model's name_or_path.\n **kwargs: Additional arguments to pass to\n :func:`tuned_lens.load_artifacts.load_lens_artifacts` and\n `th.load <https://pytorch.org/docs/stable/generated/torch.load.html>`_.\n\n Returns:\n A TunedLens instance whose unembedding is derived from the given model\n and whose layer translators are loaded from the given resource id.\n \"\"\"\n if lens_resource_id is None:\n lens_resource_id = model.config.name_or_path\n\n return cls.from_unembed_and_pretrained(\n Unembed(model), lens_resource_id, **kwargs\n )\n\n @classmethod\n def from_unembed_and_pretrained(\n cls,\n unembed: Unembed,\n lens_resource_id: str,\n **kwargs,\n ) -> \"TunedLens\":\n \"\"\"Load a tuned lens from a folder or hugging face hub.\n\n Args:\n unembed: The unembed operation to use for the lens.\n lens_resource_id: The resource id of the lens to load.\n **kwargs: Additional arguments to pass to\n :func:`tuned_lens.load_artifacts.load_lens_artifacts` and\n `th.load <https://pytorch.org/docs/stable/generated/torch.load.html>`_.\n\n Returns:\n A TunedLens instance.\n \"\"\"\n # Validate kwargs\n load_artifact_varnames = load_artifacts.load_lens_artifacts.__code__.co_varnames\n\n config_path, ckpt_path = load_artifacts.load_lens_artifacts(\n resource_id=lens_resource_id,\n **{k: v for k, v in kwargs.items() if k in load_artifact_varnames},\n )\n\n with open(config_path, \"r\") as f:\n config = TunedLensConfig.from_dict(json.load(f))\n\n # validate the unembed is the same as the one used to train the lens\n if config.unembed_hash and unembed.unembedding_hash() != config.unembed_hash:\n logger.warning(\n \"The unembedding matrix hash does not match the lens' hash.\"\n \"This lens may have been trained with a different unembedding.\"\n )\n\n # Create the lens\n lens = cls(unembed, config)\n\n th_load_kwargs = {\n **{k: v for k, v in kwargs.items() if k not in load_artifact_varnames}\n }\n # Load parameters\n state = th.load(ckpt_path, **th_load_kwargs)\n\n lens.layer_translators.load_state_dict(state)\n\n return lens\n\n def save(\n self,\n path: Union[Path, str],\n ckpt: str = \"params.pt\",\n config: str = \"config.json\",\n ) -> None:\n \"\"\"Save the lens to a directory.\n\n Args:\n path : The path to the directory to save the lens to.\n ckpt : The name of the checkpoint file to save the parameters to.\n config : The name of the config file to save the config to.\n \"\"\"\n path = Path(path)\n path.mkdir(exist_ok=True, parents=True)\n state_dict = self.layer_translators.state_dict()\n\n th.save(state_dict, path / ckpt)\n with open(path / config, \"w\") as f:\n json.dump(self.config.to_dict(), f)\n\n def transform_hidden(self, h: th.Tensor, idx: int) -> th.Tensor:\n \"\"\"Transform hidden state from layer `idx`.\"\"\"\n # Note that we add the translator output residually, in contrast to the formula\n # in the paper. By parametrizing it this way we ensure that weight decay\n # regularizes the transform toward the identity, not the zero transformation.\n return h + self[idx](h)\n\n def forward(self, h: th.Tensor, idx: int) -> th.Tensor:\n \"\"\"Transform and then decode the hidden states into logits.\"\"\"\n h = self.transform_hidden(h, idx)\n return self.unembed.forward(h)\n\n def __len__(self) -> int:\n \"\"\"Return the number of layer translators in the lens.\"\"\"\n return len(self.layer_translators)\n\n @th.inference_mode()\n def generate(\n self,\n model: PreTrainedModel,\n layer: int,\n input_ids: th.Tensor,\n do_sample: bool = True,\n temp: float = 1.0,\n max_new_tokens: int = 100,\n ) -> th.Tensor:\n \"\"\"Generate from the tuned lens at the given layer.\n\n Args:\n model: The base model the generate from. Usually the model this lens trained\n on.\n layer: The layer to generate from.\n input_ids: (batch x prompt_len) The input ids to generate from.\n do_sample: Whether to use sampling or greedy decoding.\n temp: The temperature to use for sampling.\n max_new_tokens: The maximum number of tokens to generate.\n\n Returns:\n The prompt concatenated with the newly generated tokens.\n \"\"\"\n eos_token = model.generation_config.eos_token_id\n\n tokens = input_ids\n if tokens.ndim == 1:\n tokens = tokens.unsqueeze(0)\n batch, prompt_len = tokens.shape\n del prompt_len\n past_key_values = None\n done = th.zeros(batch, dtype=th.bool)\n\n for _ in range(max_new_tokens):\n output = model(\n input_ids=tokens,\n output_hidden_states=True,\n use_cache=True,\n past_key_values=past_key_values,\n )\n past_key_values = output.past_key_values\n hidden = output.hidden_states[layer]\n new_hidden = hidden[:, -1, :]\n new_logits = self.forward(new_hidden, layer)\n if do_sample:\n new_logits = new_logits / temp\n probs = new_logits.softmax(dim=-1)\n new_tokens = th.multinomial(probs, num_samples=1)\n else:\n new_tokens = new_logits.argmax(dim=-1, keepdim=True)\n\n # Once a sequence has generated an EOS token, it should not generate any\n # other tokens.\n done = done | (new_tokens == eos_token)\n new_tokens = new_tokens.masked_fill(done, eos_token)\n tokens = th.cat([tokens, new_tokens], dim=-1)\n # Halt generation if all sequences have generated an EOS token.\n if done.all():\n break\n\n return tokens", "n_imports_parsed": 8, "n_files_resolved": 3, "n_chars_extracted": 8991}, "tests/plotting/test_token_formatter.py::19": {"resolved_imports": ["tuned_lens/plotting/token_formatter.py"], "used_names": [], "enclosing_function": "test_format_ellipsis", "extracted_code": "", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 0}, "tests/test_distance.py::20": {"resolved_imports": ["tuned_lens/stats/distance.py"], "used_names": ["Categorical", "js_divergence", "kl_divergence"], "enclosing_function": "test_js_divergence", "extracted_code": "# Source: tuned_lens/stats/distance.py\ndef js_divergence(logit_p: th.Tensor, logit_q: th.Tensor, dim: int = -1) -> th.Tensor:\n \"\"\"Compute the Jensen-Shannon divergence between two sets of logits.\n\n Conceptually, the JSD is the info value of learning which of two distributions,\n P or Q, that a random variable is drawn from, starting from a uniform prior over\n P and Q. Since the entropy of a Bernoulli variable is at most ln(2), the JSD is\n guaranteed to be in the range [0, ln(2)]. It is also symmetric and finite even\n for distributions with disjoint supports.\n\n Mathematically, the JSD is simply [KL(P || M) + KL(Q || M)] / 2, where M\n is the mean of P and Q.\n \"\"\"\n log_p = logit_p.log_softmax(dim)\n log_q = logit_q.log_softmax(dim)\n\n # Mean of P and Q\n log_m = th.stack([log_p, log_q]).sub(math.log(2)).logsumexp(0)\n\n kl_p = th.sum(log_p.exp() * (log_p - log_m), dim)\n kl_q = th.sum(log_q.exp() * (log_q - log_m), dim)\n return 0.5 * (kl_p + kl_q)", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 999}}} |