herb-150m / lean_sequence.py
ericlewis's picture
Publish Herb-150M (hf_stage_herb_main) to main
53b8f3b verified
Raw History Blame Contribute Delete
7.16 kB
"""A shorter token sequence for decision models that read spans on an encoder (cosine_head.py).
from lean_sequence import use_lean_sequence
use_lean_sequence(tokenizer) # before build_dataset; from_pretrained(..., sequence="lean") does it
Clef writes every record as a chat for a language model: a system turn, headers, field and option labels and an
assistant turn. A span head on an encoder reads none of that. The lean sequence keeps the state, each question's
text and each option, and nothing else:
state <sep> question <sep> option <sep> option ... (<sep> question <sep> option ... for more questions)
It is cut out of Clef's own encoding, token for token: the state, the question text and the options are exactly
the tokens Clef writes (an option is still its JSON, with description and option_id), and the record keeps Clef's
structure with its spans moved. So the head, the collators, the trainers, evaluate and predict work unchanged.
A row of ours that takes 419 tokens in Clef's sequence takes 295.
The choice travels with the tokenizer: only records encoded with a tokenizer that use_lean_sequence marked are
lean. A model trained on lean records has decision_config["sequence"] == "lean" and must be given a marked
tokenizer whenever it is used; encoder_decision.py does that when it loads one.
DataLoader workers have to be forked (the default on Linux up to Python 3.13) or run this module's install():
a process that never ran it writes Clef's sequence. packed_decision_trainer.py's collator runs it.
"""
import dataclasses
LEAN, LEAN_START = "lean", "lean-start" # "lean-start" puts the tokenizer's bos token first
STATE_HEADER, SCHEMA_HEADER = "STATE:\n", "\n\nSCHEMA FIELDS:" # what Clef writes before and after the state
NO_LIMIT = 1 << 30
def plain(tokenizer):
"""The tokenizer itself, out of Unsloth's _MemoTokenizer or a processor."""
return getattr(tokenizer, "tokenizer", tokenizer)
def markers(tokenizer):
"""(the tokens of Clef's header before the state, of its header after the state, the separator token)."""
found = getattr(tokenizer, "_lean_markers", None)
if found is None:
def tokens(text):
return tuple(tokenizer(text, add_special_tokens=False).input_ids)
separator = tokenizer.sep_token_id
if separator is None:
newline = tokens("\n")
if len(newline) != 1:
raise ValueError("The lean sequence needs a tokenizer with a sep_token, or with one token for a newline.")
separator = newline[0]
found = tokenizer._lean_markers = (tokens(STATE_HEADER), tokens(SCHEMA_HEADER), separator)
return found
def _find(ids, pattern, start, stop, last=False):
# Where `pattern` starts in ids[start:stop]: the first place, or the last.
width = len(pattern)
places = range(stop - width, start - 1, -1) if last else range(start, stop - width + 1)
for place in places:
if ids[place] == pattern[0] and ids[place:place + width] == pattern:
return place
return None
def encode_lean_record(encode, tokenizer, record, max_length=None, processor=None):
"""Clef's record for `record` with its sequence cut down to the state, the question texts and the options.
`encode` is Unsloth's encode_record. Over max_length the end of the state is cut, never a question or an option."""
full = encode(tokenizer, record, max_length=NO_LIMIT, processor=processor)
if getattr(full, "media", None):
raise ValueError("the lean sequence does not hold images")
ids = tuple(full.input_ids)
state_header, schema_header, separator = markers(plain(tokenizer))
first = min(question.question_span[0] for question in full.questions)
start = _find(ids, state_header, 0, first)
stop = None if start is None else _find(ids, schema_header, start, first, last=True)
if stop is None:
raise RuntimeError("The lean sequence did not find 'STATE:' and 'SCHEMA FIELDS:' in Clef's encoding of a "
"record, so that encoding is not the one it was written for.")
start += len(state_header)
real = plain(tokenizer)
first_token = [real.bos_token_id] if getattr(real, "decision_sequence", None) == LEAN_START else []
kept = len(first_token) + sum(1 + b - a for question in full.questions for a, b in (question.question_span, *question.option_spans))
room = stop - start if max_length is None else min(stop - start, max_length - kept)
if room < 0:
raise ValueError(f"its questions and options take {kept} tokens, more than max_length = {max_length}")
out, questions = first_token + list(ids[start:start + room]), []
for question in full.questions:
spans = []
for a, b in (question.question_span, *question.option_spans):
out.append(separator)
spans.append((len(out), len(out) + b - a))
out.extend(ids[a:b])
questions.append(dataclasses.replace(question, question_span=spans[0], option_spans=tuple(spans[1:])))
return dataclasses.replace(full, input_ids=type(full.input_ids)(out), questions=type(full.questions)(questions))
def install():
"""Put the lean encoder in front of Unsloth's encode_record, which build_dataset, the collator's field
permutation and predict all call. It acts only for a tokenizer that use_lean_sequence marked."""
from unsloth.models import clef
clef_encode = clef.encode_record
if getattr(clef_encode, "clef_encode_record", None) is not None:
return
def encode_record(tokenizer, record, *args, **kwargs):
if getattr(plain(tokenizer), "decision_sequence", None) not in (LEAN, LEAN_START):
return clef_encode(tokenizer, record, *args, **kwargs)
return encode_lean_record(clef_encode, tokenizer, record, *args, **kwargs)
encode_record.clef_encode_record = clef_encode
clef.encode_record = encode_record
def use_lean_sequence(tokenizer, start=False):
"""Mark a tokenizer: records encoded with it are lean from now on. Returns the tokenizer.
`start` puts the tokenizer's bos token first, where an embedding model built on the encoder pools."""
install()
real = plain(tokenizer)
markers(real) # a tokenizer that cannot do it fails here, not in the middle of a build
if start and real.bos_token_id is None:
raise ValueError("The lean sequence with a start token needs a tokenizer with a bos_token.")
real.decision_sequence = LEAN_START if start else LEAN
return tokenizer
def describe(tokenizer, record):
"""A record's sequence as text and what each of its spans covers, for checking a layout by eye."""
real, ids = plain(tokenizer), list(record.input_ids)
lines = [f"{len(ids)} tokens: {real.decode(ids)}"]
for question in record.questions:
lines.append(f" question {question.question_id!r}: {real.decode(ids[slice(*question.question_span)])!r}")
for name, span in zip(question.option_ids, question.option_spans):
lines.append(f" option {name!r}: {real.decode(ids[slice(*span)])!r}")
return "\n".join(lines)