-
Notifications
You must be signed in to change notification settings - Fork 625
feat: add Kimi-K3 model definition and quantization example #2994
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
kylesayrs
wants to merge
7
commits into
main
Choose a base branch
from
kimi-k3-example
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
7 commits
Select commit
Hold shift + click to select a range
47f71bb
feat: add Kimi-K3 model definition and quantization example
kylesayrs 696791a
Apply suggestions from code review
kylesayrs d7f930f
docs: add comments noting differences from upstream Kimi-K3 modeling …
kylesayrs b6dd6de
refactor: rename modeling_kimi_k3_linear back to modeling_kimi_linear…
kylesayrs 15e99ed
docs: add Kimi-K3 to key models, exclude modeling files from linting
kylesayrs f4fbc03
docs: add Kimi-K3 FP8 Block example to key models
kylesayrs 26034fb
Merge branch 'main' into kimi-k3-example
kylesayrs 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
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
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,46 @@ | ||
| ## Kimi-K3 FP8 Block Example | ||
|
|
||
| ### Overview | ||
|
|
||
| This example uses `model_free_ptq` to quantize Kimi-K3 to FP8 block format without loading the full model into memory. | ||
| The original checkpoint ships pre-quantized, so a `CompressedTensorsDequantizer` is used to dequantize on the fly during conversion. | ||
|
|
||
| The full example script can be found [here](../../../examples/model_free_ptq/kimi_k3_fp8_block.py). | ||
|
|
||
| ### Code Walkthrough | ||
|
|
||
| ```python | ||
| from compressed_tensors.entrypoints.convert import CompressedTensorsDequantizer | ||
|
|
||
| from llmcompressor import model_free_ptq | ||
|
|
||
| MODEL_ID = "moonshotai/Kimi-K3" | ||
| SAVE_DIR = MODEL_ID.rstrip("/").split("/")[-1] + "-FP8-BLOCK" | ||
|
|
||
| # no attention because (q_proj|k_proj|v_proj|b_proj|f_a_proj) are all fused | ||
| # and `b_proj` has weight shape [96, 7168] which is not divisible by 128 | ||
| ignore = [ | ||
| "re:.*embed_tokens.*", | ||
| "re:.*self_attn.*", | ||
| "re:.*block_sparse_moe\.gate.*", | ||
| "re:.*self_attention_res_proj.*", | ||
| "re:.*mlp_res_proj.*", | ||
| "re:.*output_attn_res_proj.*", | ||
| "re:.*lm_head.*", | ||
| "re:.*vision_tower.*", | ||
| "re:.*mm_projector.*", | ||
| ] | ||
|
|
||
| model_free_ptq( | ||
| model_stub=MODEL_ID, | ||
| save_directory=SAVE_DIR, | ||
| scheme="FP8_BLOCK", | ||
| ignore=ignore, | ||
| converter=CompressedTensorsDequantizer( | ||
| MODEL_ID, | ||
| ignore=ignore, | ||
| ), | ||
| max_workers=7, | ||
| device=[f"cuda:{i}" for i in range(7)], | ||
| ) | ||
| ``` |
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,8 @@ | ||
| # Kimi K3 | ||
|
|
||
| Quantization examples for the Kimi K3 model. | ||
|
|
||
| ## Examples | ||
|
|
||
| - [NVFP4 Example](nvfp4-example.md) | ||
| - [FP8 Block Example](fp8-block-example.md) |
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,100 @@ | ||
| ## Kimi-K3 NVFP4 Example | ||
|
|
||
| ### Overview | ||
|
|
||
| Kimi-K3 requires custom modeling files bundled with LLM Compressor, since it is not yet supported in Transformers. | ||
| The example below quantizes the model to NVFP4 using calibration data. | ||
|
|
||
| The full example script can be found [here](../../../examples/quantizing_moe/kimi_k3_example.py). | ||
|
|
||
| ### Code Walkthrough | ||
|
|
||
| ```python | ||
| from compressed_tensors.quantization import QuantizationConfig | ||
| from transformers import AutoTokenizer | ||
|
|
||
| from datasets import load_dataset | ||
| from llmcompressor import oneshot | ||
| from llmcompressor.modeling.kimi_k3 import KimiK3ForConditionalGeneration | ||
| from llmcompressor.modifiers.quantization import QuantizationModifier | ||
| from llmcompressor.utils import load_context | ||
|
|
||
| MODEL_ID = "moonshotai/Kimi-K3" | ||
|
|
||
| # Load quantization config from pretrained and add ignore patterns | ||
| # for modules that should not be quantized | ||
| qconfig = QuantizationConfig.from_pretrained(MODEL_ID) | ||
| qconfig.ignore += [ | ||
| "re:.*mlp_res_proj.*", | ||
| "re:.*self_attention_res_proj.*", | ||
| "re:.*routed_expert.*", | ||
| "re:.*output_attn_res_proj.*", | ||
| ] | ||
|
|
||
| # Load model with the modified quantization config | ||
| with load_context(KimiK3ForConditionalGeneration): | ||
| model = KimiK3ForConditionalGeneration.from_pretrained( | ||
| MODEL_ID, | ||
| quantization_config=qconfig, | ||
| device_map="auto", | ||
| torch_dtype="auto", | ||
| trust_remote_code=True, | ||
| ) | ||
| tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True) | ||
|
|
||
| DATASET_ID = "HuggingFaceH4/ultrachat_200k" | ||
| DATASET_SPLIT = "train_sft" | ||
| NUM_CALIBRATION_SAMPLES = 512 | ||
| MAX_SEQUENCE_LENGTH = 2048 | ||
|
|
||
| # Load dataset and preprocess | ||
| ds = load_dataset(DATASET_ID, split=f"{DATASET_SPLIT}[:{NUM_CALIBRATION_SAMPLES}]") | ||
| ds = ds.shuffle(seed=42) | ||
|
|
||
|
|
||
| def preprocess(example): | ||
| return { | ||
| "text": tokenizer.apply_chat_template( | ||
| example["messages"], | ||
| tokenize=False, | ||
| ) | ||
| } | ||
|
|
||
|
|
||
| ds = ds.map(preprocess) | ||
|
|
||
|
|
||
| def tokenize(sample): | ||
| return tokenizer( | ||
| sample["text"], | ||
| padding=False, | ||
| max_length=MAX_SEQUENCE_LENGTH, | ||
| truncation=True, | ||
| add_special_tokens=False, | ||
| ) | ||
|
|
||
|
|
||
| ds = ds.map(tokenize, remove_columns=ds.column_names) | ||
|
|
||
| recipe = QuantizationModifier( | ||
| targets="Linear", | ||
| scheme="NVFP4", | ||
| ignore=[ | ||
| "lm_head", | ||
| r"re:.*block_sparse_moe\.gate", | ||
| "re:.*vision_tower.*", | ||
| ], | ||
| ) | ||
|
|
||
| oneshot( | ||
| model=model, | ||
| dataset=ds, | ||
| recipe=recipe, | ||
| max_seq_length=MAX_SEQUENCE_LENGTH, | ||
| num_calibration_samples=NUM_CALIBRATION_SAMPLES, | ||
| ) | ||
|
|
||
| SAVE_DIR = MODEL_ID.rstrip("/").split("/")[-1] + "-NVFP4" | ||
| model.save_pretrained(SAVE_DIR) | ||
| tokenizer.save_pretrained(SAVE_DIR) | ||
| ``` |
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,33 @@ | ||
| from compressed_tensors.entrypoints.convert import CompressedTensorsDequantizer | ||
|
|
||
| from llmcompressor import model_free_ptq | ||
|
|
||
| MODEL_ID = "moonshotai/Kimi-K3" | ||
| SAVE_DIR = MODEL_ID.rstrip("/").split("/")[-1] + "-FP8-BLOCK" | ||
|
|
||
| # no attention because (q_proj|k_proj|v_proj|b_proj|f_a_proj) are all fused | ||
| # and `b_proj` has weight shape [96, 7168] which is not divisible by 128 | ||
| ignore = [ | ||
| "re:.*embed_tokens.*", | ||
| "re:.*self_attn.*", | ||
| "re:.*block_sparse_moe\.gate.*", | ||
| "re:.*self_attention_res_proj.*", | ||
| "re:.*mlp_res_proj.*", | ||
| "re:.*output_attn_res_proj.*", | ||
| "re:.*lm_head.*", | ||
| "re:.*vision_tower.*", | ||
| "re:.*mm_projector.*", | ||
| ] | ||
|
|
||
| model_free_ptq( | ||
| model_stub=MODEL_ID, | ||
| save_directory=SAVE_DIR, | ||
| scheme="FP8_BLOCK", | ||
| ignore=ignore, | ||
| converter=CompressedTensorsDequantizer( | ||
| MODEL_ID, | ||
| ignore=ignore, | ||
| ), | ||
| max_workers=7, | ||
| device=[f"cuda:{i}" for i in range(7)], | ||
| ) |
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,87 @@ | ||
| from compressed_tensors.quantization import QuantizationConfig | ||
| from datasets import load_dataset | ||
| from transformers import AutoTokenizer | ||
|
|
||
| from llmcompressor import oneshot | ||
| from llmcompressor.modeling.kimi_k3 import KimiK3ForConditionalGeneration | ||
| from llmcompressor.modifiers.quantization import QuantizationModifier | ||
| from llmcompressor.utils import load_context | ||
|
|
||
| MODEL_ID = "moonshotai/Kimi-K3" | ||
|
|
||
| # Load quantization config from pretrained and add ignore patterns | ||
| # for modules that should not be quantized | ||
| qconfig = QuantizationConfig.from_pretrained(MODEL_ID) | ||
| qconfig.ignore += [ | ||
| "re:.*mlp_res_proj.*", | ||
| "re:.*self_attention_res_proj.*", | ||
| "re:.*routed_expert.*", | ||
| "re:.*output_attn_res_proj.*", | ||
| ] | ||
|
|
||
| # Load model with the modified quantization config | ||
| with load_context(KimiK3ForConditionalGeneration): | ||
| model = KimiK3ForConditionalGeneration.from_pretrained( | ||
| MODEL_ID, | ||
| quantization_config=qconfig, | ||
| device_map="auto", | ||
| torch_dtype="auto", | ||
| trust_remote_code=True, | ||
| ) | ||
| tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True) | ||
|
|
||
| DATASET_ID = "HuggingFaceH4/ultrachat_200k" | ||
| DATASET_SPLIT = "train_sft" | ||
| NUM_CALIBRATION_SAMPLES = 512 | ||
| MAX_SEQUENCE_LENGTH = 2048 | ||
|
|
||
| # Load dataset and preprocess | ||
| ds = load_dataset(DATASET_ID, split=f"{DATASET_SPLIT}[:{NUM_CALIBRATION_SAMPLES}]") | ||
| ds = ds.shuffle(seed=42) | ||
|
|
||
|
|
||
| def preprocess(example): | ||
| return { | ||
| "text": tokenizer.apply_chat_template( | ||
| example["messages"], | ||
| tokenize=False, | ||
| ) | ||
| } | ||
|
|
||
|
|
||
| ds = ds.map(preprocess) | ||
|
|
||
|
|
||
| def tokenize(sample): | ||
| return tokenizer( | ||
| sample["text"], | ||
| padding=False, | ||
| max_length=MAX_SEQUENCE_LENGTH, | ||
| truncation=True, | ||
| add_special_tokens=False, | ||
| ) | ||
|
|
||
|
|
||
| ds = ds.map(tokenize, remove_columns=ds.column_names) | ||
|
|
||
| recipe = QuantizationModifier( | ||
| targets="Linear", | ||
| scheme="NVFP4", | ||
| ignore=[ | ||
| "lm_head", | ||
| r"re:.*block_sparse_moe\.gate", | ||
| "re:.*vision_tower.*", | ||
| ], | ||
| ) | ||
|
|
||
| oneshot( | ||
| model=model, | ||
| dataset=ds, | ||
| recipe=recipe, | ||
| max_seq_length=MAX_SEQUENCE_LENGTH, | ||
| num_calibration_samples=NUM_CALIBRATION_SAMPLES, | ||
| ) | ||
|
|
||
| SAVE_DIR = MODEL_ID.rstrip("/").split("/")[-1] + "-NVFP4" | ||
| model.save_pretrained(SAVE_DIR) | ||
| tokenizer.save_pretrained(SAVE_DIR) | ||
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
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
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
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 @@ | ||
| from .modeling_kimi_k3 import KimiK3ForConditionalGeneration |
Oops, something went wrong.
Oops, something went wrong.
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.