Skip to content

Commit ab85b2a

Browse files
dbortvmpuri
andauthored
Refactor generate.py for modularity (#906) (#918)
This PR refactors the chat function in generate.py by creating a `Generator` class, removing unnecessary global variables and simplifying the code structure. Tokens and metrics are now yielded by the Generator rather than being printed directly to stdout, making it easier to re-use this code for non-CLI tools. **Tests:** Generate ``` python3 torchchat.py generate stories15M --prompt "Once upon a time," Using device=mps Loading model... Time to load model: 0.46 seconds ----------------------------------------------------------- Once upon a time, there was a little girl named Lily. One day, she went to the park with her mom. They saw a big tree with lots of pears on it. Lily wanted to eat a pear, but they were too high up. She tried to jump, but she couldn't reach them. Then, a boy came and took a pear from the tree. Lily was surprised! She thought the boy would be mean, but he was harmless and didn't mean to hurt her. She asked him if she could have a pear too. The boy said yes and gave her a pear. Lily was very happy and thanked the boy for sharing. They sat under the tree and ate the pear together. It was a good day at the park. Once upon a time, there was a little girl named Lily. She loved to play in the garden with her mommy. One day, they were planting some Time for inference 1: 3.55 sec total, time to first token 0.00 sec with parallel prefill, 199 tokens, 56.01 tokens/sec, 17.85 ms/token Bandwidth achieved: 2.73 GB/s *** This first iteration will include cold start effects for dynamic import, hardware caches. *** ======================================== Average tokens/sec: 56.01 ======================================== Average tokens/sec: 119.35 Memory used: 0.00 GB ``` Eval ``` python3 torchchat.py eval stories15M --tasks wikitext --limit 10 NumExpr defaulting to 10 threads. PyTorch version 2.5.0.dev20240629 available. Using device=mps Loading model... Time to load model: 0.38 seconds ----------------------------------------------------------- Using device 'mps' [Task: wikitext] metric word_perplexity is defined, but aggregation is not. using default aggregation=weighted_perplexity [Task: wikitext] metric word_perplexity is defined, but higher_is_better is not. using default higher_is_better=False [Task: wikitext] metric byte_perplexity is defined, but aggregation is not. using default aggregation=weighted_perplexity [Task: wikitext] metric byte_perplexity is defined, but higher_is_better is not. using default higher_is_better=False [Task: wikitext] metric bits_per_byte is defined, but aggregation is not. using default aggregation=bits_per_byte [Task: wikitext] metric bits_per_byte is defined, but higher_is_better is not. using default higher_is_better=False Repo card metadata block was not found. Setting CardData to empty. Repo card metadata block was not found. Setting CardData to empty. Building contexts for wikitext on rank 0... 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 10/10 [00:00<00:00, 541.59it/s] Running loglikelihood_rolling requests 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 10/10 [00:04<00:00, 2.25it/s] Time to run eval: 22.57s. Time in model.forward: 1.01s, over 33 model evaluations forward run time stats - Median: 0.02s Min: 0.01s Max: 0.27s For model /Users/puri/.torchchat/model-cache/stories15M/stories15M.pt wikitext: word_perplexity,none: 47350.8811 byte_perplexity,none: 7.7811 bits_per_byte,none: 2.9600 alias: wikitext ``` Co-authored-by: vmpuri <[email protected]>
1 parent e1914fa commit ab85b2a

File tree

3 files changed

+717
-629
lines changed

3 files changed

+717
-629
lines changed

eval.py

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@
44
# This source code is licensed under the license found in the
55
# LICENSE file in the root directory of this source tree.
66
import argparse
7-
import time
8-
from typing import Optional
7+
from typing import Callable, Optional
98

109
import torch
1110
import torch._dynamo.config
@@ -20,7 +19,6 @@
2019
from build.model import Transformer
2120
from build.utils import set_precision
2221
from cli import add_arguments_for_verb, arg_init
23-
from generate import encode_tokens, model_forward
2422
from utils.measure_time import measure_time
2523

2624
torch._dynamo.config.automatic_dynamic_shapes = True
@@ -85,11 +83,17 @@ def __init__(
8583
self,
8684
model: Transformer,
8785
tokenizer,
86+
model_forward: Optional[Callable] = None,
8887
max_seq_length: Optional[int] = None,
8988
device="cpu",
9089
):
9190
super().__init__(device=device)
9291
self._model = model
92+
self._model_forward = (
93+
model_forward
94+
if model_forward is not None
95+
else lambda x, input_pos: model(x, input_pos)
96+
)
9397
self._tokenizer = tokenizer
9498
self._device = torch.device(device)
9599
self._max_seq_length = 2048 if max_seq_length is None else max_seq_length
@@ -116,11 +120,8 @@ def device(self):
116120
return self._device
117121

118122
def tok_encode(self, string: str, **kwargs):
119-
encoded = encode_tokens(self._tokenizer, string, bos=True, device=self._device)
120-
# encoded is a pytorch tensor, but some internal logic in the
121-
# eval harness expects it to be a list instead
122-
# TODO: verify this for multi-batch as well
123-
encoded = encoded.tolist()
123+
bos_id = self._tokenizer.bos_id()
124+
encoded = [bos_id] + self._tokenizer.encode(string)
124125
return encoded
125126

126127
def tok_decode(self, tokens):
@@ -142,7 +143,7 @@ def _model_call(self, inps):
142143
)
143144
x = seq.index_select(0, input_pos).view(1, -1)
144145
with measure_time(message=None) as measure:
145-
logits = model_forward(self._model, x, input_pos)
146+
logits = self._model_forward(x, input_pos)
146147
self.times.append(measure.get_time())
147148
return logits
148149

@@ -153,6 +154,7 @@ def _model_generate(self, context, max_length, eos_token_id):
153154
@torch.no_grad()
154155
def eval(
155156
model: Transformer,
157+
model_forward: Callable,
156158
tokenizer,
157159
tasks: Optional[list] = None,
158160
limit: Optional[int] = None,
@@ -176,7 +178,11 @@ def eval(
176178
tasks = ["wikitext"]
177179

178180
model_eval_wrapper = GPTFastEvalWrapper(
179-
model, tokenizer, max_seq_length, device=device
181+
model,
182+
tokenizer,
183+
model_forward=model_forward,
184+
max_seq_length=max_seq_length,
185+
device=device,
180186
)
181187

182188
try:
@@ -231,11 +237,12 @@ def main(args) -> None:
231237
)
232238
tokenizer_args.validate_model(model)
233239

240+
model_forward = lambda x, input_pos: model(x, input_pos) # noqa
241+
234242
if compile:
235243
assert not (
236244
builder_args.dso_path or builder_args.pte_path
237245
), "cannot compile exported model"
238-
global model_forward
239246
model_forward = torch.compile(
240247
model_forward, mode="reduce-overhead", dynamic=True, fullgraph=True
241248
)
@@ -244,6 +251,7 @@ def main(args) -> None:
244251
with measure_time("Time to run eval: {time:.02f}s."):
245252
result = eval(
246253
model.to(device),
254+
model_forward,
247255
tokenizer,
248256
tasks,
249257
limit,

0 commit comments

Comments
 (0)