Andrej Karpathy Claude Fable 5 commited on
Commit
ca366eb
·
1 Parent(s): e02b339

allocate the inference KV cache in COMPUTE_DTYPE instead of hardcoding cuda->bf16, fixing bf16 inference (e.g. NANOCHAT_DTYPE=bfloat16 on MPS) and deleting an old hack. Thank you @mparrett #795

Browse files
Files changed (1) hide show
  1. nanochat/engine.py +3 -8
nanochat/engine.py CHANGED
@@ -17,7 +17,7 @@ import signal
17
  import warnings
18
  from contextlib import contextmanager
19
  from collections import deque
20
- from nanochat.common import compute_init, autodetect_device_type
21
  from nanochat.checkpoint_manager import load_model
22
 
23
  # -----------------------------------------------------------------------------
@@ -177,13 +177,8 @@ class Engine:
177
  """Same as generate, but does single prefill and then clones the KV cache."""
178
  assert isinstance(tokens, list) and isinstance(tokens[0], int), "expecting list of ints"
179
  device = self.model.get_device()
180
- # NOTE: setting the dtype here and in this way is an ugly hack.
181
- # Currently the repo assumes that cuda -> bfloat16 and everything else -> float32.
182
- # We need to know the dtype here to call __init__ on KVCache and pre-allocate its tensors.
183
- # As a quick hack, we're making generate() function inherit and know about this repo-wise assumption.
184
- # I think there has to be a bigger refactor to deal with device/dtype tracking across the codebase.
185
- # In particular, the KVCache should allocate its tensors lazily
186
- dtype = torch.bfloat16 if device.type == "cuda" else torch.float32
187
  rng = torch.Generator(device=device)
188
  rng.manual_seed(seed)
189
 
 
17
  import warnings
18
  from contextlib import contextmanager
19
  from collections import deque
20
+ from nanochat.common import compute_init, autodetect_device_type, COMPUTE_DTYPE
21
  from nanochat.checkpoint_manager import load_model
22
 
23
  # -----------------------------------------------------------------------------
 
177
  """Same as generate, but does single prefill and then clones the KV cache."""
178
  assert isinstance(tokens, list) and isinstance(tokens[0], int), "expecting list of ints"
179
  device = self.model.get_device()
180
+ # Allocate the KV cache in the compute dtype so it matches what the forward pass emits
181
+ dtype = COMPUTE_DTYPE
 
 
 
 
 
182
  rng = torch.Generator(device=device)
183
  rng.manual_seed(seed)
184