|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2023-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +"""Extract hidden states from an HF-compatible LLM.""" |
| 17 | + |
| 18 | +import argparse |
| 19 | +import asyncio |
| 20 | +import json |
| 21 | +from pathlib import Path |
| 22 | + |
| 23 | +import torch |
| 24 | +from tqdm import tqdm as tqdm |
| 25 | +from transformers import AutoModel, AutoTokenizer |
| 26 | + |
| 27 | + |
| 28 | +def parse_args() -> argparse.Namespace: |
| 29 | + parser = argparse.ArgumentParser( |
| 30 | + description="""Collect hidden states from conversations |
| 31 | + by running full conversations through a Hugging Face model.""" |
| 32 | + ) |
| 33 | + |
| 34 | + ## Model & Generation Parameters ## |
| 35 | + parser.add_argument( |
| 36 | + "--model", |
| 37 | + type=str, |
| 38 | + required=True, |
| 39 | + help="Name of the served model.", |
| 40 | + ) |
| 41 | + |
| 42 | + ## Client Parameters ## |
| 43 | + parser.add_argument( |
| 44 | + "--max-seq-len", |
| 45 | + type=int, |
| 46 | + default=3072, |
| 47 | + help="""Maximum number of tokens in a conversation. Longer conversations will be skipped. |
| 48 | + Defaults to 3072 tokens.""", |
| 49 | + ) |
| 50 | + |
| 51 | + ## I/O Parameters ## |
| 52 | + parser.add_argument( |
| 53 | + "--input-file", |
| 54 | + type=Path, |
| 55 | + required=True, |
| 56 | + help="""Path to the input `jsonl` file containing conversations. |
| 57 | + Each entry must have a unique `conversation_id` field and a `conversations` field |
| 58 | + containing a list of messages.""", |
| 59 | + ) |
| 60 | + parser.add_argument( |
| 61 | + "--output-dir", |
| 62 | + type=Path, |
| 63 | + required=True, |
| 64 | + help="""Root directory in which to save the hidden states. |
| 65 | + The data will be saved as a torch (`.pt`) dump file for each conversation.""", |
| 66 | + ) |
| 67 | + parser.add_argument( |
| 68 | + "--debug-max-num-conversations", |
| 69 | + type=int, |
| 70 | + default=None, |
| 71 | + help="""For debugging purposes, limit the number of conversations processed. |
| 72 | + Default is None, meaning no limit.""", |
| 73 | + ) |
| 74 | + |
| 75 | + return parser.parse_args() |
| 76 | + |
| 77 | + |
| 78 | +async def main(args: argparse.Namespace) -> None: |
| 79 | + all_conversations = [] |
| 80 | + with args.input_file.open("r", encoding="utf-8") as f: |
| 81 | + all_conversations.extend([json.loads(line) for line in f if line.strip()]) |
| 82 | + |
| 83 | + if any(not entry.get("conversation_id") for entry in all_conversations): |
| 84 | + msg = "All conversations must have a 'conversation_id' field." |
| 85 | + raise ValueError(msg) |
| 86 | + |
| 87 | + print("Loaded", len(all_conversations), "conversations from", args.input_file) |
| 88 | + |
| 89 | + model = AutoModel.from_pretrained(args.model, torch_dtype="auto", device_map="auto") |
| 90 | + num_hidden_layers = getattr(model.config, "num_hidden_layers", None) |
| 91 | + |
| 92 | + tokenizer = AutoTokenizer.from_pretrained(args.model) |
| 93 | + if tokenizer.pad_token is None: |
| 94 | + tokenizer.pad_token = tokenizer.eos_token |
| 95 | + |
| 96 | + output_dir = args.output_dir |
| 97 | + output_dir.mkdir(parents=True, exist_ok=True) |
| 98 | + num_skipped_too_long = 0 |
| 99 | + num_invalid = 0 |
| 100 | + num_success = 0 |
| 101 | + num_total_conversations = min( |
| 102 | + len(all_conversations), args.debug_max_num_conversations or len(all_conversations) |
| 103 | + ) |
| 104 | + for entry in tqdm( |
| 105 | + all_conversations[: args.debug_max_num_conversations], |
| 106 | + desc="Processing conversations", |
| 107 | + total=num_total_conversations, |
| 108 | + ): |
| 109 | + conversation_id = entry["conversation_id"] |
| 110 | + conversations = entry["conversations"] |
| 111 | + if not conversations or not isinstance(conversations, list): |
| 112 | + num_invalid += 1 |
| 113 | + continue |
| 114 | + |
| 115 | + # Tokenize and check length |
| 116 | + input_ids = tokenizer.apply_chat_template( |
| 117 | + conversations, return_tensors="pt", add_generation_template=False |
| 118 | + ) |
| 119 | + num_input_tokens = input_ids.shape[1] |
| 120 | + if num_input_tokens <= 10 or num_input_tokens > args.max_seq_len: |
| 121 | + num_skipped_too_long += 1 |
| 122 | + continue |
| 123 | + |
| 124 | + # Get hidden states |
| 125 | + with torch.inference_mode(): |
| 126 | + outputs = model(input_ids=input_ids.to(model.device), output_hidden_states=True) |
| 127 | + if num_hidden_layers is None: |
| 128 | + num_hidden_layers = len(outputs.hidden_states) - 1 |
| 129 | + else: |
| 130 | + assert num_hidden_layers + 1 == len(outputs.hidden_states), ( |
| 131 | + f"Expected {num_hidden_layers}+1 layers of hidden states, but got {len(outputs.hidden_states)}." |
| 132 | + ) |
| 133 | + # Extract hidden states from layers with index (2, N/2, N-3), and the output hidden states |
| 134 | + hidden_states = outputs.hidden_states |
| 135 | + selected_layer_indices = [2, num_hidden_layers // 2, num_hidden_layers - 3] |
| 136 | + aux_hidden_states = torch.cat( |
| 137 | + [hidden_states[i].squeeze(0).cpu() for i in selected_layer_indices], dim=-1 |
| 138 | + ) |
| 139 | + output_hidden_states = outputs.last_hidden_state.squeeze(0).cpu() |
| 140 | + output_file = output_dir / f"{conversation_id}.pt" |
| 141 | + num_success += 1 |
| 142 | + with open(output_file, "wb") as f: |
| 143 | + torch.save( |
| 144 | + { |
| 145 | + "input_ids": input_ids.squeeze(0).cpu(), |
| 146 | + "hidden_states": output_hidden_states, |
| 147 | + "aux_hidden_states": aux_hidden_states, |
| 148 | + "conversation_id": conversation_id, |
| 149 | + }, |
| 150 | + f, |
| 151 | + ) |
| 152 | + |
| 153 | + if num_skipped_too_long > 0: |
| 154 | + print(f"Skipped {num_skipped_too_long} conversations due to length constraints.") |
| 155 | + if num_invalid > 0: |
| 156 | + print(f"Skipped {num_invalid} invalid conversations without proper fields.") |
| 157 | + |
| 158 | + if num_success == num_total_conversations: |
| 159 | + print(f"Successfully processed all {num_success} conversations.") |
| 160 | + else: |
| 161 | + print( |
| 162 | + f"Successfully processed {num_success} out of {num_total_conversations} conversations." |
| 163 | + ) |
| 164 | + |
| 165 | + |
| 166 | +if __name__ == "__main__": |
| 167 | + cli_args = parse_args() |
| 168 | + asyncio.run(main(cli_args)) |
0 commit comments