5"""Evolve virtual tokens with an opt-in Transformers backend on CPU."""
10from dataclasses
import asdict
11from pathlib
import Path
21 """Use an embedding prefix followed by a fixed text prompt."""
23 def __init__(self, model, tokenizer, prompt, max_new_tokens):
24 self.
model = model.eval().requires_grad_(
False)
28 tokens = tokenizer(prompt, add_special_tokens=
False, return_tensors=
"pt").input_ids
32 """Repeat the vocabulary's mean embedding for the initial soft prompt."""
33 return self.
table.weight.detach().mean(dim=0).expand(virtual_tokens, -1).numpy().copy()
35 @torch.inference_mode()
37 """Sample a fixed-budget continuation using the supplied virtual tokens."""
38 prefix = torch.as_tensor(embedding, dtype=self.
table.weight.dtype)[
None, ...]
39 inputs = torch.cat((prefix, self.
context), dim=1)
40 limit = getattr(self.
model.config,
"max_position_embeddings",
None)
41 if limit
is not None and inputs.shape[1] + self.
max_new_tokens > limit:
42 raise ValueError(
"The virtual prefix, prompt and token budget exceed the model context.")
43 generator = torch.Generator(device=
"cpu").manual_seed(seed)
46 logits = self.
model(inputs_embeds=inputs, use_cache=
False).logits[0, -1].float()
47 token = torch.multinomial(logits.softmax(dim=-1), 1, generator=generator)
48 if token.item() == self.
tokenizer.eos_token_id:
50 token_ids.append(int(token.item()))
51 inputs = torch.cat((inputs, self.
table(token[
None, :])), dim=1)
52 return self.
tokenizer.decode(token_ids, skip_special_tokens=
True)
55def tiny_decoder(seed):
56 """Build a small randomly initialized GPT-2 with a local vocabulary."""
57 from tokenizers
import Tokenizer
58 from tokenizers.models
import WordLevel
59 from tokenizers.pre_tokenizers
import Whitespace
60 from transformers
import GPT2Config, GPT2LMHeadModel, PreTrainedTokenizerFast
62 words = (
"<pad>",
"<eos>",
"<unk>",
"Describe",
"a",
"journey",
"by",
"bus",
"train",
"walk",
63 "river",
"city",
"museum",
"morning",
"evening",
"short",
"long",
".")
64 vocabulary = {word: idx
for idx, word
in enumerate(words)}
65 backend = Tokenizer(WordLevel(vocabulary, unk_token=
"<unk>"))
66 backend.pre_tokenizer = Whitespace()
67 tokenizer = PreTrainedTokenizerFast(tokenizer_object=backend, unk_token=
"<unk>",
68 pad_token=
"<pad>", eos_token=
"<eos>")
69 config = GPT2Config(vocab_size=len(words), n_positions=64, n_embd=24, n_layer=1, n_head=2,
70 pad_token_id=tokenizer.pad_token_id, eos_token_id=tokenizer.eos_token_id)
71 with torch.random.fork_rng(devices=[]):
72 torch.random.default_generator.manual_seed(seed)
73 model = GPT2LMHeadModel(config)
74 return model, tokenizer
77def evaluate_completion(text):
78 """Score travel vocabulary and measure length and lexical diversity."""
79 tokens = re.findall(
r"\b\w+\b", text.casefold())
82 travel_words = {
"journey",
"bus",
"train",
"walk",
"river",
"city",
"museum"}
83 quality = len(travel_words.intersection(tokens)) / len(travel_words)
84 return quality, (min(1., len(tokens) / 12.), len(set(tokens)) / len(tokens))
88 """Compare frozen-model variation modes with equal generation calls."""
89 parser = argparse.ArgumentParser(description=__doc__)
90 parser.add_argument(
"--model", type=Path, help=
"Local checkpoint and tokenizer directory.")
91 parser.add_argument(
"--budget", type=int, default=24)
92 parser.add_argument(
"--tokens", type=int, default=12)
93 parser.add_argument(
"--seed", type=int, default=11)
94 args = parser.parse_args()
95 if args.budget < 1
or args.tokens < 1:
96 parser.error(
"Budget and tokens must be positive.")
97 torch.set_num_threads(1)
98 if args.model
is None:
99 model, tokenizer = tiny_decoder(args.seed)
101 from transformers
import AutoModelForCausalLM, AutoTokenizer
103 model = AutoModelForCausalLM.from_pretrained(args.model, local_files_only=
True)
104 tokenizer = AutoTokenizer.from_pretrained(args.model, local_files_only=
True)
105 decoder =
FrozenDecoder(model, tokenizer,
"Describe a journey by", args.tokens)
106 initial = decoder.initial_embedding(2)
107 for mode
in (
"targeted",
"gaussian",
"fixed"):
108 archive =
Grid(shape=(4, 4), features_domain=((0., 1.),) * 2,
109 fitness_domain=((0., 1.),), fitness_weights=(1.,))
110 search =
SoftPromptMAPElites(archive, initial, sigma=.05, probe_step=.1, probe_directions=2,
112 search.run(decoder, evaluate_completion, budget=args.budget, mode=mode)
113 print(json.dumps({
"mode": mode,
"cells": len(archive),
"qd": archive.qd_score(), **asdict(search.stats)}))
116if __name__ ==
"__main__":
Evolve soft prompts using Gaussian, crossover, and descriptor-guided mutations.
Decode from actual input embeddings with a private generation RNG.
__call__(self, embedding, seed)
initial_embedding(self, virtual_tokens)