-
Notifications
You must be signed in to change notification settings - Fork 625
[WIP] [Kimi-K3] #2978
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
Closed
Closed
[WIP] [Kimi-K3] #2978
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
553ea54
better ignore
kylesayrs ef07907
final
kylesayrs bcbda0b
kylesayrs/july28
kylesayrs 152ce20
proper tracing
kylesayrs 24bc29d
traceable, correct recipe
kylesayrs 054728e
fix non-dist case
kylesayrs de43010
tqdms
kylesayrs 5fe18e2
random stuff
kylesayrs c654ff7
best
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
| 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
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,96 @@ | ||
| from compressed_tensors.offload import dispatch_model | ||
| 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 = "inference-optimization/Kimi-K3-0.18B" | ||
|
|
||
| # Load model. | ||
| with load_context(KimiK3ForConditionalGeneration): | ||
| model = KimiK3ForConditionalGeneration.from_pretrained( | ||
| MODEL_ID, | ||
| device_map="auto", | ||
| trust_remote_code=True, | ||
| ) | ||
| tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True) | ||
|
|
||
| DATASET_ID = "HuggingFaceH4/ultrachat_200k" | ||
| DATASET_SPLIT = "train_sft" | ||
|
|
||
| # Select number of samples. 512 samples is a good place to start. | ||
| # MoE models benefit from more samples for better expert calibration. | ||
| 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) | ||
|
|
||
|
|
||
| # Tokenize inputs. | ||
| 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) | ||
|
|
||
| # Configure the quantization algorithm and scheme. | ||
| # In this case, we: | ||
| # * quantize the weights to fp4 with per-group-16 scaling | ||
| # * quantize the activations to fp4 with calibrated global scale | ||
| # The MoE gate (KimiMoEGate) and vision tower are excluded from quantization. | ||
| recipe = QuantizationModifier( | ||
| targets="Linear", | ||
| scheme="NVFP4", | ||
| ignore=[ | ||
| "lm_head", | ||
| r"re:.*block_sparse_moe\.gate", | ||
| "re:.*vision_tower.*", | ||
| ], | ||
| ) | ||
|
|
||
| # Apply quantization. | ||
| oneshot( | ||
| model=model, | ||
| dataset=ds, | ||
| recipe=recipe, | ||
| max_seq_length=MAX_SEQUENCE_LENGTH, | ||
| num_calibration_samples=NUM_CALIBRATION_SAMPLES, | ||
| ) | ||
|
|
||
| print("\n\n") | ||
| print("========== SAMPLE GENERATION ==============") | ||
| dispatch_model(model) | ||
| input_ids = tokenizer("Hello my name is", return_tensors="pt").input_ids.to( | ||
| model.device | ||
| ) | ||
| output = model.generate(input_ids, max_new_tokens=100) | ||
| print(tokenizer.decode(output[0])) | ||
| print("==========================================\n\n") | ||
|
|
||
| # Save to disk in compressed-tensors format. | ||
| 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
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,121 @@ | ||
| import torch | ||
| from compressed_tensors.offload import init_dist | ||
| from compressed_tensors.quantization.quant_scheme import ( | ||
| FP8_BLOCK, | ||
| NVFP4, | ||
| QuantizationScheme, | ||
| ) | ||
| from transformers import AutoTokenizer, InklingForConditionalGeneration | ||
|
|
||
| from datasets import load_dataset | ||
| from llmcompressor import oneshot | ||
| from llmcompressor.datasets.utils import get_rank_partition | ||
| from llmcompressor.modifiers.quantization import QuantizationModifier | ||
| from llmcompressor.utils import load_context | ||
|
|
||
| # Load the model | ||
| init_dist() | ||
| # if torch.distributed.get_rank() == 0: | ||
| # torch.cuda.memory._record_memory_history(max_entries=10000000) | ||
| # model_id = "thinkingmachines/Inkling" | ||
| model_id = "inference-optimization/Inkling-0.6B-A0.6B" | ||
| with load_context(InklingForConditionalGeneration): | ||
| model = InklingForConditionalGeneration.from_pretrained( | ||
| model_id, | ||
| device_map="auto_offload", | ||
| max_memory={}, | ||
| offload_folder="/mnt/nvme-data/engine/kylesayrs/offload_folder", | ||
| ) | ||
| tokenizer = AutoTokenizer.from_pretrained(model_id) | ||
|
|
||
| # Select calibration dataset. | ||
| DATASET_ID = "HuggingFaceH4/ultrachat_200k" | ||
| DATASET_SPLIT = "train_sft" | ||
|
|
||
| # Select number of samples. 512 samples is a good place to start. | ||
| # Increasing the number of samples can improve accuracy. | ||
| NUM_CALIBRATION_SAMPLES = 4 # 512 | ||
| MAX_SEQUENCE_LENGTH = 1024 # 2048 | ||
|
|
||
| # Load dataset and preprocess. | ||
| ds = load_dataset( | ||
| DATASET_ID, split=get_rank_partition(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) | ||
|
|
||
|
|
||
| # Tokenize inputs. | ||
| 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) | ||
|
|
||
| # Configure the quantization algorithm to run. | ||
| recipe = QuantizationModifier( | ||
| config_groups={ | ||
| "attention": QuantizationScheme( | ||
| targets=[r"re:.*attn\..*"], | ||
| **FP8_BLOCK, | ||
| ), | ||
| "mlp": QuantizationScheme( | ||
| targets=[r"re:.*mlp\..*"], | ||
| **NVFP4, | ||
| ), | ||
| }, | ||
| ignore=[ | ||
| r"re:.*sconv$", | ||
| r"re:.*mlp\.gate$", # technically not necessary `InklingTopkRouter` | ||
| r"re:.*shared_experts.*", | ||
| r"re:audio_tower.*", | ||
| r"re:vision_tower.*", | ||
| ], | ||
| ) | ||
|
|
||
| try: | ||
| # Apply algorithms. | ||
| num_experts = getattr(model.config, "n_routed_experts", 256) | ||
| oneshot( | ||
| model=model, | ||
| dataset=ds, | ||
| batch_size=1, | ||
| recipe=recipe, | ||
| shuffle_calibration_samples=False, | ||
| # sequential_targets=["InklingAttention", "ExpertMLP"], | ||
| # sequential_targets_per_subgraph=(num_experts // 4 + 10), | ||
| ) | ||
| finally: | ||
| # if torch.distributed.get_rank() == 0: | ||
| # torch.cuda.memory._dump_snapshot("inkling_memory.pickle") | ||
| pass | ||
|
|
||
| # Save to disk compressed. | ||
| # Note: base checkpoint generation_config needs fixing for newer transformers versions | ||
| model.generation_config.top_p = None | ||
| SAVE_DIR = ( | ||
| "/mnt/nvme-data/engine/kylesayrs/" | ||
| + model_id.rstrip("/").split("/")[-1] | ||
| + "-NVFP4-FP8" | ||
| ) | ||
| model.save_pretrained(SAVE_DIR, save_compressed=True, save_original_format=False) | ||
| tokenizer.save_pretrained(SAVE_DIR) | ||
|
|
||
| torch.distributed.destroy_process_group() |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🚫 [linkspector] reported by reviewdog 🐶
Cannot reach https://huggingface.co/inference-optimization/Kimi-K3-0.18B Status: 401