Upload folder using huggingface_hub
Browse files- .DS_Store +0 -0
- README +62 -0
- chat.py +1563 -0
- llama32_part1_lut4.mlmodelc.zip +3 -0
- llama32_part2Q1S_lut4.mlmodelc.zip +3 -0
- llama32_part2Q2S_lut4.mlmodelc.zip +3 -0
- llama32_part2Q3S_lut4.mlmodelc.zip +3 -0
- llama32_part2Q4S_lut4.mlmodelc.zip +3 -0
- llama32_part3_lut4.mlmodelc.zip +3 -0
- tokenizer.json +0 -0
- tokenizer_config.json +35 -0
.DS_Store
ADDED
|
Binary file (6.15 kB). View file
|
|
|
README
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
ANEMLL
|
| 2 |
+
|
| 3 |
+
ANEMLL (pronounced like “animal”) is an open-source project
|
| 4 |
+
focused on accelerating the porting of Large Language Models (LLMs)
|
| 5 |
+
to tensor processors, starting with the Apple Neural Engine (ANE).
|
| 6 |
+
|
| 7 |
+
The goal is to provide a fully open-source pipeline
|
| 8 |
+
from model conversion to inference for common LLM architectures
|
| 9 |
+
running on ANE.
|
| 10 |
+
|
| 11 |
+
This enables seamless integration and on-device inference
|
| 12 |
+
for low-power applications on edge devices,
|
| 13 |
+
ensuring maximum privacy and security.
|
| 14 |
+
|
| 15 |
+
This is critical for autonomous applications,
|
| 16 |
+
where models run directly on the device
|
| 17 |
+
without requiring an internet connection.
|
| 18 |
+
|
| 19 |
+
License
|
| 20 |
+
|
| 21 |
+
ANEMLL is licensed under the MIT License.
|
| 22 |
+
https://opensource.org/license/mit
|
| 23 |
+
The model is based on Meta’s LLaMA 3.2 and may require a separate license.
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
This test model is exclusively for the DeepSeek R1 8B model converted for CoreML,
|
| 28 |
+
released before the official launch of the ANEMLL repository and minimal documentation.
|
| 29 |
+
It is intended for early adopters only who requested an early release.
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
Requirements
|
| 33 |
+
• macOS Sequoia with Apple Neural Engine and 16GB RAM
|
| 34 |
+
• CoreML Tools and HuggingFace Transformers libraries
|
| 35 |
+
• Python 3.9
|
| 36 |
+
|
| 37 |
+
chat.py provides a sample inference script.
|
| 38 |
+
We apologize for the current quality of chat.py and appreciate your patience.
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
Prerequisites:
|
| 42 |
+
pip install coremltools transformers
|
| 43 |
+
|
| 44 |
+
How to RUN:
|
| 45 |
+
python chat.py
|
| 46 |
+
|
| 47 |
+
Ctr-D to exit, Ctr-C to interrupt inference.
|
| 48 |
+
|
| 49 |
+
alternative way to run:
|
| 50 |
+
python chat.py Q123 -d /path/to/anemll-DeepSeek-8B-ctx1024 ctx=1024
|
| 51 |
+
|
| 52 |
+
The first time the model loads, macOS will take some time to place it on the device.
|
| 53 |
+
Subsequent loads will be instantaneous.
|
| 54 |
+
|
| 55 |
+
Please check following links for later updates:
|
| 56 |
+
https://huggingface.co/anemll
|
| 57 |
+
https://x.com/anemll
|
| 58 |
+
https://github.com/anemll
|
| 59 |
+
https://anemll.com
|
| 60 |
+
|
| 61 |
+
realanemll@gmail.com
|
| 62 |
+
|
chat.py
ADDED
|
@@ -0,0 +1,1563 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2025, Anemll All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Use of this source code is governed by a MIT license that can be
|
| 4 |
+
# found in the LICENSE.txt file or at https://opensource.org/license/mit
|
| 5 |
+
|
| 6 |
+
import coremltools as ct
|
| 7 |
+
import numpy as np
|
| 8 |
+
import torch
|
| 9 |
+
from transformers import AutoTokenizer
|
| 10 |
+
import os
|
| 11 |
+
import time, sys
|
| 12 |
+
import signal
|
| 13 |
+
import traceback
|
| 14 |
+
import torch.nn.functional as F
|
| 15 |
+
import queue
|
| 16 |
+
import threading
|
| 17 |
+
import re
|
| 18 |
+
|
| 19 |
+
# Configuration
|
| 20 |
+
CONTEXT_LENGTH = 1024 # Changed default from 512 to 1024
|
| 21 |
+
PREFILL_BATCH_SIZE = 64
|
| 22 |
+
MODEL_PATH = os.path.expanduser("../DeepSeekR1-8B")
|
| 23 |
+
ENABLE_VACAB_SPLIT8 = True # Enable 8-way vocab split
|
| 24 |
+
ENABLE_LOGITS2 = False # Enable 2-way vocab split
|
| 25 |
+
ENABLE_DEBUG = bool(0)
|
| 26 |
+
ENABLE_ARGMAX = bool(0)
|
| 27 |
+
ENABLE_PREFILL_BATCH = bool(1)
|
| 28 |
+
ENABLE_CHAT_DEBUG = bool(0) # Debug flag for chat loop
|
| 29 |
+
|
| 30 |
+
# ANSI color codes
|
| 31 |
+
LIGHT_BLUE = "\033[94m"
|
| 32 |
+
DARK_BLUE = "\033[34m"
|
| 33 |
+
LIGHT_GREEN = "\033[92m"
|
| 34 |
+
RESET_COLOR = "\033[0m"
|
| 35 |
+
|
| 36 |
+
if ENABLE_LOGITS2:
|
| 37 |
+
assert not ENABLE_ARGMAX, "ENABLE_ARGMAX must be False when ENABLE_LOGITS2 is True"
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def load_model(path, compute_unit=ct.ComputeUnit.CPU_AND_NE, function_name=None):
|
| 41 |
+
"""Load either compiled or uncompiled CoreML model.
|
| 42 |
+
|
| 43 |
+
Args:
|
| 44 |
+
path: Path to the model file (.mlmodelc or .mlpackage)
|
| 45 |
+
compute_unit: CoreML compute unit to use
|
| 46 |
+
function_name: Optional function name to select from multi-function models
|
| 47 |
+
"""
|
| 48 |
+
DebugLog(f"Attempting to load model: {path}")
|
| 49 |
+
DebugLog(f"File exists: {os.path.exists(path)}")
|
| 50 |
+
DebugLog(f"Is directory (for mlmodelc): {os.path.isdir(path)}")
|
| 51 |
+
|
| 52 |
+
try:
|
| 53 |
+
if path.endswith('.mlmodelc'):
|
| 54 |
+
DebugLog(f"Loading compiled model: {path}")
|
| 55 |
+
if function_name is None:
|
| 56 |
+
DebugLog("Loading without function name")
|
| 57 |
+
model = ct.models.CompiledMLModel(path, compute_unit)
|
| 58 |
+
else:
|
| 59 |
+
DebugLog(f"Loading with function name: {function_name}")
|
| 60 |
+
model = ct.models.CompiledMLModel(path, compute_unit, function_name=function_name)
|
| 61 |
+
else:
|
| 62 |
+
DebugLog(f"Loading uncompiled model: {path}")
|
| 63 |
+
if function_name is None:
|
| 64 |
+
DebugLog("Loading without function name")
|
| 65 |
+
model = ct.models.MLModel(model=path, compute_units=compute_unit, is_temp_package=False)
|
| 66 |
+
else:
|
| 67 |
+
DebugLog(f"Loading with function name: {function_name}")
|
| 68 |
+
model = ct.models.MLModel(model=path, compute_units=compute_unit, is_temp_package=False, function_name=function_name)
|
| 69 |
+
DebugLog("Model loaded successfully")
|
| 70 |
+
|
| 71 |
+
return model
|
| 72 |
+
|
| 73 |
+
except Exception as e:
|
| 74 |
+
DebugLog(f"Error loading model: {str(e)}")
|
| 75 |
+
DebugLog(f"Error type: {type(e)}")
|
| 76 |
+
raise
|
| 77 |
+
|
| 78 |
+
class SplitModelInference:
|
| 79 |
+
def __init__(self, model_parts, model_dir="."):
|
| 80 |
+
"""Initialize split model inference.
|
| 81 |
+
|
| 82 |
+
Args:
|
| 83 |
+
model_parts (list): List of model part numbers to load
|
| 84 |
+
Special cases:
|
| 85 |
+
- 'C123' for combined part2 with prefill/infer functions
|
| 86 |
+
- 'S123' for split model with prefill/infer functions
|
| 87 |
+
- 'Q123' for quad split (2Q1-2Q4)
|
| 88 |
+
- 'Q123S' for quad split with combined prefill/infer (2Q1S-2Q4S)
|
| 89 |
+
- '123D' for dual split without prefill/infer (2D1-2D2)
|
| 90 |
+
model_dir (str): Directory containing the model files (default: current directory)
|
| 91 |
+
"""
|
| 92 |
+
self.context_size = CONTEXT_LENGTH
|
| 93 |
+
self.model_dir = model_dir
|
| 94 |
+
DebugLog(f"Loading models from directory: {self.model_dir}")
|
| 95 |
+
|
| 96 |
+
# Parse configuration
|
| 97 |
+
self.quant_configs = {}
|
| 98 |
+
global_lut = None
|
| 99 |
+
if model_parts and model_parts[-1].startswith('lut'):
|
| 100 |
+
global_lut = model_parts[-1]
|
| 101 |
+
model_parts = model_parts[:-1]
|
| 102 |
+
|
| 103 |
+
# Special handling for different split modes
|
| 104 |
+
if len(model_parts) == 1:
|
| 105 |
+
if model_parts[0] == '123D': # Dual split without prefill/infer
|
| 106 |
+
self.use_combined_part2 = False
|
| 107 |
+
self.use_split_model = True
|
| 108 |
+
self.use_split_functions = False
|
| 109 |
+
self.use_quad_split = False
|
| 110 |
+
self.use_quad_split_combined = False
|
| 111 |
+
self.model_parts = ['1', '2D1', '2D2', '3']
|
| 112 |
+
if global_lut:
|
| 113 |
+
self.quant_configs = {part: global_lut for part in self.model_parts}
|
| 114 |
+
DebugLog(f"Using dual split model with parts: {self.model_parts}")
|
| 115 |
+
elif model_parts[0].startswith('C123'): # Combined part2
|
| 116 |
+
self.use_combined_part2 = True
|
| 117 |
+
self.use_split_model = False
|
| 118 |
+
self.use_split_functions = False
|
| 119 |
+
self.use_quad_split = False
|
| 120 |
+
self.use_quad_split_combined = False
|
| 121 |
+
self.model_parts = ['1', '2', '3']
|
| 122 |
+
if global_lut:
|
| 123 |
+
self.quant_configs = {part: global_lut for part in self.model_parts}
|
| 124 |
+
DebugLog(f"Using combined part2 model with parts: {self.model_parts}")
|
| 125 |
+
elif model_parts[0].startswith('S123'): # Split model with prefill/infer functions
|
| 126 |
+
self.use_combined_part2 = False
|
| 127 |
+
self.use_split_model = True
|
| 128 |
+
self.use_split_functions = True
|
| 129 |
+
self.use_quad_split = False
|
| 130 |
+
self.use_quad_split_combined = False
|
| 131 |
+
self.model_parts = ['1', '2D1S', '2D2S', '3']
|
| 132 |
+
elif model_parts[0].startswith('Q123S'): # Quad split with combined prefill/infer
|
| 133 |
+
self.use_combined_part2 = False
|
| 134 |
+
self.use_split_model = True
|
| 135 |
+
self.use_split_functions = False
|
| 136 |
+
self.use_quad_split = False
|
| 137 |
+
self.use_quad_split_combined = True
|
| 138 |
+
self.model_parts = ['1', '2Q1S', '2Q2S', '2Q3S', '2Q4S', '3']
|
| 139 |
+
elif model_parts[0].startswith('Q123'): # Regular quad split
|
| 140 |
+
self.use_combined_part2 = False
|
| 141 |
+
self.use_split_model = True
|
| 142 |
+
self.use_split_functions = False
|
| 143 |
+
self.use_quad_split = True
|
| 144 |
+
self.use_quad_split_combined = False
|
| 145 |
+
self.model_parts = ['1', '2Q1', '2Q2', '2Q3', '2Q4', '3']
|
| 146 |
+
else:
|
| 147 |
+
self.use_combined_part2 = False
|
| 148 |
+
self.use_split_model = False
|
| 149 |
+
self.use_split_functions = False
|
| 150 |
+
self.use_quad_split = False
|
| 151 |
+
self.use_quad_split_combined = False
|
| 152 |
+
self.model_parts = model_parts
|
| 153 |
+
else:
|
| 154 |
+
self.use_combined_part2 = False
|
| 155 |
+
self.use_split_model = False
|
| 156 |
+
self.use_split_functions = False
|
| 157 |
+
self.use_quad_split = False
|
| 158 |
+
self.use_quad_split_combined = False
|
| 159 |
+
self.model_parts = model_parts
|
| 160 |
+
|
| 161 |
+
# Apply global quantization if specified
|
| 162 |
+
if global_lut and not self.use_combined_part2: # Skip if already applied for C123
|
| 163 |
+
self.quant_configs = {part: global_lut for part in self.model_parts}
|
| 164 |
+
|
| 165 |
+
DebugLog(f"Using model parts: {self.model_parts}")
|
| 166 |
+
if global_lut:
|
| 167 |
+
DebugLog(f"With global quantization: {global_lut}")
|
| 168 |
+
if self.use_combined_part2:
|
| 169 |
+
DebugLog("Using combined part2 model with prefill/infer functions")
|
| 170 |
+
elif self.use_split_functions:
|
| 171 |
+
DebugLog("Using split model with prefill/infer functions")
|
| 172 |
+
elif self.use_quad_split:
|
| 173 |
+
DebugLog("Using quad split transformer model (2Q1-2Q4)")
|
| 174 |
+
elif self.use_quad_split_combined:
|
| 175 |
+
DebugLog("Using combined quad split transformer model (2Q1S-2Q4S)")
|
| 176 |
+
|
| 177 |
+
self.models = {}
|
| 178 |
+
self.states = {}
|
| 179 |
+
self.load_models()
|
| 180 |
+
|
| 181 |
+
def find_model_path(self, base_name, description="model"):
|
| 182 |
+
"""Find model path, checking mlmodelc first then mlpackage.
|
| 183 |
+
Also tries both with and without lut suffix.
|
| 184 |
+
|
| 185 |
+
Args:
|
| 186 |
+
base_name: Base name of the model without extension
|
| 187 |
+
description: Description for error message (e.g., "Split model part 2D1S")
|
| 188 |
+
|
| 189 |
+
Returns:
|
| 190 |
+
str: Path to the found model file
|
| 191 |
+
|
| 192 |
+
Raises:
|
| 193 |
+
FileNotFoundError: If neither mlmodelc nor mlpackage exists
|
| 194 |
+
"""
|
| 195 |
+
# For quad split parts, only try mlmodelc
|
| 196 |
+
if any(part in base_name for part in ['2Q1S', '2Q2S', '2Q3S', '2Q4S', '2Q1', '2Q2', '2Q3', '2Q4']):
|
| 197 |
+
model_path = os.path.join(self.model_dir, f"{base_name}.mlmodelc")
|
| 198 |
+
if os.path.exists(model_path):
|
| 199 |
+
return model_path
|
| 200 |
+
# If not found, try without lut suffix
|
| 201 |
+
if '_lut' in base_name:
|
| 202 |
+
base_without_lut = base_name.split('_lut')[0]
|
| 203 |
+
model_path = os.path.join(self.model_dir, f"{base_without_lut}.mlmodelc")
|
| 204 |
+
if os.path.exists(model_path):
|
| 205 |
+
return model_path
|
| 206 |
+
# Neither exists
|
| 207 |
+
raise FileNotFoundError(f"{description} not found: {base_name}.mlmodelc does not exist" +
|
| 208 |
+
(f" (also tried {base_name.split('_lut')[0]}.mlmodelc)" if '_lut' in base_name else ""))
|
| 209 |
+
|
| 210 |
+
# For other parts, try both mlmodelc and mlpackage
|
| 211 |
+
for ext in ['.mlmodelc', '.mlpackage']:
|
| 212 |
+
model_path = os.path.join(self.model_dir, f"{base_name}{ext}")
|
| 213 |
+
if os.path.exists(model_path):
|
| 214 |
+
return model_path
|
| 215 |
+
|
| 216 |
+
# If not found, try without lut suffix
|
| 217 |
+
if '_lut' in base_name:
|
| 218 |
+
base_without_lut = base_name.split('_lut')[0]
|
| 219 |
+
for ext in ['.mlmodelc', '.mlpackage']:
|
| 220 |
+
model_path = os.path.join(self.model_dir, f"{base_without_lut}{ext}")
|
| 221 |
+
if os.path.exists(model_path):
|
| 222 |
+
return model_path
|
| 223 |
+
|
| 224 |
+
# Neither exists
|
| 225 |
+
raise FileNotFoundError(f"{description} not found: neither {base_name}.mlmodelc nor {base_name}.mlpackage exist in {self.model_dir}" +
|
| 226 |
+
(f" (also tried {base_name.split('_lut')[0]}.mlmodelc/mlpackage)" if '_lut' in base_name else ""))
|
| 227 |
+
|
| 228 |
+
def load_models(self):
|
| 229 |
+
"""Load each model part."""
|
| 230 |
+
DebugLog("Loading model parts...")
|
| 231 |
+
|
| 232 |
+
for part in self.model_parts:
|
| 233 |
+
quant_suffix = f"_{self.quant_configs[part]}" if part in self.quant_configs else ""
|
| 234 |
+
model_key = f"{part}{quant_suffix}" # Use this as the key in self.models
|
| 235 |
+
|
| 236 |
+
try:
|
| 237 |
+
if part == '2' and self.use_combined_part2:
|
| 238 |
+
# Load combined part2 with multiple functions
|
| 239 |
+
base_name = f"llama32_part2_combined{quant_suffix}"
|
| 240 |
+
model_path = self.find_model_path(base_name, "Combined part2 model")
|
| 241 |
+
|
| 242 |
+
DebugLog(f"Loading combined part2 model: {model_path}")
|
| 243 |
+
# Load prefill function
|
| 244 |
+
self.models['2_prefill'] = load_model(model_path, compute_unit=ct.ComputeUnit.CPU_AND_NE, function_name='prefill')
|
| 245 |
+
# Load infer function
|
| 246 |
+
self.models['2_infer'] = load_model(model_path, compute_unit=ct.ComputeUnit.CPU_AND_NE, function_name='infer')
|
| 247 |
+
# Create shared state
|
| 248 |
+
self.states['transformer'] = self.models['2_prefill'].make_state()
|
| 249 |
+
DebugLog("Combined part2 model loaded successfully")
|
| 250 |
+
elif part == '2' and not self.use_combined_part2:
|
| 251 |
+
# Load regular part2 model
|
| 252 |
+
base_name = f"llama32_part2{quant_suffix}"
|
| 253 |
+
model_path = self.find_model_path(base_name, "Regular part2 model")
|
| 254 |
+
|
| 255 |
+
DebugLog(f"Loading regular part2 model: {model_path}")
|
| 256 |
+
self.models[model_key] = load_model(model_path)
|
| 257 |
+
self.states['transformer'] = self.models[model_key].make_state()
|
| 258 |
+
DebugLog("Regular part2 model loaded successfully")
|
| 259 |
+
elif part in ['2D1S', '2D2S'] and self.use_split_functions:
|
| 260 |
+
# Load split model with prefill/infer functions
|
| 261 |
+
base_name = f"llama32_part{part}{quant_suffix}"
|
| 262 |
+
model_path = self.find_model_path(base_name, f"Split model part {part}")
|
| 263 |
+
|
| 264 |
+
DebugLog(f"Loading split model part {part}: {model_path}")
|
| 265 |
+
# Load prefill function
|
| 266 |
+
self.models[f'{part}_prefill'] = load_model(model_path, compute_unit=ct.ComputeUnit.CPU_AND_NE, function_name='prefill')
|
| 267 |
+
# Load infer function
|
| 268 |
+
self.models[f'{part}_infer'] = load_model(model_path, compute_unit=ct.ComputeUnit.CPU_AND_NE, function_name='infer')
|
| 269 |
+
# Create shared state for first part only
|
| 270 |
+
if part == '2D1S':
|
| 271 |
+
self.states['transformer'] = self.models[f'{part}_infer'].make_state()
|
| 272 |
+
DebugLog(f"Split model part {part} loaded successfully")
|
| 273 |
+
elif part.endswith('S') and self.use_quad_split_combined:
|
| 274 |
+
# Load combined quad split model with prefill/infer functions
|
| 275 |
+
base_name = f"llama32_part{part}{quant_suffix}"
|
| 276 |
+
model_path = self.find_model_path(base_name, f"Combined quad split part {part}")
|
| 277 |
+
|
| 278 |
+
DebugLog(f"Loading combined quad split part {part}: {model_path}")
|
| 279 |
+
# Load prefill function
|
| 280 |
+
self.models[f'{part}_prefill'] = load_model(model_path, compute_unit=ct.ComputeUnit.CPU_AND_NE, function_name='prefill')
|
| 281 |
+
# Load infer function
|
| 282 |
+
self.models[f'{part}_infer'] = load_model(model_path, compute_unit=ct.ComputeUnit.CPU_AND_NE, function_name='infer')
|
| 283 |
+
# Create shared state for first part only
|
| 284 |
+
if part == '2Q1S':
|
| 285 |
+
self.states['transformer'] = self.models[f'{part}_infer'].make_state()
|
| 286 |
+
DebugLog(f"Created shared transformer state for all quad split parts")
|
| 287 |
+
DebugLog(f"Combined quad split part {part} loaded successfully")
|
| 288 |
+
elif part.startswith('2Q') and self.use_quad_split:
|
| 289 |
+
# Load quad split model with prefill/infer functions
|
| 290 |
+
# Append 'S' to part name for file lookup
|
| 291 |
+
base_name = f"llama32_part{part}S{quant_suffix}"
|
| 292 |
+
model_path = self.find_model_path(base_name, f"Quad split part {part}")
|
| 293 |
+
|
| 294 |
+
DebugLog(f"Loading quad split part {part}: {model_path}")
|
| 295 |
+
# Load prefill function
|
| 296 |
+
self.models[f'{part}_prefill'] = load_model(model_path, compute_unit=ct.ComputeUnit.CPU_AND_NE, function_name='prefill')
|
| 297 |
+
# Load infer function
|
| 298 |
+
self.models[f'{part}_infer'] = load_model(model_path, compute_unit=ct.ComputeUnit.CPU_AND_NE, function_name='infer')
|
| 299 |
+
# Create shared state for first part only
|
| 300 |
+
if part == '2Q1':
|
| 301 |
+
self.states['transformer'] = self.models[f'{part}_infer'].make_state()
|
| 302 |
+
DebugLog(f"Created shared transformer state for all quad split parts")
|
| 303 |
+
print(f"Created shared transformer state for all quad split parts")
|
| 304 |
+
print(f"Quad split part {part} loaded successfully")
|
| 305 |
+
else:
|
| 306 |
+
# Load regular models (part 1 and part3)
|
| 307 |
+
base_name = f"llama32_part{part}{quant_suffix}"
|
| 308 |
+
model_path = self.find_model_path(base_name, f"Regular part {part}")
|
| 309 |
+
|
| 310 |
+
print(f"[MODEL LOAD] Regular part {part}:")
|
| 311 |
+
print(f" - File: {model_path}")
|
| 312 |
+
print(f" - Loading as: '{model_key}'")
|
| 313 |
+
|
| 314 |
+
# Try loading with CPU first, then fall back to CPU_AND_NE if needed
|
| 315 |
+
try:
|
| 316 |
+
self.models[model_key] = load_model(model_path, compute_unit=ct.ComputeUnit.CPU_AND_NE)
|
| 317 |
+
print(f" - Loaded with CPU_AND_NE compute unit")
|
| 318 |
+
except Exception as cpu_error:
|
| 319 |
+
print(f" - CPU load failed, trying CPU_AND_NE: {str(cpu_error)}")
|
| 320 |
+
self.models[model_key] = load_model(model_path, compute_unit=ct.ComputeUnit.CPU)
|
| 321 |
+
print(f" - Loaded with CPU compute unit")
|
| 322 |
+
|
| 323 |
+
print(f"[MODEL LOAD] Current model_parts keys: {list(self.models.keys())}")
|
| 324 |
+
|
| 325 |
+
except Exception as e:
|
| 326 |
+
print(f"Error loading model part {part}: {str(e)}")
|
| 327 |
+
raise
|
| 328 |
+
|
| 329 |
+
def run_transformer_prefill(self, hidden_states, update_mask, position_ids, causal_mask, current_pos):
|
| 330 |
+
"""Run the transformer model in prefill mode."""
|
| 331 |
+
if self.use_split_functions:
|
| 332 |
+
# Use prefill variants for split model
|
| 333 |
+
for part in ['2D1S', '2D2S']:
|
| 334 |
+
inputs = {
|
| 335 |
+
'hidden_states': hidden_states.numpy(),
|
| 336 |
+
'position_ids': position_ids.numpy(),
|
| 337 |
+
'causal_mask': causal_mask.numpy(),
|
| 338 |
+
'start_pos': current_pos.numpy()
|
| 339 |
+
}
|
| 340 |
+
output = self.models[f'{part}_prefill'].predict(inputs, self.states['transformer'])
|
| 341 |
+
hidden_states = torch.from_numpy(output['dummy_output'])
|
| 342 |
+
return hidden_states
|
| 343 |
+
else:
|
| 344 |
+
# Use existing prefill implementation
|
| 345 |
+
return super().run_transformer_prefill(hidden_states, update_mask, position_ids, causal_mask, current_pos)
|
| 346 |
+
|
| 347 |
+
def run_transformer_infer(self, hidden_states, update_mask, position_ids, causal_mask, current_pos):
|
| 348 |
+
"""Run the transformer model in infer mode."""
|
| 349 |
+
if self.use_split_functions:
|
| 350 |
+
# Use infer variants for split model
|
| 351 |
+
for part in ['2D1S', '2D2S']:
|
| 352 |
+
inputs = {
|
| 353 |
+
'hidden_states': hidden_states.numpy(),
|
| 354 |
+
'update_mask': update_mask.numpy(),
|
| 355 |
+
'position_ids': position_ids.numpy(),
|
| 356 |
+
'causal_mask': causal_mask.numpy(),
|
| 357 |
+
'current_pos': current_pos.numpy()
|
| 358 |
+
}
|
| 359 |
+
output = self.models[f'{part}_infer'].predict(inputs, self.states['transformer'])
|
| 360 |
+
hidden_states = torch.from_numpy(output['transformer_output'])
|
| 361 |
+
return hidden_states
|
| 362 |
+
else:
|
| 363 |
+
# Use existing infer implementation
|
| 364 |
+
return super().run_transformer_infer(hidden_states, update_mask, position_ids, causal_mask, current_pos)
|
| 365 |
+
|
| 366 |
+
def get_state(self, part):
|
| 367 |
+
"""Get the appropriate state for a model part."""
|
| 368 |
+
return self.states['transformer']
|
| 369 |
+
|
| 370 |
+
def run_embeddings(self, input_ids):
|
| 371 |
+
"""Run the embeddings model (part 1)."""
|
| 372 |
+
if '1' not in self.models:
|
| 373 |
+
raise ValueError("Embeddings model (part 1) not loaded")
|
| 374 |
+
|
| 375 |
+
output_dict = self.models['1'].predict({
|
| 376 |
+
'input_ids': input_ids.numpy()
|
| 377 |
+
})
|
| 378 |
+
return torch.from_numpy(output_dict['hidden_states'])
|
| 379 |
+
|
| 380 |
+
def run_transformer(self, hidden_states, update_mask, position_ids, causal_mask, current_pos, part='2'):
|
| 381 |
+
"""Run the transformer model."""
|
| 382 |
+
if part not in self.models:
|
| 383 |
+
raise ValueError(f"Transformer model (part {part}) not loaded")
|
| 384 |
+
|
| 385 |
+
inputs = {
|
| 386 |
+
'hidden_states': hidden_states.numpy(),
|
| 387 |
+
'update_mask': update_mask.numpy(),
|
| 388 |
+
'position_ids': position_ids.numpy(),
|
| 389 |
+
'causal_mask': causal_mask.numpy(),
|
| 390 |
+
'current_pos': current_pos.numpy()
|
| 391 |
+
}
|
| 392 |
+
|
| 393 |
+
output_dict = self.models[part].predict(inputs, self.get_state(part))
|
| 394 |
+
return torch.from_numpy(output_dict['transformer_output'])
|
| 395 |
+
|
| 396 |
+
def run_transformer_splits(self, hidden_states, update_mask, position_ids, causal_mask, current_pos):
|
| 397 |
+
"""Run through transformer splits based on model configuration."""
|
| 398 |
+
if not self.use_split_model:
|
| 399 |
+
return self.run_transformer(hidden_states, update_mask, position_ids, causal_mask, current_pos)
|
| 400 |
+
|
| 401 |
+
# Handle different split configurations
|
| 402 |
+
if any(part.startswith('2Q') for part in self.model_parts): # Quad split
|
| 403 |
+
for i in range(1, 5):
|
| 404 |
+
part = f'2Q{i}'
|
| 405 |
+
hidden_states = self.run_transformer(
|
| 406 |
+
hidden_states, update_mask, position_ids, causal_mask, current_pos, part=part
|
| 407 |
+
)
|
| 408 |
+
elif any(part.startswith('2O') for part in self.model_parts): # Octa split
|
| 409 |
+
for i in range(1, 9):
|
| 410 |
+
part = f'2O{i}'
|
| 411 |
+
hidden_states = self.run_transformer(
|
| 412 |
+
hidden_states, update_mask, position_ids, causal_mask, current_pos, part=part
|
| 413 |
+
)
|
| 414 |
+
elif any(part.startswith('2D') for part in self.model_parts): # Dual split
|
| 415 |
+
# Run through both parts of the dual split
|
| 416 |
+
for base_part in ['2D1', '2D2']:
|
| 417 |
+
# Find the correct model key (with lut suffix if present)
|
| 418 |
+
part_key = next(key for key in self.models.keys() if key.startswith(f'{base_part}_') or key == base_part)
|
| 419 |
+
|
| 420 |
+
# Use the shared transformer state
|
| 421 |
+
if 'transformer' not in self.states:
|
| 422 |
+
raise ValueError("Transformer state not initialized. Make sure 2D1 is loaded first.")
|
| 423 |
+
|
| 424 |
+
inputs = {
|
| 425 |
+
'hidden_states': hidden_states.numpy(),
|
| 426 |
+
'update_mask': update_mask.numpy(),
|
| 427 |
+
'position_ids': position_ids.numpy(),
|
| 428 |
+
'causal_mask': causal_mask.numpy(),
|
| 429 |
+
'current_pos': current_pos.numpy()
|
| 430 |
+
}
|
| 431 |
+
output_dict = self.models[part_key].predict(inputs, self.states['transformer'])
|
| 432 |
+
hidden_states = torch.from_numpy(output_dict['transformer_output'])
|
| 433 |
+
|
| 434 |
+
return hidden_states
|
| 435 |
+
|
| 436 |
+
def run_lm_head(self, hidden_states):
|
| 437 |
+
"""Run the LM head model (part 3)."""
|
| 438 |
+
if '3' not in self.models:
|
| 439 |
+
raise ValueError("LM head model (part 3) not loaded")
|
| 440 |
+
|
| 441 |
+
output_dict = self.models['3'].predict({
|
| 442 |
+
'hidden_states': hidden_states.numpy()
|
| 443 |
+
})
|
| 444 |
+
|
| 445 |
+
# Handle split logits
|
| 446 |
+
logits_parts = []
|
| 447 |
+
for i in range(1, 9): # logits1 through logits8
|
| 448 |
+
logits_key = f'logits{i}'
|
| 449 |
+
if logits_key in output_dict:
|
| 450 |
+
logits_part = torch.from_numpy(output_dict[logits_key])
|
| 451 |
+
logits_parts.append(logits_part)
|
| 452 |
+
|
| 453 |
+
# Concatenate along the vocabulary dimension
|
| 454 |
+
return torch.cat(logits_parts, dim=-1)
|
| 455 |
+
|
| 456 |
+
def run_full_model(self, input_ids, update_mask, position_ids, causal_mask, current_pos):
|
| 457 |
+
"""Run the full model."""
|
| 458 |
+
if 'full' not in self.models:
|
| 459 |
+
raise ValueError("Full model not loaded")
|
| 460 |
+
|
| 461 |
+
# Update context size from global
|
| 462 |
+
self.context_size = CONTEXT_LENGTH
|
| 463 |
+
|
| 464 |
+
#kv_ was removed from the input names
|
| 465 |
+
inputs = {
|
| 466 |
+
'input_ids': input_ids.numpy(),
|
| 467 |
+
'update_mask': update_mask.numpy(),
|
| 468 |
+
'position_ids': position_ids.numpy(),
|
| 469 |
+
'causal_mask': causal_mask.numpy(),
|
| 470 |
+
'current_pos': current_pos.numpy()
|
| 471 |
+
}
|
| 472 |
+
|
| 473 |
+
# Print shapes of all inputs
|
| 474 |
+
if False:
|
| 475 |
+
print("[DEBUG] Input shapes:")
|
| 476 |
+
for key, value in inputs.items():
|
| 477 |
+
print(f" {key}: {value.shape}")
|
| 478 |
+
|
| 479 |
+
output_dict = self.models['full'].predict(inputs, self.states['transformer'])
|
| 480 |
+
|
| 481 |
+
# Handle split logits if necessary
|
| 482 |
+
if ENABLE_VACAB_SPLIT8:
|
| 483 |
+
logits_parts = []
|
| 484 |
+
for i in range(1, 9):
|
| 485 |
+
logits_parts.append(output_dict[f'logits{i}'])
|
| 486 |
+
logits = np.concatenate(logits_parts, axis=-1)
|
| 487 |
+
else:
|
| 488 |
+
logits = output_dict['logits']
|
| 489 |
+
|
| 490 |
+
return torch.from_numpy(logits)
|
| 491 |
+
|
| 492 |
+
def make_causal_mask(length, start):
|
| 493 |
+
|
| 494 |
+
# Initialize the mask with -inf
|
| 495 |
+
mask = np.full((1, 1, length, length), -np.inf, dtype=np.float16)
|
| 496 |
+
|
| 497 |
+
# Create row and column indices
|
| 498 |
+
row_indices = np.arange(length).reshape(length, 1) # Column vector
|
| 499 |
+
col_indices = np.arange(length).reshape(1, length) # Row vector
|
| 500 |
+
|
| 501 |
+
# Set allowed positions to 0 where col_index is within the allowed range of row_index
|
| 502 |
+
mask[:, :, col_indices <= (row_indices + start)] = 0
|
| 503 |
+
return mask
|
| 504 |
+
|
| 505 |
+
def initialize_tokenizer(model_path):
|
| 506 |
+
"""Initialize and configure the tokenizer."""
|
| 507 |
+
try:
|
| 508 |
+
print(f"[DEBUG] Loading tokenizer from model path: {model_path}")
|
| 509 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
|
| 510 |
+
|
| 511 |
+
print("\n[DEBUG] Tokenizer Configuration:")
|
| 512 |
+
print(f"Tokenizer type: {type(tokenizer)}")
|
| 513 |
+
print(f"Tokenizer name: {tokenizer.__class__.__name__}")
|
| 514 |
+
print(f"Vocabulary size: {len(tokenizer)}")
|
| 515 |
+
print(f"Model max length: {tokenizer.model_max_length}")
|
| 516 |
+
#print(f"Chat template: {tokenizer.chat_template if hasattr(tokenizer, 'chat_template') else 'None'}")
|
| 517 |
+
|
| 518 |
+
if tokenizer.pad_token is None:
|
| 519 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 520 |
+
tokenizer.pad_token_id = tokenizer.eos_token_id
|
| 521 |
+
print("[DEBUG] Set PAD token to EOS token")
|
| 522 |
+
|
| 523 |
+
print(f"\n[DEBUG] Special Tokens:")
|
| 524 |
+
print(f"PAD token: '{tokenizer.pad_token}' (ID: {tokenizer.pad_token_id})")
|
| 525 |
+
print(f"EOS token: '{tokenizer.eos_token}' (ID: {tokenizer.eos_token_id})")
|
| 526 |
+
print(f"BOS token: '{tokenizer.bos_token}' (ID: {tokenizer.bos_token_id})")
|
| 527 |
+
print(f"UNK token: '{tokenizer.unk_token}' (ID: {tokenizer.unk_token_id})")
|
| 528 |
+
|
| 529 |
+
return tokenizer
|
| 530 |
+
|
| 531 |
+
except Exception as e:
|
| 532 |
+
print(f"[ERROR] Failed to load tokenizer from {model_path}")
|
| 533 |
+
return None
|
| 534 |
+
|
| 535 |
+
class TokenPrinter:
|
| 536 |
+
"""Handles background printing of generated tokens."""
|
| 537 |
+
def __init__(self, tokenizer):
|
| 538 |
+
self.tokenizer = tokenizer
|
| 539 |
+
self.token_queue = queue.Queue()
|
| 540 |
+
self.stop_event = threading.Event()
|
| 541 |
+
self.thread = None
|
| 542 |
+
self.buffer = ""
|
| 543 |
+
self.lock = threading.Lock()
|
| 544 |
+
self.thinking = True # Track if we're still in thinking mode
|
| 545 |
+
self.decoding_buffer = [] # <-- Buffer for token IDs
|
| 546 |
+
self.start()
|
| 547 |
+
|
| 548 |
+
def start(self):
|
| 549 |
+
"""Start the printer thread."""
|
| 550 |
+
if self.thread is None:
|
| 551 |
+
self.thread = threading.Thread(target=self._print_worker)
|
| 552 |
+
self.thread.daemon = True
|
| 553 |
+
self.thread.start()
|
| 554 |
+
|
| 555 |
+
def add_token(self, token_id):
|
| 556 |
+
"""Add a token to the print queue."""
|
| 557 |
+
if not self.stop_event.is_set():
|
| 558 |
+
self.token_queue.put(token_id)
|
| 559 |
+
|
| 560 |
+
def drain_buffer(self):
|
| 561 |
+
"""
|
| 562 |
+
Decode token IDs from self.decoding_buffer in the main thread,
|
| 563 |
+
then print them with the correct color logic.
|
| 564 |
+
"""
|
| 565 |
+
if not self.decoding_buffer:
|
| 566 |
+
return
|
| 567 |
+
|
| 568 |
+
# Decode all tokens at once in the main thread.
|
| 569 |
+
token_str = self.tokenizer.decode(self.decoding_buffer)
|
| 570 |
+
self.decoding_buffer.clear()
|
| 571 |
+
|
| 572 |
+
# Color-handling logic. Check for "</think>" and handle self.thinking.
|
| 573 |
+
if self.thinking and "</think>" in token_str:
|
| 574 |
+
self.thinking = False
|
| 575 |
+
parts = token_str.split("</think>")
|
| 576 |
+
if len(parts) > 0:
|
| 577 |
+
print(parts[0] + "</think>", end='', flush=True)
|
| 578 |
+
if len(parts) > 1:
|
| 579 |
+
print(LIGHT_BLUE + parts[1], end='', flush=True)
|
| 580 |
+
else:
|
| 581 |
+
if not self.thinking:
|
| 582 |
+
print(LIGHT_BLUE + token_str, end='', flush=True)
|
| 583 |
+
else:
|
| 584 |
+
print(token_str, end='', flush=True)
|
| 585 |
+
|
| 586 |
+
def _print_worker(self):
|
| 587 |
+
"""Worker thread that takes token_ids from the queue but doesn't decode."""
|
| 588 |
+
while not self.stop_event.is_set():
|
| 589 |
+
try:
|
| 590 |
+
token_id = self.token_queue.get(timeout=0.01)
|
| 591 |
+
with self.lock:
|
| 592 |
+
# Just store the token_id, decode later on the main thread
|
| 593 |
+
self.decoding_buffer.append(token_id)
|
| 594 |
+
self.token_queue.task_done()
|
| 595 |
+
except queue.Empty:
|
| 596 |
+
continue
|
| 597 |
+
except Exception as e:
|
| 598 |
+
print(f"\n[ERROR] Token printer error: {str(e)}")
|
| 599 |
+
break
|
| 600 |
+
|
| 601 |
+
def stop(self):
|
| 602 |
+
"""Stop the printer thread."""
|
| 603 |
+
if self.thread and self.thread.is_alive():
|
| 604 |
+
self.stop_event.set()
|
| 605 |
+
try:
|
| 606 |
+
self.thread.join(timeout=1.0)
|
| 607 |
+
except Exception:
|
| 608 |
+
pass
|
| 609 |
+
print(RESET_COLOR) # Reset color at the end
|
| 610 |
+
return self.buffer
|
| 611 |
+
|
| 612 |
+
def parse_coreml_error(error_str):
|
| 613 |
+
"""Parse CoreML error message to extract shape information.
|
| 614 |
+
|
| 615 |
+
Args:
|
| 616 |
+
error_str: The error message string from CoreML
|
| 617 |
+
|
| 618 |
+
Returns:
|
| 619 |
+
tuple: (got_shape, expected_shape) or None if parsing fails
|
| 620 |
+
"""
|
| 621 |
+
try:
|
| 622 |
+
# Extract shapes from error message using regex
|
| 623 |
+
pattern = r"shape \(([\d\s x]+)\) does not match the shape \(([\d\s x]+)\)"
|
| 624 |
+
match = re.search(pattern, str(error_str))
|
| 625 |
+
if match:
|
| 626 |
+
got_shape = tuple(int(x) for x in match.group(1).split('x'))
|
| 627 |
+
expected_shape = tuple(int(x) for x in match.group(2).split('x'))
|
| 628 |
+
return got_shape, expected_shape
|
| 629 |
+
return None
|
| 630 |
+
except Exception as e:
|
| 631 |
+
print(f"Error parsing CoreML error message: {e}")
|
| 632 |
+
return None
|
| 633 |
+
|
| 634 |
+
def handle_coreml_shape_error(e, model_name=""):
|
| 635 |
+
"""Handle CoreML shape mismatch errors with detailed information.
|
| 636 |
+
|
| 637 |
+
Args:
|
| 638 |
+
e: The exception object
|
| 639 |
+
model_name: Name of the model for better error reporting
|
| 640 |
+
"""
|
| 641 |
+
error_str = str(e)
|
| 642 |
+
if "MultiArray shape" in error_str:
|
| 643 |
+
shape_info = parse_coreml_error(error_str)
|
| 644 |
+
if shape_info:
|
| 645 |
+
got_shape, expected_shape = shape_info
|
| 646 |
+
print(f"\n[ERROR] Shape mismatch in {model_name}:")
|
| 647 |
+
print(f" Got shape: {' x '.join(str(x) for x in got_shape)}")
|
| 648 |
+
print(f" Expected shape: {' x '.join(str(x) for x in expected_shape)}")
|
| 649 |
+
print("This usually indicates a mismatch between the model's expected context length")
|
| 650 |
+
print("and the actual input being provided.")
|
| 651 |
+
else:
|
| 652 |
+
print(f"\n[ERROR] Shape mismatch error in {model_name}:")
|
| 653 |
+
print(f" {error_str}")
|
| 654 |
+
else:
|
| 655 |
+
print(f"\n[ERROR] CoreML error in {model_name}:")
|
| 656 |
+
print(f" {error_str}")
|
| 657 |
+
|
| 658 |
+
def PreFillChunk(model_parts, input_ids, current_pos, context_size, causal_mask, batch_size=64):
|
| 659 |
+
tokens_to_process = current_pos
|
| 660 |
+
batch_pos = 0
|
| 661 |
+
|
| 662 |
+
while batch_pos < tokens_to_process:
|
| 663 |
+
batch_end = min(batch_pos + batch_size, tokens_to_process)
|
| 664 |
+
current_batch_size = batch_end - batch_pos
|
| 665 |
+
|
| 666 |
+
try:
|
| 667 |
+
# Get current batch of tokens
|
| 668 |
+
batch_input = input_ids[:, batch_pos:batch_end]
|
| 669 |
+
|
| 670 |
+
# Pad if needed
|
| 671 |
+
if current_batch_size < batch_size:
|
| 672 |
+
batch_input = F.pad(
|
| 673 |
+
batch_input,
|
| 674 |
+
(0, batch_size - current_batch_size),
|
| 675 |
+
value=0
|
| 676 |
+
)
|
| 677 |
+
|
| 678 |
+
# Generate position IDs for this batch
|
| 679 |
+
position_ids = torch.arange(batch_pos, batch_pos + batch_size, dtype=torch.int32)
|
| 680 |
+
|
| 681 |
+
# Prepare causal mask for this batch
|
| 682 |
+
multiple_causal_mask = causal_mask[:, :, batch_pos:batch_pos + batch_size, :]
|
| 683 |
+
|
| 684 |
+
# Find the correct model key for part 1 (with lut suffix if present)
|
| 685 |
+
part1_key = next(key for key in model_parts.keys() if key.startswith('1_') or key == '1')
|
| 686 |
+
|
| 687 |
+
try:
|
| 688 |
+
# Run embeddings (part 1)
|
| 689 |
+
hidden_states = model_parts[part1_key].predict({'input_ids': batch_input.numpy()})['hidden_states']
|
| 690 |
+
hidden_states = torch.from_numpy(hidden_states)
|
| 691 |
+
except Exception as e:
|
| 692 |
+
handle_coreml_shape_error(e, f"embeddings model (part {part1_key})")
|
| 693 |
+
raise
|
| 694 |
+
|
| 695 |
+
# Get shared transformer state
|
| 696 |
+
shared_state = model_parts['states']['transformer']
|
| 697 |
+
|
| 698 |
+
# Handle different model configurations
|
| 699 |
+
if any(f'{part}_prefill' in model_parts for part in ['2D1S', '2D2S']):
|
| 700 |
+
# S123 mode with prefill/infer functions
|
| 701 |
+
for part in ['2D1S', '2D2S']:
|
| 702 |
+
try:
|
| 703 |
+
inputs = {
|
| 704 |
+
'hidden_states': hidden_states.numpy(),
|
| 705 |
+
'position_ids': position_ids.numpy(),
|
| 706 |
+
'causal_mask': multiple_causal_mask.numpy(),
|
| 707 |
+
'start_pos': np.array([batch_pos], dtype=np.int32)
|
| 708 |
+
}
|
| 709 |
+
output = model_parts[f'{part}_prefill'].predict(inputs, shared_state)
|
| 710 |
+
hidden_states = torch.from_numpy(output['dummy_output'])
|
| 711 |
+
except Exception as e:
|
| 712 |
+
handle_coreml_shape_error(e, f"transformer model (part {part})")
|
| 713 |
+
raise
|
| 714 |
+
elif any(part.endswith('S') for part in model_parts if part.startswith('2Q')):
|
| 715 |
+
# Q123S mode with combined quad split
|
| 716 |
+
for i in range(1, 5):
|
| 717 |
+
part = f'2Q{i}S'
|
| 718 |
+
try:
|
| 719 |
+
inputs = {
|
| 720 |
+
'hidden_states': hidden_states.numpy(),
|
| 721 |
+
'position_ids': position_ids.numpy(),
|
| 722 |
+
'causal_mask': multiple_causal_mask.numpy(),
|
| 723 |
+
'start_pos': np.array([batch_pos], dtype=np.int32)
|
| 724 |
+
}
|
| 725 |
+
output = model_parts[f'{part}_prefill'].predict(inputs, shared_state)
|
| 726 |
+
hidden_states = torch.from_numpy(output['dummy_output'])
|
| 727 |
+
except Exception as e:
|
| 728 |
+
handle_coreml_shape_error(e, f"transformer model (part {part})")
|
| 729 |
+
raise
|
| 730 |
+
elif any(part.startswith('2Q') for part in model_parts):
|
| 731 |
+
# Q123 mode with quad split
|
| 732 |
+
for i in range(1, 5):
|
| 733 |
+
part = f'2Q{i}'
|
| 734 |
+
if f'{part}_prefill' in model_parts:
|
| 735 |
+
# Use prefill function if available
|
| 736 |
+
try:
|
| 737 |
+
inputs = {
|
| 738 |
+
'hidden_states': hidden_states.numpy(),
|
| 739 |
+
'position_ids': position_ids.numpy(),
|
| 740 |
+
'causal_mask': multiple_causal_mask.numpy(),
|
| 741 |
+
'start_pos': np.array([batch_pos], dtype=np.int32)
|
| 742 |
+
}
|
| 743 |
+
output = model_parts[f'{part}_prefill'].predict(inputs, shared_state)
|
| 744 |
+
hidden_states = torch.from_numpy(output['dummy_output'])
|
| 745 |
+
except Exception as e:
|
| 746 |
+
handle_coreml_shape_error(e, f"transformer model (part {part})")
|
| 747 |
+
raise
|
| 748 |
+
else:
|
| 749 |
+
# Use regular predict if no prefill function
|
| 750 |
+
try:
|
| 751 |
+
inputs = {
|
| 752 |
+
'hidden_states': hidden_states.numpy(),
|
| 753 |
+
'update_mask': torch.zeros((1, 1, context_size, 1), dtype=torch.float16).numpy(),
|
| 754 |
+
'position_ids': position_ids.numpy(),
|
| 755 |
+
'causal_mask': multiple_causal_mask.numpy(),
|
| 756 |
+
'current_pos': position_ids[0].numpy()
|
| 757 |
+
}
|
| 758 |
+
output = model_parts[part].predict(inputs, shared_state)
|
| 759 |
+
hidden_states = torch.from_numpy(output['transformer_output'])
|
| 760 |
+
except Exception as e:
|
| 761 |
+
handle_coreml_shape_error(e, f"transformer model (part {part})")
|
| 762 |
+
raise
|
| 763 |
+
elif any(key.startswith('2D') for key in model_parts.keys()):
|
| 764 |
+
# 123D mode with dual split (no prefill functions)
|
| 765 |
+
for base_part in ['2D1', '2D2']:
|
| 766 |
+
# Find the correct model key (with lut suffix if present)
|
| 767 |
+
part_key = next(key for key in model_parts.keys() if key.startswith(f'{base_part}_') or key == base_part)
|
| 768 |
+
try:
|
| 769 |
+
inputs = {
|
| 770 |
+
'hidden_states': hidden_states.numpy(),
|
| 771 |
+
'update_mask': torch.zeros((1, 1, context_size, 1), dtype=torch.float16).numpy(),
|
| 772 |
+
'position_ids': position_ids.numpy(),
|
| 773 |
+
'causal_mask': multiple_causal_mask.numpy(),
|
| 774 |
+
'current_pos': position_ids[0].numpy()
|
| 775 |
+
}
|
| 776 |
+
output = model_parts[part_key].predict(inputs, shared_state)
|
| 777 |
+
hidden_states = torch.from_numpy(output['transformer_output'])
|
| 778 |
+
except Exception as e:
|
| 779 |
+
handle_coreml_shape_error(e, f"transformer model (part {part_key})")
|
| 780 |
+
raise
|
| 781 |
+
|
| 782 |
+
batch_pos = batch_end
|
| 783 |
+
|
| 784 |
+
except Exception as e:
|
| 785 |
+
print(f"\n[ERROR] Failed processing batch {batch_pos}-{batch_end}:")
|
| 786 |
+
print(f" {str(e)}")
|
| 787 |
+
raise
|
| 788 |
+
|
| 789 |
+
return torch.tensor([current_pos], dtype=torch.int32)
|
| 790 |
+
|
| 791 |
+
def PreFillChunkOneByOne(model_parts, input_ids, current_pos, context_size, causal_mask):
|
| 792 |
+
"""Process prefill tokens one at a time using infer function."""
|
| 793 |
+
#print(f"[DEBUG] Starting one-by-one prefill for {current_pos} tokens")
|
| 794 |
+
|
| 795 |
+
for pos in range(current_pos):
|
| 796 |
+
# Get current token
|
| 797 |
+
current_token = input_ids[:, pos:pos+1]
|
| 798 |
+
single_causal_mask = causal_mask[:, :, pos:pos+1, :]
|
| 799 |
+
current_pos_tensor = torch.tensor([pos], dtype=torch.int32)
|
| 800 |
+
|
| 801 |
+
# Find the correct model key for part 1 (with lut suffix if present)
|
| 802 |
+
part1_key = next(key for key in model_parts.keys() if key.startswith('1_') or key == '1')
|
| 803 |
+
|
| 804 |
+
# Run embeddings (part 1)
|
| 805 |
+
hidden_states = torch.from_numpy(model_parts[part1_key].predict({
|
| 806 |
+
'input_ids': current_token.numpy()
|
| 807 |
+
})['hidden_states'])
|
| 808 |
+
|
| 809 |
+
#print(f"[DEBUG] pos: {pos} token: {current_token.item()} states: {hidden_states.shape}")
|
| 810 |
+
|
| 811 |
+
# Get shared transformer state
|
| 812 |
+
shared_state = model_parts['states']['transformer']
|
| 813 |
+
|
| 814 |
+
# Handle different model configurations
|
| 815 |
+
if any(f'{part}_infer' in model_parts for part in ['2D1S', '2D2S']):
|
| 816 |
+
# S123 mode with prefill/infer functions
|
| 817 |
+
for part in ['2D1S', '2D2S']:
|
| 818 |
+
inputs = {
|
| 819 |
+
'hidden_states': hidden_states.numpy(),
|
| 820 |
+
'update_mask': np.zeros((1, 1, context_size, 1), dtype=np.float16),
|
| 821 |
+
'position_ids': current_pos_tensor.numpy(),
|
| 822 |
+
'causal_mask': single_causal_mask.numpy(),
|
| 823 |
+
'current_pos': current_pos_tensor.numpy()
|
| 824 |
+
}
|
| 825 |
+
output = model_parts[f'{part}_infer'].predict(inputs, shared_state)
|
| 826 |
+
hidden_states = torch.from_numpy(output['transformer_output'])
|
| 827 |
+
elif any(key.startswith('2D') for key in model_parts.keys()):
|
| 828 |
+
# 123D mode or individual parts mode
|
| 829 |
+
for base_part in ['2D1', '2D2']:
|
| 830 |
+
# Find the correct model key (with lut suffix if present)
|
| 831 |
+
part_key = next(key for key in model_parts.keys() if key.startswith(f'{base_part}_') or key == base_part)
|
| 832 |
+
inputs = {
|
| 833 |
+
'hidden_states': hidden_states.numpy(),
|
| 834 |
+
'update_mask': np.zeros((1, 1, context_size, 1), dtype=np.float16),
|
| 835 |
+
'position_ids': current_pos_tensor.numpy(),
|
| 836 |
+
'causal_mask': single_causal_mask.numpy(),
|
| 837 |
+
'current_pos': current_pos_tensor.numpy()
|
| 838 |
+
}
|
| 839 |
+
output = model_parts[part_key].predict(inputs, shared_state)
|
| 840 |
+
hidden_states = torch.from_numpy(output['transformer_output'])
|
| 841 |
+
|
| 842 |
+
return torch.tensor([current_pos], dtype=torch.int32)
|
| 843 |
+
|
| 844 |
+
def run_inference(model_parts, tokenizer, prompt, context_size=CONTEXT_LENGTH, num_iterations=5, temperature=0.0):
|
| 845 |
+
"""Run inference using model parts."""
|
| 846 |
+
DebugLog(f"\nPrompt: {prompt}")
|
| 847 |
+
if temperature > 0:
|
| 848 |
+
DebugLog(f"Using temperature: {temperature}")
|
| 849 |
+
|
| 850 |
+
# Prepare the prompt
|
| 851 |
+
messages = [{"role": "user", "content": prompt}]
|
| 852 |
+
formatted_input = tokenizer.apply_chat_template(
|
| 853 |
+
messages,
|
| 854 |
+
return_tensors="pt",
|
| 855 |
+
add_generation_prompt=False
|
| 856 |
+
)
|
| 857 |
+
decoded_input = tokenizer.decode(formatted_input[0])
|
| 858 |
+
DebugLog(f"Decoded input: {decoded_input}")
|
| 859 |
+
DebugLog(f"prompt: {prompt}")
|
| 860 |
+
DebugLog(f"formatted_input size: {formatted_input.size()}")
|
| 861 |
+
DebugLog(f"formatted_input: {formatted_input}")
|
| 862 |
+
|
| 863 |
+
base_input_ids = formatted_input.to(torch.int32)
|
| 864 |
+
context_pos = base_input_ids.size(1)
|
| 865 |
+
prompt_tokens = context_pos - 1
|
| 866 |
+
|
| 867 |
+
# Pad sequence to context_size
|
| 868 |
+
input_ids = F.pad(
|
| 869 |
+
base_input_ids,
|
| 870 |
+
(0, context_size - context_pos),
|
| 871 |
+
value=0
|
| 872 |
+
)
|
| 873 |
+
|
| 874 |
+
DebugLog(f"context_pos (prompt length) = {context_pos}")
|
| 875 |
+
|
| 876 |
+
# Create causal mask
|
| 877 |
+
causal_mask = make_causal_mask(context_size, 0)
|
| 878 |
+
causal_mask = torch.tensor(causal_mask, dtype=torch.float16)
|
| 879 |
+
|
| 880 |
+
# Prefill phase
|
| 881 |
+
DebugLog("\nStarting prefill...")
|
| 882 |
+
start_time = time.time()
|
| 883 |
+
|
| 884 |
+
# Check if we're using 123D mode or individual parts
|
| 885 |
+
use_single_token = any(key.contains('2D') for key in model_parts.keys()) or any(part.contains('2D') for part in model_parts)
|
| 886 |
+
|
| 887 |
+
if False: #use_single_token:
|
| 888 |
+
print("\nRunning ST prefill...")
|
| 889 |
+
current_pos = PreFillChunkOneByOne(
|
| 890 |
+
model_parts,
|
| 891 |
+
input_ids,
|
| 892 |
+
context_pos - 1,
|
| 893 |
+
context_size,
|
| 894 |
+
causal_mask
|
| 895 |
+
)
|
| 896 |
+
sequential_prefill_time = time.time() - start_time
|
| 897 |
+
batch_prefll_time = 0.0
|
| 898 |
+
else:
|
| 899 |
+
print("\nRunning batch prefill...")
|
| 900 |
+
current_pos = PreFillChunk(
|
| 901 |
+
model_parts,
|
| 902 |
+
input_ids,
|
| 903 |
+
context_pos - 1,
|
| 904 |
+
context_size,
|
| 905 |
+
causal_mask,
|
| 906 |
+
batch_size=PREFILL_BATCH_SIZE
|
| 907 |
+
)
|
| 908 |
+
batch_prefill_time = time.time() - start_time
|
| 909 |
+
sequential_prefill_time = 0.0
|
| 910 |
+
|
| 911 |
+
# Initialize token printer
|
| 912 |
+
token_printer = TokenPrinter(tokenizer)
|
| 913 |
+
print("\nGenerated response:", end=' ', flush=True)
|
| 914 |
+
|
| 915 |
+
# Generation loop
|
| 916 |
+
start_gen_time = time.time()
|
| 917 |
+
pos = context_pos - 1
|
| 918 |
+
|
| 919 |
+
tokens_generated = 0
|
| 920 |
+
try:
|
| 921 |
+
DebugLog(f"\nStarting inference... context_pos: {context_pos}")
|
| 922 |
+
pos = context_pos
|
| 923 |
+
for step in range(num_iterations):
|
| 924 |
+
with torch.no_grad():
|
| 925 |
+
# Check if we need to shift cache
|
| 926 |
+
if pos >= context_size - 2:
|
| 927 |
+
shift_size = context_size // 4
|
| 928 |
+
new_size = context_size - shift_size
|
| 929 |
+
|
| 930 |
+
# Create shifted input_ids and preserve the most recent context
|
| 931 |
+
# Don't add BOS token since this is a continuation
|
| 932 |
+
tmp = torch.zeros((1, context_size), dtype=torch.int32)
|
| 933 |
+
tmp[:,0:new_size] = input_ids[:,shift_size:context_size]
|
| 934 |
+
input_ids = tmp
|
| 935 |
+
|
| 936 |
+
# Adjust position after shift
|
| 937 |
+
pos = new_size
|
| 938 |
+
|
| 939 |
+
# Create update mask for current position
|
| 940 |
+
update_mask = torch.zeros((1, 1, context_size, 1), dtype=torch.float16)
|
| 941 |
+
update_mask[0, 0, pos-1, 0] = 1.0
|
| 942 |
+
|
| 943 |
+
#print(f"\n[DEBUG] Shifted cache by {shift_size} tokens, maintaining context window of {new_size} tokens, new pos: {pos}")
|
| 944 |
+
|
| 945 |
+
# For Q123 mode, we need to run prefill on the shifted sequence
|
| 946 |
+
if any(part.startswith('2Q') for part in model_parts):
|
| 947 |
+
# Run prefill using PreFillChunk with proper batch size
|
| 948 |
+
# No need to adjust position since we're not adding BOS
|
| 949 |
+
current_pos = PreFillChunk(
|
| 950 |
+
model_parts,
|
| 951 |
+
input_ids,
|
| 952 |
+
pos-1, # how much ob
|
| 953 |
+
context_size, # Use full context size
|
| 954 |
+
causal_mask,
|
| 955 |
+
batch_size=PREFILL_BATCH_SIZE
|
| 956 |
+
)
|
| 957 |
+
#print(f"[DEBUG] Ran prefill after shift for position {pos} with batch_size={PREFILL_BATCH_SIZE}")
|
| 958 |
+
# Position should already be correct since we didn't add BOS
|
| 959 |
+
pos = current_pos
|
| 960 |
+
|
| 961 |
+
# Get current token
|
| 962 |
+
current_token = input_ids[:, pos-1:pos]
|
| 963 |
+
|
| 964 |
+
# Find the correct model key for part 1 (with lut suffix if present)
|
| 965 |
+
part1_key = next(key for key in model_parts.keys() if key.startswith('1_') or key == '1')
|
| 966 |
+
|
| 967 |
+
# Run embeddings (part 1)
|
| 968 |
+
hidden_states = model_parts[part1_key].predict({
|
| 969 |
+
'input_ids': current_token.numpy()
|
| 970 |
+
})['hidden_states']
|
| 971 |
+
hidden_states = torch.from_numpy(hidden_states)
|
| 972 |
+
|
| 973 |
+
# Get shared transformer state
|
| 974 |
+
shared_state = model_parts['states']['transformer']
|
| 975 |
+
|
| 976 |
+
# Create update mask for current position
|
| 977 |
+
update_mask = torch.zeros((1, 1, context_size, 1), dtype=torch.float16)
|
| 978 |
+
update_mask[0, 0, pos-1, 0] = 1.0
|
| 979 |
+
|
| 980 |
+
# Create position IDs tensor
|
| 981 |
+
position_ids = torch.tensor([pos-1], dtype=torch.int32)
|
| 982 |
+
|
| 983 |
+
# Create causal mask for current position
|
| 984 |
+
single_causal_mask = causal_mask[:, :, pos-1:pos, :]
|
| 985 |
+
|
| 986 |
+
# Run transformer layers based on model type
|
| 987 |
+
if any(f'{part}_infer' in model_parts for part in ['2D1S', '2D2S']):
|
| 988 |
+
# S123 mode with prefill/infer functions
|
| 989 |
+
for part in ['2D1S', '2D2S']:
|
| 990 |
+
inputs = {
|
| 991 |
+
'hidden_states': hidden_states.numpy(),
|
| 992 |
+
'update_mask': update_mask.numpy(),
|
| 993 |
+
'position_ids': position_ids.numpy(),
|
| 994 |
+
'causal_mask': single_causal_mask.numpy(),
|
| 995 |
+
'current_pos': position_ids.numpy()
|
| 996 |
+
}
|
| 997 |
+
output = model_parts[f'{part}_infer'].predict(inputs, shared_state)
|
| 998 |
+
hidden_states = torch.from_numpy(output['transformer_output'])
|
| 999 |
+
elif any(part.startswith('2Q') for part in model_parts.keys()):
|
| 1000 |
+
# Q123S mode with combined quad split
|
| 1001 |
+
for i in range(1, 5):
|
| 1002 |
+
part = f'2Q{i}S'
|
| 1003 |
+
inputs = {
|
| 1004 |
+
'hidden_states': hidden_states.numpy(),
|
| 1005 |
+
'update_mask': update_mask.numpy(),
|
| 1006 |
+
'position_ids': position_ids.numpy(),
|
| 1007 |
+
'causal_mask': single_causal_mask.numpy(),
|
| 1008 |
+
'current_pos': position_ids.numpy()
|
| 1009 |
+
}
|
| 1010 |
+
output = model_parts[f'{part}_infer'].predict(inputs, shared_state)
|
| 1011 |
+
hidden_states = torch.from_numpy(output['transformer_output'])
|
| 1012 |
+
elif any(part.startswith('2Q') for part in model_parts):
|
| 1013 |
+
# Q123 mode with quad split
|
| 1014 |
+
#print(f"[DEBUG] Running quad split inference at position {pos}")
|
| 1015 |
+
for i in range(1, 5):
|
| 1016 |
+
part = f'2Q{i}'
|
| 1017 |
+
if f'{part}_infer' in model_parts:
|
| 1018 |
+
# Use infer function if available
|
| 1019 |
+
inputs = {
|
| 1020 |
+
'hidden_states': hidden_states.numpy(),
|
| 1021 |
+
'update_mask': update_mask.numpy(),
|
| 1022 |
+
'position_ids': position_ids.numpy(),
|
| 1023 |
+
'causal_mask': single_causal_mask.numpy(),
|
| 1024 |
+
'current_pos': position_ids.numpy()
|
| 1025 |
+
}
|
| 1026 |
+
output = model_parts[f'{part}_infer'].predict(inputs, shared_state)
|
| 1027 |
+
else:
|
| 1028 |
+
# Use regular predict if no infer function
|
| 1029 |
+
inputs = {
|
| 1030 |
+
'hidden_states': hidden_states.numpy(),
|
| 1031 |
+
'update_mask': update_mask.numpy(),
|
| 1032 |
+
'position_ids': position_ids.numpy(),
|
| 1033 |
+
'causal_mask': single_causal_mask.numpy(),
|
| 1034 |
+
'current_pos': position_ids.numpy()
|
| 1035 |
+
}
|
| 1036 |
+
output = model_parts[part].predict(inputs, shared_state)
|
| 1037 |
+
hidden_states = torch.from_numpy(output['transformer_output'])
|
| 1038 |
+
elif any(key.startswith('2D') for key in model_parts.keys()):
|
| 1039 |
+
# 123D mode or individual parts mode
|
| 1040 |
+
for base_part in ['2D1', '2D2']:
|
| 1041 |
+
# Find the correct model key (with lut suffix if present)
|
| 1042 |
+
part_key = next(key for key in model_parts.keys() if key.startswith(f'{base_part}_') or key == base_part)
|
| 1043 |
+
inputs = {
|
| 1044 |
+
'hidden_states': hidden_states.numpy(),
|
| 1045 |
+
'update_mask': update_mask.numpy(),
|
| 1046 |
+
'position_ids': position_ids.numpy(),
|
| 1047 |
+
'causal_mask': single_causal_mask.numpy(),
|
| 1048 |
+
'current_pos': position_ids.numpy()
|
| 1049 |
+
}
|
| 1050 |
+
output = model_parts[part_key].predict(inputs, shared_state)
|
| 1051 |
+
hidden_states = torch.from_numpy(output['transformer_output'])
|
| 1052 |
+
else:
|
| 1053 |
+
print("\n[ERROR] No transformer model parts found!")
|
| 1054 |
+
break
|
| 1055 |
+
|
| 1056 |
+
try:
|
| 1057 |
+
# Run final layer norm and get logits
|
| 1058 |
+
# Find the correct model key for part 3 (with lut suffix if present)
|
| 1059 |
+
part3_key = next(key for key in model_parts.keys() if key.startswith('3_') or key == '3')
|
| 1060 |
+
output_dict = model_parts[part3_key].predict({
|
| 1061 |
+
'hidden_states': hidden_states.numpy()
|
| 1062 |
+
})
|
| 1063 |
+
|
| 1064 |
+
if ENABLE_VACAB_SPLIT8:
|
| 1065 |
+
# Get all logits parts in a single call
|
| 1066 |
+
logits_parts = []
|
| 1067 |
+
for i in range(1, 9):
|
| 1068 |
+
logits_parts.append(output_dict[f'logits{i}'])
|
| 1069 |
+
logits = np.concatenate(logits_parts, axis=-1)
|
| 1070 |
+
elif ENABLE_LOGITS2:
|
| 1071 |
+
# Get both logits parts in a single call
|
| 1072 |
+
logits = np.concatenate([
|
| 1073 |
+
output_dict['logits1'],
|
| 1074 |
+
output_dict['logits2']
|
| 1075 |
+
], axis=-1)
|
| 1076 |
+
else:
|
| 1077 |
+
logits = output_dict['logits']
|
| 1078 |
+
|
| 1079 |
+
# Convert to tensor and get next token
|
| 1080 |
+
logits = torch.from_numpy(logits)
|
| 1081 |
+
|
| 1082 |
+
# Apply temperature if specified
|
| 1083 |
+
if temperature > 0:
|
| 1084 |
+
# Scale logits by temperature
|
| 1085 |
+
logits = logits / temperature
|
| 1086 |
+
# Apply softmax to get probabilities
|
| 1087 |
+
probs = F.softmax(logits[0, -1, :], dim=-1)
|
| 1088 |
+
# Sample from the distribution
|
| 1089 |
+
next_token = torch.multinomial(probs, num_samples=1).item()
|
| 1090 |
+
else:
|
| 1091 |
+
# Use argmax if no temperature
|
| 1092 |
+
next_token = torch.argmax(logits[0, -1, :]).item()
|
| 1093 |
+
|
| 1094 |
+
# Add token to input sequence
|
| 1095 |
+
input_ids[0, pos] = next_token
|
| 1096 |
+
token_printer.add_token(next_token)
|
| 1097 |
+
|
| 1098 |
+
# Safely decode tokens in the main thread
|
| 1099 |
+
token_printer.drain_buffer()
|
| 1100 |
+
|
| 1101 |
+
# Update position and count
|
| 1102 |
+
pos += 1
|
| 1103 |
+
tokens_generated += 1
|
| 1104 |
+
|
| 1105 |
+
if next_token == tokenizer.eos_token_id:
|
| 1106 |
+
print("\n[DEBUG] Generated EOS token, stopping...")
|
| 1107 |
+
break
|
| 1108 |
+
except Exception as e:
|
| 1109 |
+
print(f"\n[ERROR] Error in final layer or token generation: {str(e)}")
|
| 1110 |
+
break
|
| 1111 |
+
|
| 1112 |
+
except KeyboardInterrupt:
|
| 1113 |
+
print("\n[DEBUG] Interrupted by user")
|
| 1114 |
+
except Exception as e:
|
| 1115 |
+
print(f"\n[ERROR] Exception during inference: {str(e)}")
|
| 1116 |
+
print(traceback.format_exc())
|
| 1117 |
+
|
| 1118 |
+
# Print timing statistics
|
| 1119 |
+
end_time = time.time()
|
| 1120 |
+
total_time = end_time - start_gen_time
|
| 1121 |
+
|
| 1122 |
+
print(f"\n\nTotal time: {total_time:.2f} seconds")
|
| 1123 |
+
print(f"Generation tokens: {tokens_generated}")
|
| 1124 |
+
print(f"Prefill tokens: {prompt_tokens}")
|
| 1125 |
+
print(f"Total tokens (prefill + generation): {prompt_tokens + tokens_generated}")
|
| 1126 |
+
|
| 1127 |
+
if prompt_tokens > 0:
|
| 1128 |
+
if batch_prefill_time > 0: # If using batch prefill
|
| 1129 |
+
prefill_tokens_per_second = prompt_tokens / batch_prefill_time
|
| 1130 |
+
effective_prefill_tokens_per_second = prompt_tokens / batch_prefill_time # Don't multiply by batch size
|
| 1131 |
+
print(f"Actual prefill tokens per second: {prefill_tokens_per_second:.2f}")
|
| 1132 |
+
print(f"Effective prefill tokens per second (batch={PREFILL_BATCH_SIZE}): {effective_prefill_tokens_per_second:.2f}")
|
| 1133 |
+
elif sequential_prefill_time > 0: # If using sequential prefill
|
| 1134 |
+
prefill_tokens_per_second = prompt_tokens / sequential_prefill_time
|
| 1135 |
+
print(f"Sequential prefill tokens per second: {prefill_tokens_per_second:.2f}")
|
| 1136 |
+
|
| 1137 |
+
if tokens_generated > 0:
|
| 1138 |
+
total_processing_time = total_time + (batch_prefill_time if batch_prefill_time > 0 else sequential_prefill_time)
|
| 1139 |
+
overall_tokens_per_second = (prompt_tokens + tokens_generated) / total_processing_time
|
| 1140 |
+
generation_tokens_per_second = tokens_generated / total_time
|
| 1141 |
+
print(f"Overall tokens processed per second (including prefill): {overall_tokens_per_second:.2f}")
|
| 1142 |
+
print(f"Generation-only tokens per second: {generation_tokens_per_second:.2f}")
|
| 1143 |
+
|
| 1144 |
+
return token_printer.stop(), {
|
| 1145 |
+
'total_time': total_time,
|
| 1146 |
+
'batch_prefill_time': batch_prefill_time,
|
| 1147 |
+
'sequential_prefill_time': sequential_prefill_time,
|
| 1148 |
+
'tokens_generated': tokens_generated,
|
| 1149 |
+
'prompt_tokens': prompt_tokens
|
| 1150 |
+
}
|
| 1151 |
+
|
| 1152 |
+
def DebugLog(message, always_print=False):
|
| 1153 |
+
"""Print debug message if ENABLE_CHAT_DEBUG is True or always_print is True.
|
| 1154 |
+
|
| 1155 |
+
Args:
|
| 1156 |
+
message: Message to print
|
| 1157 |
+
always_print: If True, print regardless of ENABLE_CHAT_DEBUG setting
|
| 1158 |
+
"""
|
| 1159 |
+
if ENABLE_CHAT_DEBUG or always_print:
|
| 1160 |
+
print(f"[DEBUG] {message}")
|
| 1161 |
+
|
| 1162 |
+
def chat_loop(model_parts, tokenizer, context_size=CONTEXT_LENGTH, temperature=0.0):
|
| 1163 |
+
"""Interactive chat loop that maintains conversation history."""
|
| 1164 |
+
print("\nStarting chat session. Press Ctrl+D to exit.")
|
| 1165 |
+
print("Type your message and press Enter to chat.")
|
| 1166 |
+
|
| 1167 |
+
DebugLog(f"Using context size: {context_size}")
|
| 1168 |
+
DebugLog(f"Temperature: {temperature}")
|
| 1169 |
+
DebugLog(f"Model parts loaded: {list(model_parts.keys())}")
|
| 1170 |
+
|
| 1171 |
+
# Initialize conversation history
|
| 1172 |
+
conversation = []
|
| 1173 |
+
input_ids = None
|
| 1174 |
+
current_pos = 0
|
| 1175 |
+
|
| 1176 |
+
try:
|
| 1177 |
+
while True:
|
| 1178 |
+
try:
|
| 1179 |
+
print(f"\n{LIGHT_GREEN}You:{RESET_COLOR}", end=' ', flush=True)
|
| 1180 |
+
user_input = input().strip()
|
| 1181 |
+
except EOFError:
|
| 1182 |
+
print("\nExiting chat...")
|
| 1183 |
+
break
|
| 1184 |
+
|
| 1185 |
+
if not user_input:
|
| 1186 |
+
continue
|
| 1187 |
+
|
| 1188 |
+
# Add user message to conversation
|
| 1189 |
+
conversation.append({"role": "user", "content": user_input})
|
| 1190 |
+
|
| 1191 |
+
DebugLog("\nFormatting conversation:")
|
| 1192 |
+
for msg in conversation:
|
| 1193 |
+
DebugLog(f" {msg['role']}: {msg['content'][:50]}...")
|
| 1194 |
+
|
| 1195 |
+
# Format entire conversation
|
| 1196 |
+
formatted_input = tokenizer.apply_chat_template(
|
| 1197 |
+
conversation,
|
| 1198 |
+
return_tensors="pt",
|
| 1199 |
+
add_generation_prompt=True
|
| 1200 |
+
)
|
| 1201 |
+
|
| 1202 |
+
DebugLog("\nTokenization:")
|
| 1203 |
+
DebugLog(f"Input token IDs: {formatted_input[0][:50]}...")
|
| 1204 |
+
DebugLog(f"Decoded tokens: {tokenizer.decode(formatted_input[0][:50])}...")
|
| 1205 |
+
DebugLog(f"Total tokens: {formatted_input.size(1)}")
|
| 1206 |
+
|
| 1207 |
+
# Convert to int32 tensor
|
| 1208 |
+
base_input_ids = formatted_input.to(torch.int32)
|
| 1209 |
+
context_pos = base_input_ids.size(1)
|
| 1210 |
+
|
| 1211 |
+
DebugLog(f"Context position: {context_pos}")
|
| 1212 |
+
|
| 1213 |
+
# Check if we need to truncate history
|
| 1214 |
+
if context_pos >= context_size - 100:
|
| 1215 |
+
DebugLog(f"\nNeed to truncate: {context_pos} tokens > {context_size-100} limit")
|
| 1216 |
+
while context_pos >= context_size - 100 and len(conversation) > 2:
|
| 1217 |
+
removed = conversation.pop(0)
|
| 1218 |
+
DebugLog(f"Removed message: {removed['role']}: {removed['content'][:30]}...")
|
| 1219 |
+
formatted_input = tokenizer.apply_chat_template(
|
| 1220 |
+
conversation,
|
| 1221 |
+
return_tensors="pt",
|
| 1222 |
+
add_generation_prompt=True
|
| 1223 |
+
)
|
| 1224 |
+
base_input_ids = formatted_input.to(torch.int32)
|
| 1225 |
+
context_pos = base_input_ids.size(1)
|
| 1226 |
+
DebugLog(f"New context size: {context_pos}")
|
| 1227 |
+
|
| 1228 |
+
# Pad sequence to context_size
|
| 1229 |
+
input_ids = F.pad(
|
| 1230 |
+
base_input_ids,
|
| 1231 |
+
(0, context_size - context_pos),
|
| 1232 |
+
value=0
|
| 1233 |
+
)
|
| 1234 |
+
|
| 1235 |
+
# Create causal mask for the entire context
|
| 1236 |
+
causal_mask = make_causal_mask(context_size, 0)
|
| 1237 |
+
causal_mask = torch.tensor(causal_mask, dtype=torch.float16)
|
| 1238 |
+
DebugLog(f"Created causal mask with shape: {causal_mask.shape}")
|
| 1239 |
+
|
| 1240 |
+
print(f"\n{LIGHT_BLUE}Assistant:{RESET_COLOR}", end=' ', flush=True)
|
| 1241 |
+
|
| 1242 |
+
# Run prefill on entire context
|
| 1243 |
+
if False: #any(key.contains('2D') for key in model_parts.keys()):
|
| 1244 |
+
DebugLog("Using sequential prefill")
|
| 1245 |
+
current_pos = PreFillChunkOneByOne(
|
| 1246 |
+
model_parts,
|
| 1247 |
+
input_ids,
|
| 1248 |
+
context_pos,
|
| 1249 |
+
context_size,
|
| 1250 |
+
causal_mask
|
| 1251 |
+
)
|
| 1252 |
+
elif any(part.startswith('2Q') for part in model_parts.keys()):
|
| 1253 |
+
DebugLog(f"Using quad split prefill (size={PREFILL_BATCH_SIZE})")
|
| 1254 |
+
current_pos = PreFillChunk(
|
| 1255 |
+
model_parts,
|
| 1256 |
+
input_ids,
|
| 1257 |
+
context_pos,
|
| 1258 |
+
context_size,
|
| 1259 |
+
causal_mask,
|
| 1260 |
+
batch_size=PREFILL_BATCH_SIZE
|
| 1261 |
+
)
|
| 1262 |
+
else:
|
| 1263 |
+
DebugLog(f"Using standard batch prefill (size={PREFILL_BATCH_SIZE})")
|
| 1264 |
+
current_pos = PreFillChunk(
|
| 1265 |
+
model_parts,
|
| 1266 |
+
input_ids,
|
| 1267 |
+
context_pos,
|
| 1268 |
+
context_size,
|
| 1269 |
+
causal_mask,
|
| 1270 |
+
batch_size=PREFILL_BATCH_SIZE
|
| 1271 |
+
)
|
| 1272 |
+
|
| 1273 |
+
# Initialize token printer
|
| 1274 |
+
token_printer = TokenPrinter(tokenizer)
|
| 1275 |
+
|
| 1276 |
+
# Generation loop
|
| 1277 |
+
pos = context_pos
|
| 1278 |
+
response_tokens = []
|
| 1279 |
+
generation_start_time = time.time() # Add timing
|
| 1280 |
+
|
| 1281 |
+
try:
|
| 1282 |
+
while True: # Changed from context_size - 1 to True for continuous generation
|
| 1283 |
+
# Check if we need to shift window
|
| 1284 |
+
if pos >= context_size - 2:
|
| 1285 |
+
DebugLog("\nShifting context window...")
|
| 1286 |
+
|
| 1287 |
+
shift_size = context_size // 4 # Shift by 1/4 of context
|
| 1288 |
+
new_size = context_size - shift_size
|
| 1289 |
+
|
| 1290 |
+
# Create shifted input_ids and preserve the most recent context
|
| 1291 |
+
tmp = torch.zeros((1, context_size), dtype=torch.int32)
|
| 1292 |
+
tmp[:,0:new_size] = input_ids[:,shift_size:context_size]
|
| 1293 |
+
input_ids = tmp
|
| 1294 |
+
|
| 1295 |
+
# Adjust position after shift
|
| 1296 |
+
pos = new_size
|
| 1297 |
+
|
| 1298 |
+
DebugLog(f"Shifted window by {shift_size} tokens, new position: {pos}")
|
| 1299 |
+
|
| 1300 |
+
# Run prefill on the shifted sequence
|
| 1301 |
+
if False: #if any(key.contains('2D') for key in model_parts.keys()):
|
| 1302 |
+
DebugLog("Running sequential prefill after shift")
|
| 1303 |
+
current_pos = PreFillChunkOneByOne(
|
| 1304 |
+
model_parts,
|
| 1305 |
+
input_ids,
|
| 1306 |
+
pos,
|
| 1307 |
+
context_size,
|
| 1308 |
+
causal_mask
|
| 1309 |
+
)
|
| 1310 |
+
else:
|
| 1311 |
+
DebugLog("Running batch prefill after shift (size={PREFILL_BATCH_SIZE})")
|
| 1312 |
+
current_pos = PreFillChunk(
|
| 1313 |
+
model_parts,
|
| 1314 |
+
input_ids,
|
| 1315 |
+
pos,
|
| 1316 |
+
context_size,
|
| 1317 |
+
causal_mask,
|
| 1318 |
+
batch_size=PREFILL_BATCH_SIZE
|
| 1319 |
+
)
|
| 1320 |
+
|
| 1321 |
+
# Get current token
|
| 1322 |
+
current_token = input_ids[:, pos-1:pos]
|
| 1323 |
+
|
| 1324 |
+
# Find the correct model key for part 1
|
| 1325 |
+
part1_key = next(key for key in model_parts.keys() if key.startswith('1_') or key == '1')
|
| 1326 |
+
|
| 1327 |
+
# Run embeddings (part 1)
|
| 1328 |
+
hidden_states = model_parts[part1_key].predict({
|
| 1329 |
+
'input_ids': current_token.numpy()
|
| 1330 |
+
})['hidden_states']
|
| 1331 |
+
hidden_states = torch.from_numpy(hidden_states)
|
| 1332 |
+
|
| 1333 |
+
# Get shared transformer state
|
| 1334 |
+
shared_state = model_parts['states']['transformer']
|
| 1335 |
+
|
| 1336 |
+
# Create update mask for current position
|
| 1337 |
+
update_mask = torch.zeros((1, 1, context_size, 1), dtype=torch.float16)
|
| 1338 |
+
update_mask[0, 0, pos-1, 0] = 1.0
|
| 1339 |
+
|
| 1340 |
+
# Create position IDs tensor
|
| 1341 |
+
position_ids = torch.tensor([pos-1], dtype=torch.int32)
|
| 1342 |
+
|
| 1343 |
+
# Create causal mask for current position
|
| 1344 |
+
single_causal_mask = causal_mask[:, :, pos-1:pos, :]
|
| 1345 |
+
|
| 1346 |
+
# Run transformer layers based on model type
|
| 1347 |
+
if any(f'{part}_infer' in model_parts for part in ['2D1S', '2D2S']):
|
| 1348 |
+
for part in ['2D1S', '2D2S']:
|
| 1349 |
+
inputs = {
|
| 1350 |
+
'hidden_states': hidden_states.numpy(),
|
| 1351 |
+
'update_mask': update_mask.numpy(),
|
| 1352 |
+
'position_ids': position_ids.numpy(),
|
| 1353 |
+
'causal_mask': single_causal_mask.numpy(),
|
| 1354 |
+
'current_pos': position_ids.numpy()
|
| 1355 |
+
}
|
| 1356 |
+
output = model_parts[f'{part}_infer'].predict(inputs, shared_state)
|
| 1357 |
+
hidden_states = torch.from_numpy(output['transformer_output'])
|
| 1358 |
+
elif any(part.startswith('2Q') for part in model_parts.keys()):
|
| 1359 |
+
DebugLog(f"Running quad split inference at position {pos}")
|
| 1360 |
+
for i in range(1, 5):
|
| 1361 |
+
part = f'2Q{i}'
|
| 1362 |
+
if f'{part}_infer' in model_parts:
|
| 1363 |
+
# Use infer function if available
|
| 1364 |
+
inputs = {
|
| 1365 |
+
'hidden_states': hidden_states.numpy(),
|
| 1366 |
+
'update_mask': update_mask.numpy(),
|
| 1367 |
+
'position_ids': position_ids.numpy(),
|
| 1368 |
+
'causal_mask': single_causal_mask.numpy(),
|
| 1369 |
+
'current_pos': position_ids.numpy()
|
| 1370 |
+
}
|
| 1371 |
+
output = model_parts[f'{part}_infer'].predict(inputs, shared_state)
|
| 1372 |
+
else:
|
| 1373 |
+
# Use regular predict if no infer function
|
| 1374 |
+
inputs = {
|
| 1375 |
+
'hidden_states': hidden_states.numpy(),
|
| 1376 |
+
'update_mask': update_mask.numpy(),
|
| 1377 |
+
'position_ids': position_ids.numpy(),
|
| 1378 |
+
'causal_mask': single_causal_mask.numpy(),
|
| 1379 |
+
'current_pos': position_ids.numpy()
|
| 1380 |
+
}
|
| 1381 |
+
output = model_parts[part].predict(inputs, shared_state)
|
| 1382 |
+
hidden_states = torch.from_numpy(output['transformer_output'])
|
| 1383 |
+
elif any(key.startswith('2D') for key in model_parts.keys()):
|
| 1384 |
+
for base_part in ['2D1', '2D2']:
|
| 1385 |
+
part_key = next(key for key in model_parts.keys() if key.startswith(f'{base_part}_') or key == base_part)
|
| 1386 |
+
inputs = {
|
| 1387 |
+
'hidden_states': hidden_states.numpy(),
|
| 1388 |
+
'update_mask': update_mask.numpy(),
|
| 1389 |
+
'position_ids': position_ids.numpy(),
|
| 1390 |
+
'causal_mask': single_causal_mask.numpy(),
|
| 1391 |
+
'current_pos': position_ids.numpy()
|
| 1392 |
+
}
|
| 1393 |
+
output = model_parts[part_key].predict(inputs, shared_state)
|
| 1394 |
+
hidden_states = torch.from_numpy(output['transformer_output'])
|
| 1395 |
+
|
| 1396 |
+
# Run final layer norm and get logits
|
| 1397 |
+
part3_key = next(key for key in model_parts.keys() if key.startswith('3_') or key == '3')
|
| 1398 |
+
output_dict = model_parts[part3_key].predict({
|
| 1399 |
+
'hidden_states': hidden_states.numpy()
|
| 1400 |
+
})
|
| 1401 |
+
|
| 1402 |
+
if ENABLE_VACAB_SPLIT8:
|
| 1403 |
+
logits_parts = []
|
| 1404 |
+
for i in range(1, 9):
|
| 1405 |
+
logits_parts.append(output_dict[f'logits{i}'])
|
| 1406 |
+
logits = np.concatenate(logits_parts, axis=-1)
|
| 1407 |
+
else:
|
| 1408 |
+
logits = output_dict['logits']
|
| 1409 |
+
|
| 1410 |
+
# Convert to tensor and get next token
|
| 1411 |
+
logits = torch.from_numpy(logits)
|
| 1412 |
+
|
| 1413 |
+
# Apply temperature if specified
|
| 1414 |
+
if temperature > 0:
|
| 1415 |
+
logits = logits / temperature
|
| 1416 |
+
probs = F.softmax(logits[0, -1, :], dim=-1)
|
| 1417 |
+
next_token = torch.multinomial(probs, num_samples=1).item()
|
| 1418 |
+
else:
|
| 1419 |
+
next_token = torch.argmax(logits[0, -1, :]).item()
|
| 1420 |
+
|
| 1421 |
+
# Add token to input sequence and response
|
| 1422 |
+
input_ids[0, pos] = next_token
|
| 1423 |
+
response_tokens.append(next_token)
|
| 1424 |
+
token_printer.add_token(next_token)
|
| 1425 |
+
|
| 1426 |
+
# Safely decode tokens in the main thread
|
| 1427 |
+
token_printer.drain_buffer()
|
| 1428 |
+
|
| 1429 |
+
pos += 1
|
| 1430 |
+
|
| 1431 |
+
# Add debug output for generated tokens
|
| 1432 |
+
if ENABLE_CHAT_DEBUG and len(response_tokens) > 0 and len(response_tokens) % 10 == 0:
|
| 1433 |
+
DebugLog(f"\nGenerated {len(response_tokens)} tokens")
|
| 1434 |
+
DebugLog(f"Last token: {next_token} -> '{tokenizer.decode([next_token])}'")
|
| 1435 |
+
|
| 1436 |
+
if next_token == tokenizer.eos_token_id:
|
| 1437 |
+
DebugLog("\nGenerated EOS token")
|
| 1438 |
+
break
|
| 1439 |
+
|
| 1440 |
+
# Get the complete response text and calculate stats
|
| 1441 |
+
response_text = token_printer.stop()
|
| 1442 |
+
generation_time = time.time() - generation_start_time
|
| 1443 |
+
tokens_per_second = len(response_tokens) / generation_time if generation_time > 0 else 0
|
| 1444 |
+
|
| 1445 |
+
DebugLog(f"\nFinal response length: {len(response_tokens)} tokens")
|
| 1446 |
+
|
| 1447 |
+
# Print generation stats in dark blue
|
| 1448 |
+
print(f"\n{DARK_BLUE}[{len(response_tokens)} tokens, {tokens_per_second:.1f} tokens/s]{RESET_COLOR}")
|
| 1449 |
+
|
| 1450 |
+
except KeyboardInterrupt:
|
| 1451 |
+
DebugLog("\nGeneration interrupted by user")
|
| 1452 |
+
response_text = token_printer.stop()
|
| 1453 |
+
generation_time = time.time() - generation_start_time
|
| 1454 |
+
tokens_per_second = len(response_tokens) / generation_time if generation_time > 0 else 0
|
| 1455 |
+
print(f"\n{DARK_BLUE}[{len(response_tokens)} tokens, {tokens_per_second:.1f} tokens/s]{RESET_COLOR}")
|
| 1456 |
+
|
| 1457 |
+
# Add assistant's response to conversation history
|
| 1458 |
+
conversation.append({"role": "assistant", "content": response_text})
|
| 1459 |
+
|
| 1460 |
+
except Exception as e:
|
| 1461 |
+
print(f"\n[ERROR] Chat loop error: {str(e)}")
|
| 1462 |
+
print(traceback.format_exc())
|
| 1463 |
+
|
| 1464 |
+
def main():
|
| 1465 |
+
global CONTEXT_LENGTH, PREFILL_BATCH_SIZE, MODEL_PATH
|
| 1466 |
+
|
| 1467 |
+
print("ANEMLL Chat. Pre-relase alpha version, 2025-01-31")
|
| 1468 |
+
print("Copyright (c) 2025, Anemll All rights reserved.")
|
| 1469 |
+
# Set default parameters
|
| 1470 |
+
model_type = "Q123" # Default model type
|
| 1471 |
+
lut_suffix = "lut4" # Default LUT suffix
|
| 1472 |
+
temperature = 0.0
|
| 1473 |
+
model_parts = {}
|
| 1474 |
+
model_path = "." # Default to current directory
|
| 1475 |
+
|
| 1476 |
+
if len(sys.argv) < 2:
|
| 1477 |
+
print("Usage: python chat.py [model_parts] [options]")
|
| 1478 |
+
print("Usage: python chat.py [model_parts] [options]")
|
| 1479 |
+
print("\nOptions:")
|
| 1480 |
+
print(" -d PATH # Model directory path (for both tokenizer and CoreML models)")
|
| 1481 |
+
print(" S123 # Combined split model (2D1S+2D2S)")
|
| 1482 |
+
print(" C123 # Combined part2 model with prefill/infer")
|
| 1483 |
+
print(" Q123 # Quad split model (2Q1-2Q4) [default]")
|
| 1484 |
+
print(" Q123S # Combined quad split model (2Q1S-2Q4S)")
|
| 1485 |
+
print(" 1 2D1 2D2 3 # Individual split parts")
|
| 1486 |
+
print(" pfN # Prefill batch size (e.g., pf128)")
|
| 1487 |
+
print(" ctx=N # Context length (e.g., ctx=2048) [default: 1024]")
|
| 1488 |
+
print(" temp=X # Temperature for sampling (e.g., temp=0.01)")
|
| 1489 |
+
print(" lut4 # LUT suffix [default]")
|
| 1490 |
+
print("\nDefault configuration: Q123 lut4 ctx=1024")
|
| 1491 |
+
print(" python chat.py Q123 -d ../anemll-DeepSeek-8B-ctx1024")
|
| 1492 |
+
# Use defaults instead of exiting
|
| 1493 |
+
print("\nUsing default configuration...")
|
| 1494 |
+
else:
|
| 1495 |
+
# Process command line arguments
|
| 1496 |
+
i = 1
|
| 1497 |
+
while i < len(sys.argv):
|
| 1498 |
+
if sys.argv[i] == '-d' and i + 1 < len(sys.argv):
|
| 1499 |
+
model_path = sys.argv[i + 1]
|
| 1500 |
+
i += 2
|
| 1501 |
+
# Extract context length from model path if present
|
| 1502 |
+
ctx_match = re.search(r'ctx(\d+)', model_path)
|
| 1503 |
+
if ctx_match:
|
| 1504 |
+
ctx_value = int(ctx_match.group(1))
|
| 1505 |
+
if 512 <= ctx_value <= 4096*2:
|
| 1506 |
+
CONTEXT_LENGTH = ctx_value
|
| 1507 |
+
print(f"Setting context length to {CONTEXT_LENGTH} from model path")
|
| 1508 |
+
continue
|
| 1509 |
+
elif sys.argv[i].startswith('lut'):
|
| 1510 |
+
lut_suffix = sys.argv[i]
|
| 1511 |
+
elif sys.argv[i] in ['S123', 'Q123', 'Q123S', 'C123', '123D']:
|
| 1512 |
+
model_type = sys.argv[i]
|
| 1513 |
+
i += 1
|
| 1514 |
+
|
| 1515 |
+
# Initialize tokenizer using the same path
|
| 1516 |
+
tokenizer = initialize_tokenizer(model_path)
|
| 1517 |
+
if tokenizer is None:
|
| 1518 |
+
print("[ERROR] Failed to initialize tokenizer. Exiting.")
|
| 1519 |
+
return
|
| 1520 |
+
|
| 1521 |
+
# Process model parts
|
| 1522 |
+
parts = [model_type]
|
| 1523 |
+
if lut_suffix:
|
| 1524 |
+
parts.append(lut_suffix)
|
| 1525 |
+
|
| 1526 |
+
try:
|
| 1527 |
+
split_model = SplitModelInference(parts, model_dir=model_path)
|
| 1528 |
+
model_parts.update(split_model.models)
|
| 1529 |
+
model_parts['states'] = {'transformer': split_model.states['transformer']}
|
| 1530 |
+
except Exception as e:
|
| 1531 |
+
print(f"Error loading model parts: {str(e)}")
|
| 1532 |
+
return
|
| 1533 |
+
|
| 1534 |
+
# Process remaining arguments
|
| 1535 |
+
i = 1
|
| 1536 |
+
while i < len(sys.argv):
|
| 1537 |
+
arg = sys.argv[i]
|
| 1538 |
+
if arg.startswith('pf') and arg[2:].isdigit():
|
| 1539 |
+
PREFILL_BATCH_SIZE = int(arg[2:])
|
| 1540 |
+
elif arg.startswith('ctx='):
|
| 1541 |
+
try:
|
| 1542 |
+
CONTEXT_LENGTH = int(arg.split('=')[1])
|
| 1543 |
+
except (IndexError, ValueError):
|
| 1544 |
+
print(f"[WARNING] Invalid context length format. Using default: {CONTEXT_LENGTH}")
|
| 1545 |
+
elif arg.startswith('temp='):
|
| 1546 |
+
try:
|
| 1547 |
+
temperature = float(arg.split('=')[1])
|
| 1548 |
+
if temperature < 0:
|
| 1549 |
+
print(f"[WARNING] Temperature must be non-negative. Using default: 0.0")
|
| 1550 |
+
temperature = 0.0
|
| 1551 |
+
except (IndexError, ValueError):
|
| 1552 |
+
print(f"[WARNING] Invalid temperature format. Using default: 0.0")
|
| 1553 |
+
i += 1
|
| 1554 |
+
|
| 1555 |
+
try:
|
| 1556 |
+
# Start interactive chat loop
|
| 1557 |
+
chat_loop(model_parts, tokenizer, context_size=CONTEXT_LENGTH, temperature=temperature)
|
| 1558 |
+
except Exception as e:
|
| 1559 |
+
print("An error occurred:")
|
| 1560 |
+
print(traceback.format_exc())
|
| 1561 |
+
|
| 1562 |
+
if __name__ == "__main__":
|
| 1563 |
+
main()
|
llama32_part1_lut4.mlmodelc.zip
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b5ae73d6d7f21fcca5d507000053fdd02b51981e68f6b657248b8a67fac112ce
|
| 3 |
+
size 809296883
|
llama32_part2Q1S_lut4.mlmodelc.zip
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1baa5e12e398e635358b11c7c6159a51b76e6b83b9b5f7b6967cfaf1c3fda143
|
| 3 |
+
size 840797896
|
llama32_part2Q2S_lut4.mlmodelc.zip
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:281f082ed2df5b0b2a042a2e017261f1859efe823d841b95b1f6a65bb3a977c0
|
| 3 |
+
size 841305827
|
llama32_part2Q3S_lut4.mlmodelc.zip
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:69fee129d23ee04acfb263ba75ec5d81e68073311ac8d4fcd8f6f2f64b1f7540
|
| 3 |
+
size 844542698
|
llama32_part2Q4S_lut4.mlmodelc.zip
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4e25faaf152d83647d5d7e05b020f6353d20ebab153a3eb4fc465dbbae0a547c
|
| 3 |
+
size 842983465
|
llama32_part3_lut4.mlmodelc.zip
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9dc1d2823d7d54fd8cf2d56e1803330e3c4b7c150d62c4749d911d02b6c7cb9c
|
| 3 |
+
size 239469149
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_bos_token": true,
|
| 3 |
+
"add_eos_token": false,
|
| 4 |
+
"bos_token": {
|
| 5 |
+
"__type": "AddedToken",
|
| 6 |
+
"content": "<|begin▁of▁sentence|>",
|
| 7 |
+
"lstrip": false,
|
| 8 |
+
"normalized": true,
|
| 9 |
+
"rstrip": false,
|
| 10 |
+
"single_word": false
|
| 11 |
+
},
|
| 12 |
+
"clean_up_tokenization_spaces": false,
|
| 13 |
+
"eos_token": {
|
| 14 |
+
"__type": "AddedToken",
|
| 15 |
+
"content": "<|end▁of▁sentence|>",
|
| 16 |
+
"lstrip": false,
|
| 17 |
+
"normalized": true,
|
| 18 |
+
"rstrip": false,
|
| 19 |
+
"single_word": false
|
| 20 |
+
},
|
| 21 |
+
"legacy": true,
|
| 22 |
+
"model_max_length": 16384,
|
| 23 |
+
"pad_token": {
|
| 24 |
+
"__type": "AddedToken",
|
| 25 |
+
"content": "<|end▁of▁sentence|>",
|
| 26 |
+
"lstrip": false,
|
| 27 |
+
"normalized": true,
|
| 28 |
+
"rstrip": false,
|
| 29 |
+
"single_word": false
|
| 30 |
+
},
|
| 31 |
+
"sp_model_kwargs": {},
|
| 32 |
+
"unk_token": null,
|
| 33 |
+
"tokenizer_class": "LlamaTokenizerFast",
|
| 34 |
+
"chat_template": "{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% set ns = namespace(is_first=false, is_tool=false, is_output_first=true, system_prompt='') %}{%- for message in messages %}{%- if message['role'] == 'system' %}{% set ns.system_prompt = message['content'] %}{%- endif %}{%- endfor %}{{bos_token}}{{ns.system_prompt}}{%- for message in messages %}{%- if message['role'] == 'user' %}{%- set ns.is_tool = false -%}{{'<|User|>' + message['content']}}{%- endif %}{%- if message['role'] == 'assistant' and message['content'] is none %}{%- set ns.is_tool = false -%}{%- for tool in message['tool_calls']%}{%- if not ns.is_first %}{{'<|Assistant|><|tool▁calls▁begin|><|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\\n' + '```json' + '\\n' + tool['function']['arguments'] + '\\n' + '```' + '<|tool▁call▁end|>'}}{%- set ns.is_first = true -%}{%- else %}{{'\\n' + '<|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\\n' + '```json' + '\\n' + tool['function']['arguments'] + '\\n' + '```' + '<|tool▁call▁end|>'}}{{'<|tool▁calls▁end|><|end▁of▁sentence|>'}}{%- endif %}{%- endfor %}{%- endif %}{%- if message['role'] == 'assistant' and message['content'] is not none %}{%- if ns.is_tool %}{{'<|tool▁outputs▁end|>' + message['content'] + '<|end▁of▁sentence|>'}}{%- set ns.is_tool = false -%}{%- else %}{% set content = message['content'] %}{% if '</think>' in content %}{% set content = content.split('</think>')[-1] %}{% endif %}{{'<|Assistant|>' + content + '<|end▁of▁sentence|>'}}{%- endif %}{%- endif %}{%- if message['role'] == 'tool' %}{%- set ns.is_tool = true -%}{%- if ns.is_output_first %}{{'<|tool▁outputs▁begin|><|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- set ns.is_output_first = false %}{%- else %}{{'\\n<|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- endif %}{%- endif %}{%- endfor -%}{% if ns.is_tool %}{{'<|tool▁outputs▁end|>'}}{% endif %}{% if add_generation_prompt and not ns.is_tool %}{{'<|Assistant|>'}}{% endif %}"
|
| 35 |
+
}
|