|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | +# All rights reserved. |
| 4 | +# |
| 5 | +# This source code is licensed under the BSD-style license found in the |
| 6 | +# LICENSE file in the root directory of this source tree. |
| 7 | + |
| 8 | +""" |
| 9 | +Hugging Face implementation for DeepSeek-V3 model inference. |
| 10 | +""" |
| 11 | + |
| 12 | +import argparse |
| 13 | +import gc |
| 14 | +import os |
| 15 | +import time |
| 16 | + |
| 17 | +import torch |
| 18 | + |
| 19 | + |
| 20 | +def print_gpu_memory_usage(message=""): |
| 21 | + """Print current GPU memory usage.""" |
| 22 | + if torch.cuda.is_available(): |
| 23 | + allocated = torch.cuda.memory_allocated() / (1024**3) |
| 24 | + reserved = torch.cuda.memory_reserved() / (1024**3) |
| 25 | + print( |
| 26 | + f"GPU Memory ({message}): Allocated: {allocated:.2f} GB, Reserved: {reserved:.2f} GB" |
| 27 | + ) |
| 28 | + |
| 29 | + |
| 30 | +def run_huggingface_implementation(args, _): |
| 31 | + """Run the DeepSeek-V3 model using Hugging Face Transformers.""" |
| 32 | + # Disable Hugging Face cache |
| 33 | + from transformers import AutoConfig, AutoModelForCausalLM |
| 34 | + |
| 35 | + # We're not using the tokenizer anymore, using fake inputs instead |
| 36 | + # Use local path for model weights if specified, otherwise use model_name |
| 37 | + model_path = args.model_path |
| 38 | + print(f"Loading model from local path: {model_path}") |
| 39 | + start_time = time.time() |
| 40 | + |
| 41 | + quantization_config = { |
| 42 | + "activation_scheme": "dynamic", |
| 43 | + "fmt": "e4m3", |
| 44 | + "quant_method": "fp8", # Updated from fp8 to fbgemm_fp8 |
| 45 | + "weight_block_size": [128, 128], |
| 46 | + } |
| 47 | + print(f"Using quantization config: {quantization_config}") |
| 48 | + |
| 49 | + # ============= Change config to only use a few layers ============= |
| 50 | + config = None |
| 51 | + if args.num_layers > 0: |
| 52 | + # Try to load config from local path first, fall back to model_name if needed |
| 53 | + try: |
| 54 | + config = AutoConfig.from_pretrained(model_path, trust_remote_code=True) |
| 55 | + except Exception as e: |
| 56 | + print(f"Could not load config from local path: {e}") |
| 57 | + print(f"Falling back to loading config from {args.model_name}") |
| 58 | + config = AutoConfig.from_pretrained(args.model_name, trust_remote_code=True) |
| 59 | + |
| 60 | + config.n_group = 1 # make n_groups = a huge group |
| 61 | + config.topk_group = 1 # make topk_group = a huge group |
| 62 | + # tailer the first several layers |
| 63 | + config.num_hidden_layers = args.num_layers |
| 64 | + # Explicitly set rope_interleaved to True to use the interleaved rope implementation |
| 65 | + config.rope_interleaved = True |
| 66 | + print(f"Modified config to use only {args.num_layers} layers") |
| 67 | + print(f"Config of Deepseek: {config}") |
| 68 | + |
| 69 | + # Load the model from local path |
| 70 | + model = AutoModelForCausalLM.from_pretrained( |
| 71 | + model_path, |
| 72 | + torch_dtype=torch.bfloat16, |
| 73 | + device_map="cuda", # Try with specific device first |
| 74 | + config=config, |
| 75 | + trust_remote_code=True, |
| 76 | + # Disable features that can cause issues with device mapping |
| 77 | + attn_implementation="eager", # Use standard attention instead of flash attention |
| 78 | + quantization_config=quantization_config, |
| 79 | + local_files_only=True, # Only use local files, don't fetch from cache |
| 80 | + use_auth_token=False, # Don't try to authenticate with HF |
| 81 | + ) |
| 82 | + |
| 83 | + print(f"Model loaded in {time.time() - start_time:.2f} seconds") |
| 84 | + print_gpu_memory_usage("After loading model") |
| 85 | + |
| 86 | + # Get the device where the model is loaded |
| 87 | + device = next(model.parameters()).device |
| 88 | + print(f"Model is on device: {device}") |
| 89 | + |
| 90 | + # Create fake input directly on the correct device |
| 91 | + print("\nCreating fake input with the same shape as tokenized input") |
| 92 | + |
| 93 | + # Define sequence length for fake input |
| 94 | + seq_length = 2048 # You can adjust this based on your needs |
| 95 | + vocab_size = 50000 |
| 96 | + |
| 97 | + with torch.no_grad(): |
| 98 | + # Create fake input_ids directly on the device - using random integers between 0 and 50000 (typical vocab size) |
| 99 | + torch.manual_seed(42) |
| 100 | + tokens = torch.randint( |
| 101 | + 0, vocab_size, (1, seq_length), dtype=torch.long, device="cuda" |
| 102 | + ) |
| 103 | + |
| 104 | + # Create fake attention_mask directly on the device - all 1s for full attention |
| 105 | + attention_mask = torch.ones((1, seq_length), dtype=torch.long, device=device) |
| 106 | + |
| 107 | + # Create inputs dictionary similar to what tokenizer would produce |
| 108 | + inputs = {"input_ids": tokens, "attention_mask": attention_mask} |
| 109 | + |
| 110 | + # Print input information |
| 111 | + print(f"Fake input token IDs: {inputs['input_ids'][0][:10].cpu().numpy()}...") |
| 112 | + print(f"Fake input shape: {inputs['input_ids'].shape}") |
| 113 | + print(f"Input tensors device: {inputs['input_ids'].device}") |
| 114 | + |
| 115 | + # Run a single forward pass |
| 116 | + print("\nRunning single forward pass...") |
| 117 | + start_time = time.time() |
| 118 | + |
| 119 | + with torch.no_grad(): |
| 120 | + # Forward pass through the model with output_hidden_states=True and output_attentions=True |
| 121 | + outputs = model( |
| 122 | + **inputs, output_hidden_states=True, output_attentions=True, use_cache=False |
| 123 | + ) |
| 124 | + |
| 125 | + forward_time = time.time() - start_time |
| 126 | + |
| 127 | + # Get the logits from the output |
| 128 | + logits = outputs.logits if hasattr(outputs, "logits") else outputs |
| 129 | + |
| 130 | + # Get the predictions for the next token (highest probability) |
| 131 | + next_token_logits = logits[:, -1, :] |
| 132 | + print(f"\nNext token logits : {next_token_logits}") |
| 133 | + next_token_probs = torch.softmax(next_token_logits, dim=-1) |
| 134 | + print(f"\nNext token probabilities: {next_token_probs}") |
| 135 | + top_k_values, top_k_indices = torch.topk(next_token_probs, 5, dim=-1) |
| 136 | + |
| 137 | + print("\nForward Pass Results:") |
| 138 | + print(f"- Output logits shape: {logits.shape}") |
| 139 | + print(f"- Sequence length: {logits.shape[1]}") |
| 140 | + print(f"- Vocabulary size: {logits.shape[2]}") |
| 141 | + |
| 142 | + print( |
| 143 | + "\nTop 5 predicted next tokens (showing IDs only since we're not using tokenizer):" |
| 144 | + ) |
| 145 | + for i, (value, index) in enumerate(zip(top_k_values[0], top_k_indices[0])): |
| 146 | + print(f" {i+1}. Token ID: {index} - Probability: {value.item():.4f}") |
| 147 | + |
| 148 | + print(f"\nForward pass stats:") |
| 149 | + print(f"- Time: {forward_time:.4f} seconds") |
| 150 | + print(f"- Input tokens: {inputs['input_ids'].shape[1]}") |
| 151 | + print(f"- Tokens per second: {inputs['input_ids'].shape[1] / forward_time:.2f}") |
| 152 | + print_gpu_memory_usage("After forward pass") |
| 153 | + |
| 154 | + |
| 155 | +def main(): |
| 156 | + parser = argparse.ArgumentParser(description="Load and test DeepSeek-V3 model") |
| 157 | + parser.add_argument( |
| 158 | + "--num_layers", |
| 159 | + type=int, |
| 160 | + default=5, # tailered to 5 layers for 671B model |
| 161 | + help="Number of layers to use (0 for all layers)", |
| 162 | + ) |
| 163 | + |
| 164 | + # Hugging Face specific arguments |
| 165 | + parser.add_argument( |
| 166 | + "--model_path", |
| 167 | + type=str, |
| 168 | + default="/data/users/jianiw/model/DeepSeek-V3.1-Base", |
| 169 | + help="Hugging Face model name or path", |
| 170 | + ) |
| 171 | + |
| 172 | + args = parser.parse_args() |
| 173 | + run_huggingface_implementation(args, None) |
| 174 | + |
| 175 | + |
| 176 | +if __name__ == "__main__": |
| 177 | + main() |
0 commit comments