inference.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. from pathlib import Path
  2. import json
  3. import os
  4. from exo.inference.tinygrad.models.llama import Transformer, convert_from_huggingface, fix_bf16
  5. from exo.inference.shard import Shard
  6. from exo.inference.tokenizers import resolve_tokenizer
  7. from tinygrad.nn.state import safe_load, torch_load, load_state_dict
  8. from tinygrad import Tensor, dtypes, nn, Context
  9. from transformers import AutoTokenizer
  10. from exo.inference.inference_engine import InferenceEngine
  11. from typing import Optional, Tuple
  12. import numpy as np
  13. from exo.inference.tinygrad.tinygrad_helpers import concat_weights, load
  14. from exo.download.shard_download import ShardDownloader
  15. from concurrent.futures import ThreadPoolExecutor
  16. import asyncio
  17. import threading
  18. from functools import partial
  19. Tensor.no_grad = True
  20. # default settings
  21. TEMPERATURE = int(os.getenv("TEMPERATURE", 0.85))
  22. TOP_K = 25
  23. TOP_P = 0.9
  24. ALPHA_F = 0.1
  25. ALPHA_P = 0.0
  26. MODEL_PARAMS = {
  27. "8B": {"args": {"dim": 4096, "n_heads": 32, "n_kv_heads": 8, "n_layers": 32, "norm_eps": 1e-5, "rope_theta": 500000, "vocab_size": 128256, "hidden_dim": 14336}, "files": 1},
  28. "70B": {"args": {"dim": 8192, "n_heads": 64, "n_kv_heads": 8, "n_layers": 80, "norm_eps": 1e-5, "rope_theta": 500000, "vocab_size": 128256, "hidden_dim": 28672}, "files": 8}
  29. }
  30. def build_transformer(model_path: Path, shard: Shard, model_size="8B", device=None):
  31. # build model
  32. linear = nn.Linear
  33. with Context(THREEFRY=0):
  34. model = Transformer(**MODEL_PARAMS[model_size]["args"], linear=linear, max_context=8192, jit=True, shard=shard)
  35. # load weights
  36. if model_path.is_dir():
  37. if (model_path/"model.safetensors.index.json").exists(): weights = load(str(model_path/"model.safetensors.index.json"), shard)
  38. elif (model_path/"model.safetensors").exists(): weights = load(str(model_path/"model.safetensors"), shard)
  39. else: weights = concat_weights([load(str(model_path/f"consolidated.{i:02d}.pth"), shard) for i in range(MODEL_PARAMS[model_size]["files"])], device[0] if isinstance(device, tuple) else device)
  40. else:
  41. weights = load(str(model_path), shard)
  42. weights = convert_from_huggingface(weights, model, MODEL_PARAMS[model_size]["args"]["n_heads"], MODEL_PARAMS[model_size]["args"]["n_kv_heads"])
  43. weights = fix_bf16(weights)
  44. with Context(BEAM=0):
  45. # replace weights in model
  46. load_state_dict(model, weights, strict=False, consume=False) # consume=True
  47. return model
  48. class TinygradDynamicShardInferenceEngine(InferenceEngine):
  49. def __init__(self, shard_downloader: ShardDownloader):
  50. self.shard = None
  51. self.shard_downloader = shard_downloader
  52. self.executor = ThreadPoolExecutor(max_workers=1)
  53. async def infer_prompt(self, request_id: str, shard: Shard, prompt: str, image_str: Optional[str] = None, inference_state: Optional[str] = None) -> (np.ndarray, str, bool):
  54. await self.ensure_shard(shard)
  55. start_pos = json.loads(inference_state or "{}").get("start_pos", 0)
  56. n_captured_toks = json.loads(inference_state or "{}").get("n_captured_toks", 0)
  57. toks = await asyncio.get_event_loop().run_in_executor(self.executor, self.tokenizer.encode, prompt)
  58. h = await asyncio.get_event_loop().run_in_executor(self.executor, lambda: self.model(Tensor([toks]), start_pos, TEMPERATURE).realize())
  59. if h.shape == (1,):
  60. start_pos += len(toks)
  61. start_pos += 1
  62. n_captured_toks = 0
  63. return np.array([[h.item()]]), json.dumps({"start_pos": start_pos, "n_captured_toks": n_captured_toks}), h.item() == self.tokenizer.eos_token_id
  64. else:
  65. n_captured_toks = len(toks)
  66. return h.numpy(), json.dumps({"start_pos": start_pos, "n_captured_toks": n_captured_toks}), False
  67. async def infer_tensor(self, request_id: str, shard: Shard, input_data: np.ndarray, inference_state: Optional[str] = None) -> Tuple[np.ndarray, str, bool]:
  68. await self.ensure_shard(shard)
  69. start_pos = json.loads(inference_state or "{}").get("start_pos", 0)
  70. n_captured_toks = json.loads(inference_state or "{}").get("n_captured_toks", 0)
  71. h = await asyncio.get_event_loop().run_in_executor(self.executor, lambda: self.model(Tensor(input_data), start_pos, TEMPERATURE).realize())
  72. if h.shape == (1,):
  73. start_pos += n_captured_toks
  74. start_pos += 1
  75. n_captured_toks = 0
  76. return np.array([[h.item()]]), json.dumps({"start_pos": start_pos, "n_captured_toks": n_captured_toks}), h.item() == self.tokenizer.eos_token_id
  77. else:
  78. return h.numpy(), json.dumps({"start_pos": start_pos, "n_captured_toks": n_captured_toks}), False
  79. async def ensure_shard(self, shard: Shard):
  80. if self.shard == shard:
  81. return
  82. model_path = await self.shard_downloader.ensure_shard(shard)
  83. if self.shard != shard:
  84. self.model = await asyncio.get_event_loop().run_in_executor(self.executor, build_transformer, model_path, shard, "8B" if "8b" in shard.model_id.lower() else "70B")
  85. tokenizer_path = str((model_path if model_path.is_dir() else model_path.parent))
  86. self.tokenizer = await resolve_tokenizer(tokenizer_path)
  87. self.shard = shard