Views
No views yet
1
2# ============================================================================
3# DEEPSEEK-V2-LITE FP8 — INFERENCE TEST
4# ============================================================================
5from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedModel
6from unittest.mock import patch
7import torch, transformers, logging
8
9transformers.logging.set_verbosity_error()
10logging.getLogger("transformers").setLevel(logging.ERROR)
11
12MODEL_ID = 'frankmorales2020/deepseek-v2-lite-fp8-topo2026'
13device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
14
15_orig_init = PreTrainedModel._initialize_weights
16def _safe_init(self, module):
17 try: _orig_init(self, module)
18 except NotImplementedError as e:
19 if 'Float8_e4m3fn' in str(e) or 'normal_kernel_cpu' in str(e):
20 module._is_hf_initialized = True
21 else: raise
22
23with patch.object(PreTrainedModel, '_initialize_weights', _safe_init):
24 model = AutoModelForCausalLM.from_pretrained(
25 MODEL_ID, trust_remote_code=True, torch_dtype=torch.bfloat16,
26 device_map='cuda:0', low_cpu_mem_usage=True,
27 )
28model.eval()
29
30tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
31tokenizer.pad_token_id = tokenizer.eos_token_id
32
33TEST_PROMPTS = [
34 'The capital of France is',
35 'In machine learning, catastrophic forgetting refers to',
36 'DeepSeek-V2-Lite is a mixture-of-experts model that',
37]
38
39print('='*65)
40print(f'DEEPSEEK-V2-LITE FP8 INFERENCE TEST | {MODEL_ID}')
41print('='*65)
42for prompt in TEST_PROMPTS:
43 inp = tokenizer(prompt, return_tensors='pt').to(device)
44 with torch.no_grad():
45 out = model.generate(
46 **inp, max_new_tokens=40, do_sample=False,
47 use_cache=False, repetition_penalty=1.3,
48 pad_token_id=tokenizer.eos_token_id,
49 )
50 response = tokenizer.decode(out[0][inp['input_ids'].shape[1]:], skip_special_tokens=True)
51 print(f'\nPrompt : {prompt}')
52 print(f'Output : {response}')
53print('\n' + '='*65)
541
2 Compressing model: 3463it [00:17, 195.25it/s]
3Loading checkpoint shards: 100% 5/5 [00:02<00:00, 2.46it/s]=================================================================
4DEEPSEEK-V2-LITE FP8 INFERENCE TEST | frankmorales2020/deepseek-v2-lite-fp8-topo2026
5=================================================================
6
7Prompt : The capital of France is
8Output : Paris.
9Paris, the city that never sleeps! The French call it “La Ville-Lumière” (the City Of Light). It’s a place where you can find
10
11Prompt : In machine learning, catastrophic forgetting refers to
12Output : the phenomenon where a model trained on multiple tasks or datasets forgets previously learned information when it is presented with new data. This can occur because each task requires different parameters and weights for optimal performance; if these
13
14Prompt : DeepSeek-V2-Lite is a mixture-of-experts model that
15Output : can be used to generate text. It was trained on the Deepseek dataset, which contains over 10 billion tokens of English language data from various sources such as books and news articles.
16The
17
18=================================================================
191# Run once, then RESTART RUNTIME, then run this cell:
2# !pip install -q "compressed-tensors>=0.15.0"
3
4import warnings, logging, os
5warnings.filterwarnings("ignore")
6logging.getLogger("transformers").setLevel(logging.ERROR)
7os.environ["TRANSFORMERS_VERBOSITY"] = "error"
8os.environ["TRANSFORMERS_NO_ADVISORY_WARNINGS"] = "1"
9try:
10 from transformers.utils import logging as _hf_log
11 _hf_log.set_verbosity_error()
12except Exception:
13 pass
14
15import transformers.utils.import_utils as _iu
16import transformers.utils as _tu
17for _m in (_iu, _tu):
18 if not hasattr(_m, "is_torch_fx_available"):
19 _m.is_torch_fx_available = lambda: False
20
21import torch
22from transformers import AutoModelForCausalLM, AutoTokenizer
23import transformers.modeling_utils as _mu
24
25# FP8 fix: skip re-init of already-loaded FP8 weights.
26_mu.PreTrainedModel._initialize_weights = lambda self, *a, **k: None
27_mu.PreTrainedModel.initialize_weights = lambda self, *a, **k: None
28
29REPO = "frankmorales2020/deepseek-v2-lite-fp8-topo2026"
30PROMPTS = ["What is the capital of Japan?",
31 "What is the Spanish word for water?",
32 "What is Einstein's mass-energy equivalence?"]
33
34try:
35 tok = AutoTokenizer.from_pretrained(REPO, trust_remote_code=True)
36except Exception:
37 tok = AutoTokenizer.from_pretrained("deepseek-ai/DeepSeek-V2-Lite", trust_remote_code=True)
38if tok.pad_token is None:
39 tok.pad_token = tok.eos_token
40
41model = AutoModelForCausalLM.from_pretrained(
42 REPO, dtype=torch.float16, device_map="auto",
43 trust_remote_code=True, attn_implementation="eager").eval()
44
45nan = torch.isnan(model.get_input_embeddings().weight.float()).any().item()
46print("Embedding has NaN?", nan)
47
48if not nan:
49 for p in PROMPTS:
50 ins = tok(p, return_tensors="pt").to(model.device)
51 out = model.generate(**ins, max_new_tokens=40, do_sample=False,
52 repetition_penalty=1.2, no_repeat_ngram_size=3,
53 use_cache=False,
54 pad_token_id=tok.pad_token_id)
55 txt = tok.decode(out[0], skip_special_tokens=True)
56 print(f"\nQ: {p}\nA: {txt[len(p):].strip() if txt.startswith(p) else txt.strip()}")
571Compressing model: 100%|██████████| 3463/3463 [00:01<00:00, 1977.29it/s]
2Loading weights: 100% 12217/12217 [00:01<00:00, 8114.97it/s]Embedding has NaN? False
3Decompressing model: 100%|██████████| 3463/3463 [00:00<00:00, 13103.20it/s]
4
5Q: What is the capital of Japan?
6A: The answer to this question may seem obvious, but it’s actually a bit more complicated than you might think. The country has two capitals: Tokyo and Kyoto. Both cities are important in Japanese
7
8Q: What is the Spanish word for water?
9A: The English translation of “agua” in a sentence. Agua means Water, and it’s pronounced like this: ah-gwah (like how you say ‘gwa’
10
11Q: What is Einstein's mass-energy equivalence?
12A: Einstein’s Mass Energy Equivalence states that the energy of a body at rest (E) equals its mass times the speed of light squared. This equation can be written as: E = mc
13