-
Notifications
You must be signed in to change notification settings - Fork 16.3k
Add BF16 to FP8 scripts #809
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
yzlnew
wants to merge
2
commits into
deepseek-ai:main
Choose a base branch
from
yzlnew:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| import os | ||
| import json | ||
| import re | ||
| from argparse import ArgumentParser | ||
| from glob import glob | ||
| from tqdm import tqdm | ||
|
|
||
| import torch | ||
| from safetensors.torch import load_file, save_file | ||
|
|
||
| from kernel import weight_quant | ||
|
|
||
| # Layers that should not be quantized (remain in BF16) | ||
| SKIP_QUANT_PATTERNS = [ | ||
| r".*\.layernorm\.weight$", | ||
| r".*\.norm\.weight$", | ||
| r".*input_layernorm\.weight$", | ||
| r".*post_attention_layernorm\.weight$", | ||
| r".*\.kv_a_layernorm\.weight$", | ||
| r".*\.q_a_layernorm\.weight$", | ||
| r".*\.embed_tokens\.weight$", | ||
| r".*\.head\.weight$", | ||
| r".*lm_head\.weight$", | ||
| r".*\.eh_proj\.weight$", | ||
| r".*\.gate\.e_score_correction_bias$", | ||
| r".*\.gate\.weight$" | ||
| ] | ||
|
|
||
| def should_skip_quantization(weight_name): | ||
| """Check if weight name matches any pattern in the skip list""" | ||
| return any(re.match(pattern, weight_name) for pattern in SKIP_QUANT_PATTERNS) | ||
|
|
||
| def main(bf16_path, fp8_path): | ||
| torch.set_default_dtype(torch.bfloat16) | ||
| os.makedirs(fp8_path, exist_ok=True) | ||
|
|
||
| # Get list of safetensor files | ||
| safetensor_files = list(glob(os.path.join(bf16_path, "*.safetensors"))) | ||
| safetensor_files.sort() | ||
|
|
||
| # Load model index if it exists | ||
| model_index_file = os.path.join(bf16_path, "model.safetensors.index.json") | ||
| if os.path.exists(model_index_file): | ||
| with open(model_index_file, "r") as f: | ||
| model_index = json.load(f) | ||
| weight_map = model_index["weight_map"] | ||
| else: | ||
| # Create a new weight map if there's no index file | ||
| weight_map = {} | ||
|
|
||
| # Cache for loaded safetensor files | ||
| loaded_files = {} | ||
| fp8_weight_names = [] | ||
|
|
||
| for safetensor_file in tqdm(safetensor_files): | ||
| file_name = os.path.basename(safetensor_file) | ||
| current_state_dict = load_file(safetensor_file, device="cuda") | ||
| loaded_files[file_name] = current_state_dict | ||
|
|
||
| new_state_dict = {} | ||
| for weight_name, weight in current_state_dict.items(): | ||
| # Skip weights that should not be quantized | ||
| if should_skip_quantization(weight_name) or weight.dim() != 2: | ||
| new_state_dict[weight_name] = weight | ||
| else: | ||
| # Quantize weights to FP8 | ||
| fp8_weight, scale_inv = weight_quant(weight) | ||
| new_state_dict[weight_name] = fp8_weight | ||
| scale_inv_name = f"{weight_name}_scale_inv" | ||
| new_state_dict[scale_inv_name] = scale_inv | ||
| fp8_weight_names.append(weight_name) | ||
|
|
||
| # Update weight map | ||
| if weight_name in weight_map: | ||
| weight_map[scale_inv_name] = file_name | ||
|
|
||
| new_safetensor_file = os.path.join(fp8_path, file_name) | ||
| save_file(new_state_dict, new_safetensor_file) | ||
|
|
||
| # Memory management: keep only the 2 most recently used files | ||
| if len(loaded_files) > 2: | ||
| oldest_file = next(iter(loaded_files)) | ||
| del loaded_files[oldest_file] | ||
| torch.cuda.empty_cache() | ||
|
|
||
| # Update model index | ||
| new_model_index_file = os.path.join(fp8_path, "model.safetensors.index.json") | ||
| with open(new_model_index_file, "w") as f: | ||
| json.dump({"metadata": {}, "weight_map": weight_map}, f, indent=2) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| parser = ArgumentParser() | ||
| parser.add_argument("--input-bf16-hf-path", type=str, required=True) | ||
| parser.add_argument("--output-fp8-hf-path", type=str, required=True) | ||
| args = parser.parse_args() | ||
| main(args.input_bf16_hf_path, args.output_fp8_hf_path) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.