Initial upload of fine‑tuned Gemma + custom tokenizer
Browse files- gemma_explicit_tokenizer.py +374 -0
- model-00001-of-00005.safetensors +1 -1
- model-00002-of-00005.safetensors +1 -1
- model-00003-of-00005.safetensors +1 -1
- model-00004-of-00005.safetensors +1 -1
- model-00005-of-00005.safetensors +1 -1
- tokenizer_config.json +7 -5
- training_args.bin +1 -1
gemma_explicit_tokenizer.py
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Custom Gemma Tokenizer for explicit Format
|
| 3 |
+
|
| 4 |
+
This tokenizer implements the explicit format for message processing:
|
| 5 |
+
Format: Uses the standard chat template with proper role labels (user/assistant)
|
| 6 |
+
|
| 7 |
+
The explicit format uses the model's built-in chat template and includes proper
|
| 8 |
+
loss computation flags for training.
|
| 9 |
+
|
| 10 |
+
To save:
|
| 11 |
+
uv run tokenizers/gemma_explicit_tokenizer.py
|
| 12 |
+
which will save the tokenizer to the repos/explicit-gemma-tokenizer directory.
|
| 13 |
+
mkdir repos/explicit12b
|
| 14 |
+
# copy model over
|
| 15 |
+
cp models_v8/base_modified-google-gemma-3-12b-pt-/models/_explicit/checkpoint-8/* repos/explicit12b/
|
| 16 |
+
# copy tokenizer over
|
| 17 |
+
cp repos/explicit-gemma-tokenizer/* repos/explicit12b/
|
| 18 |
+
# upload to hf
|
| 19 |
+
|
| 20 |
+
uv run upload_to_hf.py \
|
| 21 |
+
--folder repos/explicit12b \
|
| 22 |
+
--repo-id tsor13/explicit12b
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
from typing import List, Dict, Any, Optional, Union
|
| 26 |
+
from transformers import AutoTokenizer
|
| 27 |
+
from transformers.models.gemma.tokenization_gemma_fast import GemmaTokenizerFast
|
| 28 |
+
from transformers.models.gemma.tokenization_gemma import GemmaTokenizer
|
| 29 |
+
import warnings
|
| 30 |
+
import difflib
|
| 31 |
+
import json
|
| 32 |
+
import os
|
| 33 |
+
import sys
|
| 34 |
+
|
| 35 |
+
# Add parent directory to path to import chat_utils
|
| 36 |
+
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 37 |
+
from chat_utils import chat_messages_to_text_loss, chat_messages_to_raw_text
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class GemmaExplicitTokenizer(GemmaTokenizerFast):
|
| 41 |
+
"""
|
| 42 |
+
Custom tokenizer for Gemma models that implements explicit format message processing.
|
| 43 |
+
|
| 44 |
+
This tokenizer formats messages using the explicit format where:
|
| 45 |
+
- Messages use the standard chat template with proper role labels
|
| 46 |
+
- Uses the model's built-in chat formatting
|
| 47 |
+
- Loss is computed on the assistant/output sections
|
| 48 |
+
|
| 49 |
+
Attributes:
|
| 50 |
+
start_string (str): The starting string used for output generation (depends on tokenizer)
|
| 51 |
+
end_string (str): The ending string used for output generation (depends on tokenizer)
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
def __init__(self, *args, **kwargs):
|
| 55 |
+
"""
|
| 56 |
+
Initialize the custom tokenizer.
|
| 57 |
+
|
| 58 |
+
Accepts the same arguments as GemmaTokenizerFast.
|
| 59 |
+
"""
|
| 60 |
+
super().__init__(*args, **kwargs)
|
| 61 |
+
|
| 62 |
+
# For explicit format, we use the tokenizer's own chat template
|
| 63 |
+
# The start/end strings will be determined by the chat template
|
| 64 |
+
self.start_string = None # Will be set dynamically
|
| 65 |
+
self.end_string = None # Will be set dynamically
|
| 66 |
+
|
| 67 |
+
# Add custom attributes to the tokenizer config for saving/loading
|
| 68 |
+
if not hasattr(self, 'init_kwargs'):
|
| 69 |
+
self.init_kwargs = {}
|
| 70 |
+
self.init_kwargs['start_string'] = self.start_string
|
| 71 |
+
self.init_kwargs['end_string'] = self.end_string
|
| 72 |
+
|
| 73 |
+
@classmethod
|
| 74 |
+
def from_gemma_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs):
|
| 75 |
+
"""
|
| 76 |
+
Load a tokenizer from a pretrained model or path.
|
| 77 |
+
|
| 78 |
+
This method ensures our custom class is used instead of the base GemmaTokenizerFast.
|
| 79 |
+
"""
|
| 80 |
+
# Load the base tokenizer first to get all configuration
|
| 81 |
+
base_tokenizer = GemmaTokenizerFast.from_pretrained(
|
| 82 |
+
pretrained_model_name_or_path, *args, **kwargs
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
# Create new instance of our custom class by copying the base tokenizer
|
| 86 |
+
custom_tokenizer = cls.__new__(cls)
|
| 87 |
+
|
| 88 |
+
# Copy all attributes from base tokenizer
|
| 89 |
+
for attr, value in base_tokenizer.__dict__.items():
|
| 90 |
+
setattr(custom_tokenizer, attr, value)
|
| 91 |
+
|
| 92 |
+
# Initialize our custom attributes for explicit format
|
| 93 |
+
custom_tokenizer.start_string = None # Will be determined dynamically
|
| 94 |
+
custom_tokenizer.end_string = None # Will be determined dynamically
|
| 95 |
+
|
| 96 |
+
# Update init_kwargs to include our custom attributes
|
| 97 |
+
if not hasattr(custom_tokenizer, 'init_kwargs'):
|
| 98 |
+
custom_tokenizer.init_kwargs = {}
|
| 99 |
+
custom_tokenizer.init_kwargs['start_string'] = custom_tokenizer.start_string
|
| 100 |
+
custom_tokenizer.init_kwargs['end_string'] = custom_tokenizer.end_string
|
| 101 |
+
|
| 102 |
+
return custom_tokenizer
|
| 103 |
+
|
| 104 |
+
def save_pretrained(self, save_directory: Union[str, os.PathLike], **kwargs):
|
| 105 |
+
"""
|
| 106 |
+
Save the tokenizer to a directory, including custom configuration.
|
| 107 |
+
"""
|
| 108 |
+
# Call parent save method
|
| 109 |
+
super().save_pretrained(save_directory, **kwargs)
|
| 110 |
+
|
| 111 |
+
# Save custom configuration
|
| 112 |
+
config_file = os.path.join(save_directory, "tokenizer_config.json")
|
| 113 |
+
if os.path.exists(config_file):
|
| 114 |
+
with open(config_file, 'r') as f:
|
| 115 |
+
config = json.load(f)
|
| 116 |
+
else:
|
| 117 |
+
config = {}
|
| 118 |
+
|
| 119 |
+
# Add our custom class info
|
| 120 |
+
config["tokenizer_class"] = "GemmaExplicitTokenizer"
|
| 121 |
+
config["start_string"] = self.start_string
|
| 122 |
+
config["end_string"] = self.end_string
|
| 123 |
+
# Point to our custom class in the uploaded file
|
| 124 |
+
config["auto_map"] = {
|
| 125 |
+
"AutoTokenizer": ["gemma_explicit_tokenizer.GemmaExplicitTokenizer", "gemma_explicit_tokenizer.GemmaExplicitTokenizer"]
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
with open(config_file, 'w') as f:
|
| 129 |
+
json.dump(config, f, indent=2)
|
| 130 |
+
|
| 131 |
+
def messages_to_loss_texts(
|
| 132 |
+
self,
|
| 133 |
+
messages: List[Dict[str, Any]],
|
| 134 |
+
loss_on_start_token: bool = False,
|
| 135 |
+
) -> List[Dict[str, Any]]:
|
| 136 |
+
"""
|
| 137 |
+
From messages (description / input / output) to texts (text / compute_loss) with whether or not loss should be calculated on the text for training.
|
| 138 |
+
Uses the explicit format from chat_utils.
|
| 139 |
+
"""
|
| 140 |
+
return chat_messages_to_text_loss(messages, self, loss_on_start_token, start_gen_as="output")
|
| 141 |
+
|
| 142 |
+
def messages_to_text(
|
| 143 |
+
self,
|
| 144 |
+
messages: List[Dict[str, Any]],
|
| 145 |
+
start_generation: bool = False,
|
| 146 |
+
) -> str:
|
| 147 |
+
"""
|
| 148 |
+
Messages (description / input / output) to raw text (text).
|
| 149 |
+
Uses the explicit format from chat_utils.
|
| 150 |
+
"""
|
| 151 |
+
return chat_messages_to_raw_text(messages, self, start_generation=start_generation, start_gen_as="output")
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def tokenize_messages(
|
| 155 |
+
self,
|
| 156 |
+
messages: List[Dict[str, Any]] | List[List[Dict[str, Any]]],
|
| 157 |
+
start_generation: bool = False,
|
| 158 |
+
**kwargs,
|
| 159 |
+
):
|
| 160 |
+
"""
|
| 161 |
+
For tokenizing from messages to texts. Supports batching. Good for generation
|
| 162 |
+
"""
|
| 163 |
+
if isinstance(messages, list) and isinstance(messages[0], list):
|
| 164 |
+
# Handle list of lists of messages
|
| 165 |
+
all_texts = []
|
| 166 |
+
for message_list in messages:
|
| 167 |
+
texts = self.messages_to_text(message_list, start_generation)
|
| 168 |
+
all_texts.append(texts)
|
| 169 |
+
else:
|
| 170 |
+
# Handle single list of messages
|
| 171 |
+
texts = self.messages_to_text(messages, start_generation)
|
| 172 |
+
all_texts = [texts]
|
| 173 |
+
|
| 174 |
+
# Tokenize all texts
|
| 175 |
+
processed = self(text=all_texts, **kwargs)
|
| 176 |
+
return processed
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def tokenize_loss_texts(
|
| 180 |
+
self,
|
| 181 |
+
texts: List[Dict[str, Any]],
|
| 182 |
+
loss_on_start_token: bool = False,
|
| 183 |
+
loss_on_eos: bool = False,
|
| 184 |
+
include_eos: bool = True,
|
| 185 |
+
):
|
| 186 |
+
"""
|
| 187 |
+
Tokenize texts (text / compute_loss) to tokenized texts (input_ids / attention_mask / labels).
|
| 188 |
+
|
| 189 |
+
Needs more complex logic to handle the back and forth labeling.
|
| 190 |
+
"""
|
| 191 |
+
if loss_on_eos:
|
| 192 |
+
raise ValueError("Loss on EOS is not currently supported.")
|
| 193 |
+
|
| 194 |
+
# Handle single string input
|
| 195 |
+
if isinstance(texts, str):
|
| 196 |
+
processed = self(text=texts)
|
| 197 |
+
# Add EOS token if needed
|
| 198 |
+
if (self.eos_token_id is not None and
|
| 199 |
+
processed["input_ids"][-1] != self.eos_token_id):
|
| 200 |
+
processed["input_ids"] = processed["input_ids"] + [self.eos_token_id]
|
| 201 |
+
processed["attention_mask"] = processed["attention_mask"] + [1]
|
| 202 |
+
return processed
|
| 203 |
+
|
| 204 |
+
# Handle list of text dictionaries
|
| 205 |
+
all_processed = []
|
| 206 |
+
all_texts = ''
|
| 207 |
+
example_inds = []
|
| 208 |
+
dataset_inds = []
|
| 209 |
+
|
| 210 |
+
for i, item in enumerate(texts):
|
| 211 |
+
processed = self(text=item["text"])
|
| 212 |
+
|
| 213 |
+
# Remove BOS token from all but first item
|
| 214 |
+
if i != 0 and self.bos_token_id == processed["input_ids"][0]:
|
| 215 |
+
processed["input_ids"] = processed["input_ids"][1:]
|
| 216 |
+
processed["attention_mask"] = processed["attention_mask"][1:]
|
| 217 |
+
|
| 218 |
+
# Remove EOS token if present at the end
|
| 219 |
+
if processed["input_ids"][-1] == self.eos_token_id:
|
| 220 |
+
processed["input_ids"] = processed["input_ids"][:-1]
|
| 221 |
+
processed["attention_mask"] = processed["attention_mask"][:-1]
|
| 222 |
+
|
| 223 |
+
# Check for EOS token in the middle (with special handling for <|im_end|>)
|
| 224 |
+
if self.eos_token_id in processed["input_ids"]:
|
| 225 |
+
if not self.decode([self.eos_token_id]) == "<|im_end|>":
|
| 226 |
+
raise ValueError(f"EOS token is present in input_ids: {processed['input_ids']}. Not currently supported.")
|
| 227 |
+
|
| 228 |
+
# Set labels based on compute_loss flag
|
| 229 |
+
if item["compute_loss"]:
|
| 230 |
+
processed["labels"] = processed["input_ids"].copy()
|
| 231 |
+
else:
|
| 232 |
+
processed["labels"] = [-100] * len(processed["input_ids"])
|
| 233 |
+
|
| 234 |
+
# Remove duplicate BOS tokens
|
| 235 |
+
if all_processed:
|
| 236 |
+
if processed["input_ids"][0] == self.bos_token_id:
|
| 237 |
+
processed["input_ids"] = processed["input_ids"][1:]
|
| 238 |
+
processed["attention_mask"] = processed["attention_mask"][1:]
|
| 239 |
+
processed["labels"] = processed["labels"][1:]
|
| 240 |
+
|
| 241 |
+
all_processed.append(processed)
|
| 242 |
+
all_texts += item["text"]
|
| 243 |
+
|
| 244 |
+
# Handle example indices
|
| 245 |
+
this_num = -1
|
| 246 |
+
if 'example_ind' in item.keys():
|
| 247 |
+
if item["example_ind"] is not None:
|
| 248 |
+
this_num = item["example_ind"]
|
| 249 |
+
example_inds.extend([this_num] * len(processed["input_ids"]))
|
| 250 |
+
|
| 251 |
+
# Handle dataset indices
|
| 252 |
+
dataset_ind = -1
|
| 253 |
+
if "data_id" in item.keys():
|
| 254 |
+
if item["data_id"] is not None:
|
| 255 |
+
dataset_ind = item["data_id"]
|
| 256 |
+
dataset_inds.extend([dataset_ind] * len(processed["input_ids"]))
|
| 257 |
+
|
| 258 |
+
# Combine all processed results
|
| 259 |
+
processed = all_processed[0].copy()
|
| 260 |
+
processed["input_ids"] = [item for sublist in [p["input_ids"] for p in all_processed] for item in sublist]
|
| 261 |
+
processed["attention_mask"] = [item for sublist in [p["attention_mask"] for p in all_processed] for item in sublist]
|
| 262 |
+
processed["labels"] = [item for sublist in [p["labels"] for p in all_processed] for item in sublist]
|
| 263 |
+
processed["example_inds"] = example_inds
|
| 264 |
+
processed["data_ids"] = dataset_inds
|
| 265 |
+
|
| 266 |
+
# Validate by tokenizing all_texts at once and comparing
|
| 267 |
+
processed_all = self(text=all_texts)
|
| 268 |
+
if len(processed_all["input_ids"]) != len(processed["input_ids"]):
|
| 269 |
+
warnings.warn(f"All texts are not the same length as the first text. Please check your dataset. {len(processed_all['input_ids'])} != {len(processed['input_ids'])}")
|
| 270 |
+
|
| 271 |
+
# Generate diff for debugging
|
| 272 |
+
all_text = self.decode(processed_all["input_ids"], skip_special_tokens=False)
|
| 273 |
+
processed_text = self.decode(processed["input_ids"], skip_special_tokens=False)
|
| 274 |
+
|
| 275 |
+
diff = difflib.unified_diff(all_text.splitlines(), processed_text.splitlines())
|
| 276 |
+
diff_str = "\n".join(diff)
|
| 277 |
+
print("Diff between texts:")
|
| 278 |
+
print(diff_str)
|
| 279 |
+
|
| 280 |
+
# Token diff
|
| 281 |
+
all_tokens_str = '\n'.join([str(s) for s in processed_all["input_ids"]])
|
| 282 |
+
processed_tokens_str = '\n'.join([str(s) for s in processed["input_ids"]])
|
| 283 |
+
token_diff = difflib.unified_diff(all_tokens_str.splitlines(), processed_tokens_str.splitlines())
|
| 284 |
+
token_diff_str = "\n".join(token_diff)
|
| 285 |
+
print("Diff between tokenized texts:")
|
| 286 |
+
print(token_diff_str)
|
| 287 |
+
|
| 288 |
+
# Add EOS token if needed
|
| 289 |
+
if (self.eos_token_id is not None and
|
| 290 |
+
processed["input_ids"][-1] != self.eos_token_id):
|
| 291 |
+
processed["input_ids"] = processed["input_ids"] + [self.eos_token_id]
|
| 292 |
+
processed["example_inds"] = processed["example_inds"] + [-1]
|
| 293 |
+
processed["attention_mask"] = processed["attention_mask"] + [1]
|
| 294 |
+
if processed["labels"] is not None:
|
| 295 |
+
if loss_on_eos:
|
| 296 |
+
processed["labels"] = processed["labels"] + [self.eos_token_id]
|
| 297 |
+
else:
|
| 298 |
+
processed["labels"] = processed["labels"] + [-100]
|
| 299 |
+
if "data_ids" in processed:
|
| 300 |
+
processed["data_ids"] = processed["data_ids"] + [-1]
|
| 301 |
+
|
| 302 |
+
if not include_eos:
|
| 303 |
+
# check if EOS token is present
|
| 304 |
+
if processed["input_ids"][-1] == self.eos_token_id:
|
| 305 |
+
# remove EOS token
|
| 306 |
+
processed["input_ids"] = processed["input_ids"][:-1]
|
| 307 |
+
processed["attention_mask"] = processed["attention_mask"][:-1]
|
| 308 |
+
processed["labels"] = processed["labels"][:-1]
|
| 309 |
+
processed["example_inds"] = processed["example_inds"][:-1]
|
| 310 |
+
processed["data_ids"] = processed["data_ids"][:-1]
|
| 311 |
+
|
| 312 |
+
return processed
|
| 313 |
+
|
| 314 |
+
def tokenize_messages(
|
| 315 |
+
self,
|
| 316 |
+
messages: List[Dict[str, Any]],
|
| 317 |
+
loss_on_start_token: bool = False,
|
| 318 |
+
loss_on_eos: bool = False,
|
| 319 |
+
include_eos: bool = True,
|
| 320 |
+
) -> Dict[str, Any]:
|
| 321 |
+
"""
|
| 322 |
+
Intended for tokenize from messages to tokenized texts with the loss applied.
|
| 323 |
+
"""
|
| 324 |
+
# First convert messages to text with loss computation flags
|
| 325 |
+
texts = self.messages_to_loss_texts(messages, loss_on_start_token)
|
| 326 |
+
|
| 327 |
+
# Then tokenize the texts
|
| 328 |
+
return self.tokenize_loss_texts(texts, loss_on_eos, include_eos = include_eos)
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
# Register tokenizer classes for AutoTokenizer
|
| 334 |
+
AutoTokenizer.register("GemmaExplicitTokenizer", slow_tokenizer_class=None, fast_tokenizer_class=GemmaExplicitTokenizer)
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
if __name__ == "__main__":
|
| 338 |
+
# Example usage
|
| 339 |
+
# for first load
|
| 340 |
+
custom_tokenizer = GemmaExplicitTokenizer.from_gemma_pretrained("google/gemma-3-1b-it")
|
| 341 |
+
|
| 342 |
+
# for subsequent loads
|
| 343 |
+
# custom_tokenizer = GemmaExplicitTokenizer.from_pretrained("tsor13/explicit-gemma-12b-pt")
|
| 344 |
+
# custom_tokenizer = GemmaExplicitTokenizer.from_pretrained("repos/explicit-gemma-12b-pt")
|
| 345 |
+
|
| 346 |
+
# Test messages in role/content format
|
| 347 |
+
messages = [
|
| 348 |
+
{"role": "description", "content": "This is a test task"},
|
| 349 |
+
{"role": "input", "content": "What is 2+2?"},
|
| 350 |
+
{"role": "output", "content": "4"},
|
| 351 |
+
{"role": "input", "content": "What is 3+3?"},
|
| 352 |
+
# {"role": "output", "content": "6"}
|
| 353 |
+
]
|
| 354 |
+
|
| 355 |
+
# get messages to text_loss
|
| 356 |
+
texts = custom_tokenizer.messages_to_loss_texts(messages)
|
| 357 |
+
print("Texts with loss flags:")
|
| 358 |
+
for i, text in enumerate(texts):
|
| 359 |
+
print(f" {i}: {text}")
|
| 360 |
+
|
| 361 |
+
text = custom_tokenizer.messages_to_text(messages, start_generation=True)
|
| 362 |
+
print(f"\nFull text with generation prompt:")
|
| 363 |
+
print(text)
|
| 364 |
+
|
| 365 |
+
print("\nTesting save/load cycle:")
|
| 366 |
+
# Test saving and loading
|
| 367 |
+
tokenizer_path = "repos/explicit-gemma-tokenizer"
|
| 368 |
+
custom_tokenizer.save_pretrained(tokenizer_path)
|
| 369 |
+
print("Tokenizer saved successfully!")
|
| 370 |
+
|
| 371 |
+
# also save this file in the tokenizer_path
|
| 372 |
+
import shutil
|
| 373 |
+
shutil.copy(__file__, os.path.join(tokenizer_path, "gemma_explicit_tokenizer.py"))
|
| 374 |
+
print("GemmaExplicitTokenizer.py saved successfully!")
|
model-00001-of-00005.safetensors
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
size 4979902192
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:542b2874d19bff3762d350e9c1bd370e50d80c5f709b80f1c7a443fc01849b20
|
| 3 |
size 4979902192
|
model-00002-of-00005.safetensors
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
size 4931296592
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b4ffcce1c51995b5dc648d237497030a2f779a4cd33761be3737393254886079
|
| 3 |
size 4931296592
|
model-00003-of-00005.safetensors
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
size 4931296656
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:092ae6527089321ed068b3103a101b768b3953bd4c43140bd82bdc423d0795cb
|
| 3 |
size 4931296656
|
model-00004-of-00005.safetensors
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
size 4931296656
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:422970ba53b0cb3fc42ddd8dc27077b25ee953c4d64df6861b35ee92a4529d6d
|
| 3 |
size 4931296656
|
model-00005-of-00005.safetensors
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
size 4601000928
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:71868eb31768e9d0d97fe9207f4abb09a9332e565552cfc762a5b9d0dd1b905f
|
| 3 |
size 4601000928
|
tokenizer_config.json
CHANGED
|
@@ -51325,8 +51325,9 @@
|
|
| 51325 |
},
|
| 51326 |
"boi_token": "<start_of_image>",
|
| 51327 |
"bos_token": "<bos>",
|
|
|
|
| 51328 |
"clean_up_tokenization_spaces": false,
|
| 51329 |
-
"end_string":
|
| 51330 |
"eoi_token": "<end_of_image>",
|
| 51331 |
"eos_token": "<eos>",
|
| 51332 |
"extra_special_tokens": {
|
|
@@ -51337,16 +51338,17 @@
|
|
| 51337 |
"image_token": "<image_soft_token>",
|
| 51338 |
"model_max_length": 1000000000000000019884624838656,
|
| 51339 |
"pad_token": "<pad>",
|
|
|
|
| 51340 |
"sp_model_kwargs": null,
|
| 51341 |
"spaces_between_special_tokens": false,
|
| 51342 |
-
"start_string":
|
| 51343 |
-
"tokenizer_class": "
|
| 51344 |
"unk_token": "<unk>",
|
| 51345 |
"use_default_system_prompt": false,
|
| 51346 |
"auto_map": {
|
| 51347 |
"AutoTokenizer": [
|
| 51348 |
-
"
|
| 51349 |
-
"
|
| 51350 |
]
|
| 51351 |
}
|
| 51352 |
}
|
|
|
|
| 51325 |
},
|
| 51326 |
"boi_token": "<start_of_image>",
|
| 51327 |
"bos_token": "<bos>",
|
| 51328 |
+
"chat_template": "{{ bos_token }}\n{%- if messages[0]['role'] == 'system' -%}\n {%- if messages[0]['content'] is string -%}\n {%- set first_user_prefix = messages[0]['content'] + '\n\n' -%}\n {%- else -%}\n {%- set first_user_prefix = messages[0]['content'][0]['text'] + '\n\n' -%}\n {%- endif -%}\n {%- set loop_messages = messages[1:] -%}\n{%- else -%}\n {%- set first_user_prefix = \"\" -%}\n {%- set loop_messages = messages -%}\n{%- endif -%}\n{%- for message in loop_messages -%}\n {%- if (message['role'] == 'user') != (loop.index0 % 2 == 0) -%}\n {{ raise_exception(\"Conversation roles must alternate user/assistant/user/assistant/...\") }}\n {%- endif -%}\n {%- if (message['role'] == 'assistant') -%}\n {%- set role = \"model\" -%}\n {%- else -%}\n {%- set role = message['role'] -%}\n {%- endif -%}\n {{ '<start_of_turn>' + role + '\n' + (first_user_prefix if loop.first else \"\") }}\n {%- if message['content'] is string -%}\n {{ message['content'] | trim }}\n {%- elif message['content'] is iterable -%}\n {%- for item in message['content'] -%}\n {%- if item['type'] == 'image' -%}\n {{ '<start_of_image>' }}\n {%- elif item['type'] == 'text' -%}\n {{ item['text'] | trim }}\n {%- endif -%}\n {%- endfor -%}\n {%- else -%}\n {{ raise_exception(\"Invalid content type\") }}\n {%- endif -%}\n {{ '<end_of_turn>\n' }}\n{%- endfor -%}\n{%- if add_generation_prompt -%}\n {{'<start_of_turn>model\n'}}\n{%- endif -%}\n",
|
| 51329 |
"clean_up_tokenization_spaces": false,
|
| 51330 |
+
"end_string": null,
|
| 51331 |
"eoi_token": "<end_of_image>",
|
| 51332 |
"eos_token": "<eos>",
|
| 51333 |
"extra_special_tokens": {
|
|
|
|
| 51338 |
"image_token": "<image_soft_token>",
|
| 51339 |
"model_max_length": 1000000000000000019884624838656,
|
| 51340 |
"pad_token": "<pad>",
|
| 51341 |
+
"processor_class": "Gemma3Processor",
|
| 51342 |
"sp_model_kwargs": null,
|
| 51343 |
"spaces_between_special_tokens": false,
|
| 51344 |
+
"start_string": null,
|
| 51345 |
+
"tokenizer_class": "GemmaExplicitTokenizer",
|
| 51346 |
"unk_token": "<unk>",
|
| 51347 |
"use_default_system_prompt": false,
|
| 51348 |
"auto_map": {
|
| 51349 |
"AutoTokenizer": [
|
| 51350 |
+
"gemma_explicit_tokenizer.GemmaExplicitTokenizer",
|
| 51351 |
+
"gemma_explicit_tokenizer.GemmaExplicitTokenizer"
|
| 51352 |
]
|
| 51353 |
}
|
| 51354 |
}
|
training_args.bin
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
size 7377
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e4b89185f26b9cbdf0d6a835b8d4fb2bf8c6584347553dcaa366582ca993a82c
|
| 3 |
size 7377
|