AirLLM 2.8T LLM inference with single 4GB GPU
Python chinese-llmchinese-nlpfinetunegenerative-aiinstruct-gptinstruction-setllamallmloraopen-modelsopen-sourceopen-source-modelsqlora
Prefer native transformers impl; fix shard naming and attn fallback
Yu Li63053d6050a4
diff --git a/air_llm/airllm/airllm_base.py b/air_llm/airllm/airllm_base.pyindex 5ccd7ea..ad918a5 100644--- a/air_llm/airllm/airllm_base.py+++ b/air_llm/airllm/airllm_base.py@@ -105,10 +105,19 @@ class AirLLMBaseModel:self.running_dtype = dtypeself.dtype = self.running_dtype- if hf_token is not None:- self.config = AutoConfig.from_pretrained(self.model_local_path, token=hf_token, trust_remote_code=True)- else:- self.config = AutoConfig.from_pretrained(self.model_local_path, trust_remote_code=True)+ # Prefer transformers' native implementation; only trust the model's bundled remote code when+ # transformers doesn't recognize the architecture. Vendored remote code is frequently pinned+ # to an old transformers and breaks against the current cache/generation APIs (e.g.+ # DeepSeek-V2's modeling_deepseek.py calls the long-removed DynamicCache.seen_tokens).+ token_kwargs = {'token': hf_token} if hf_token is not None else {}+ try:+ self.config = AutoConfig.from_pretrained(+ self.model_local_path, trust_remote_code=False, **token_kwargs)+ self.trust_remote_code = False+ except Exception:+ self.config = AutoConfig.from_pretrained(+ self.model_local_path, trust_remote_code=True, **token_kwargs)+ self.trust_remote_code = Trueself.generation_config = self.get_generation_config()self.tokenizer = self.get_tokenizer(hf_token=hf_token)@@ -162,13 +171,16 @@ class AirLLMBaseModel:try:with init_empty_weights(include_buffers=False):self.model = AutoModelForCausalLM.from_config(- self.config, attn_implementation="sdpa", trust_remote_code=True)+ self.config, attn_implementation="sdpa", trust_remote_code=self.trust_remote_code)except (ValueError, TypeError) as e:- print(f"attn_implementation='sdpa' not available ({e}), using default attn implementation")+ print(f"attn_implementation='sdpa' not available ({e}), falling back to eager attention")self.model = Noneif self.model is None:+ # Some (often remote-code) architectures don't support sdpa and also default to it, so we+ # must request eager explicitly; otherwise transformers re-selects sdpa and errors again.with init_empty_weights(include_buffers=False):- self.model = AutoModelForCausalLM.from_config(self.config, trust_remote_code=True)+ self.model = AutoModelForCausalLM.from_config(+ self.config, attn_implementation="eager", trust_remote_code=self.trust_remote_code)quantization_config = getattr(self.config, "quantization_config", None)if quantization_config is not None:diff --git a/air_llm/airllm/utils.py b/air_llm/airllm/utils.pyindex 2d3518e..8487808 100644--- a/air_llm/airllm/utils.py+++ b/air_llm/airllm/utils.py@@ -277,6 +277,17 @@ def split_and_save_layers(checkpoint_path, layer_shards_saving_path=None, splittn_shards = len(set(index.values()))state_dict = {}+ # Map shard ordinal -> actual checkpoint filename, taken straight from the index. We must NOT+ # reconstruct names like f"model-000{n:02d}-of-000{n_shards:02d}.safetensors": repos differ in+ # zero-padding width (e.g. DeepSeek uses model-00001-of-000004.safetensors) and in extension.+ shard_num_to_file = {}+ for v in set(index.values()):+ parts = v.split('-')+ if len(parts) > 1:+ try:+ shard_num_to_file[int(parts[1])] = v+ except ValueError:+ passif not os.path.exists(saving_path):#os.makedirs(saving_path)@@ -293,20 +304,14 @@ def split_and_save_layers(checkpoint_path, layer_shards_saving_path=None, splittif max(shards) > shard:# optinoally delete original fileif delete_original and shard != 0:- if not safetensors_format:- to_delete = checkpoint_path / f'pytorch_model-000{shard:02d}-of-000{n_shards:02d}.bin'- else:- to_delete = checkpoint_path / f'model-000{shard:02d}-of-000{n_shards:02d}.safetensors'+ to_delete = checkpoint_path / shard_num_to_file[shard]print(f"deleting original file: {to_delete}")remove_real_and_linked_file(to_delete)shard += 1print(f'Loading shard {shard}/{n_shards}')- if not safetensors_format:- to_load = checkpoint_path / f'pytorch_model-000{shard:02d}-of-000{n_shards:02d}.bin'- else:- to_load = checkpoint_path / f'model-000{shard:02d}-of-000{n_shards:02d}.safetensors'+ to_load = checkpoint_path / shard_num_to_file[shard]# check if to_load exist, if not downloaad it...if not os.path.exists(to_load):diff --git a/air_llm/tests/test_streaming_gpu.py b/air_llm/tests/test_streaming_gpu.pyindex 24b4601..25ec6f6 100644--- a/air_llm/tests/test_streaming_gpu.py+++ b/air_llm/tests/test_streaming_gpu.py@@ -39,7 +39,8 @@ def cap_vram(max_vram_gb):def run_airllm(args):from airllm import AutoModel- model = AutoModel.from_pretrained(args.model, compression=args.compression)+ model = AutoModel.from_pretrained(args.model, compression=args.compression,+ delete_original=args.delete_original)ids = model.tokenizer([args.prompt], return_tensors="pt",return_attention_mask=False)["input_ids"].cuda()@@ -81,6 +82,8 @@ def main():p.add_argument("--max-new-tokens", type=int, default=12)p.add_argument("--max-vram-gb", type=float, default=None)p.add_argument("--compression", default=None, choices=[None, "4bit", "8bit"])+ p.add_argument("--delete-original", action="store_true",+ help="delete the original checkpoint shards while splitting (saves disk for big models)")p.add_argument("--compare", action="store_true",help="also run a full-load reference and assert outputs match")args = p.parse_args()