text
stringlengths
5
631k
id
stringlengths
14
178
metadata
dict
__index_level_0__
int64
0
647
from transformers import BertTokenizerFast from .custom_tokenization import CustomTokenizer class CustomTokenizerFast(BertTokenizerFast): slow_tokenizer_class = CustomTokenizer pass
transformers/utils/test_module/custom_tokenization_fast.py/0
{ "file_path": "transformers/utils/test_module/custom_tokenization_fast.py", "repo_id": "transformers", "token_count": 54 }
600
- sections: - local: index title: TRL - local: installation title: Installation - local: quickstart title: Quickstart title: Getting started - sections: - local: dataset_formats title: Dataset Formats - local: paper_index title: Paper Index - local: how_to_train title: Training FAQ - local: logging title: Understanding Logs title: Conceptual Guides - sections: - local: clis title: Command Line Interface (CLI) - local: customization title: Customizing the Training - local: reducing_memory_usage title: Reducing Memory Usage - local: speeding_up_training title: Speeding Up Training - local: distributing_training title: Distributing Training - local: use_model title: Using Trained Models title: How-to guides - sections: - local: deepspeed_integration title: DeepSpeed - local: liger_kernel_integration title: Liger Kernel - local: peft_integration title: PEFT - local: unsloth_integration title: Unsloth - local: vllm_integration title: vLLM title: Integrations - sections: - local: example_overview title: Example Overview - local: community_tutorials title: Community Tutorials - local: sentiment_tuning title: Sentiment Tuning - local: using_llama_models title: Training StackLlama - local: detoxifying_a_lm title: Detoxifying a Language Model - local: multi_adapter_rl title: Multi Adapter RLHF title: Examples - sections: - sections: # Sorted alphabetically - local: alignprop_trainer title: AlignProp - local: bco_trainer title: BCO - local: cpo_trainer title: CPO - local: ddpo_trainer title: DDPO - local: dpo_trainer title: DPO - local: online_dpo_trainer title: Online DPO - local: gkd_trainer title: GKD - local: grpo_trainer title: GRPO - local: kto_trainer title: KTO - local: nash_md_trainer title: Nash-MD - local: orpo_trainer title: ORPO - local: ppo_trainer title: PPO - local: prm_trainer title: PRM - local: reward_trainer title: Reward - local: rloo_trainer title: RLOO - local: sft_trainer title: SFT - local: iterative_sft_trainer title: Iterative SFT - local: xpo_trainer title: XPO title: Trainers - local: models title: Model Classes - local: model_utils title: Model Utilities - local: best_of_n title: Best of N Sampling - local: judges title: Judges - local: callbacks title: Callbacks - local: data_utils title: Data Utilities - local: rewards title: Reward Functions - local: script_utils title: Script Utilities - local: others title: Others title: API
trl/docs/source/_toctree.yml/0
{ "file_path": "trl/docs/source/_toctree.yml", "repo_id": "trl", "token_count": 1067 }
601
# Use model after training Once you have trained a model using either the SFTTrainer, PPOTrainer, or DPOTrainer, you will have a fine-tuned model that can be used for text generation. In this section, we'll walk through the process of loading the fine-tuned model and generating text. If you need to run an inference server with the trained model, you can explore libraries such as [`text-generation-inference`](https://github.com/huggingface/text-generation-inference). ## Load and Generate If you have fine-tuned a model fully, meaning without the use of PEFT you can simply load it like any other language model in transformers. E.g. the value head that was trained during the PPO training is no longer needed and if you load the model with the original transformer class it will be ignored: ```python from transformers import AutoTokenizer, AutoModelForCausalLM model_name_or_path = "kashif/stack-llama-2" #path/to/your/model/or/name/on/hub device = "cpu" # or "cuda" if you have a GPU model = AutoModelForCausalLM.from_pretrained(model_name_or_path).to(device) tokenizer = AutoTokenizer.from_pretrained(model_name_or_path) inputs = tokenizer.encode("This movie was really", return_tensors="pt").to(device) outputs = model.generate(inputs) print(tokenizer.decode(outputs[0])) ``` Alternatively you can also use the pipeline: ```python from transformers import pipeline model_name_or_path = "kashif/stack-llama-2" #path/to/your/model/or/name/on/hub pipe = pipeline("text-generation", model=model_name_or_path) print(pipe("This movie was really")[0]["generated_text"]) ``` ## Use Adapters PEFT ```python from peft import PeftConfig, PeftModel from transformers import AutoModelForCausalLM, AutoTokenizer base_model_name = "kashif/stack-llama-2" #path/to/your/model/or/name/on/hub" adapter_model_name = "path/to/my/adapter" model = AutoModelForCausalLM.from_pretrained(base_model_name) model = PeftModel.from_pretrained(model, adapter_model_name) tokenizer = AutoTokenizer.from_pretrained(base_model_name) ``` You can also merge the adapters into the base model so you can use the model like a normal transformers model, however the checkpoint will be significantly bigger: ```python model = AutoModelForCausalLM.from_pretrained(base_model_name) model = PeftModel.from_pretrained(model, adapter_model_name) model = model.merge_and_unload() model.save_pretrained("merged_adapters") ``` Once you have the model loaded and either merged the adapters or keep them separately on top you can run generation as with a normal model outlined above.
trl/docs/source/use_model.md/0
{ "file_path": "trl/docs/source/use_model.md", "repo_id": "trl", "token_count": 778 }
602
# Copyright 2020-2025 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from trl import SFTTrainer class LayerSkipSFTTrainer(SFTTrainer): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.early_exit_layer = 0 # initialize with 0 self.always_last_layer = True self.early_exit_loss_scale = 1.0 def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None): self.early_exit_layer = ( self.early_exit_layer % (model.config.num_hidden_layers - 1) ) + 1 # rotates between [1, num_hidden_layers-1] bs, seqlen = inputs.input_ids.shape labels = inputs.pop("labels") outputs = model(**inputs, output_hidden_states=True) hidden_state = outputs["hidden_states"][self.early_exit_layer].to(model.dtype) if self.early_exit_layer != model.config.num_hidden_layers: hidden_state = model.model.norm(hidden_state) logits = model.lm_head(hidden_state) loss_early = model.loss_function(logits=logits, labels=labels, vocab_size=model.vocab_size) if self.always_last_layer: loss_last = model.loss_function(logits=outputs["logits"], labels=labels, vocab_size=model.vocab_size) loss = self.early_exit_loss_scale * loss_early.to(loss_last.device) + 1.0 * loss_last # normalize loss scales loss = loss / (1.0 + self.early_exit_loss_scale) else: loss = loss_early return loss
trl/examples/research_projects/layer_skip/scripts/custom_trainer.py/0
{ "file_path": "trl/examples/research_projects/layer_skip/scripts/custom_trainer.py", "repo_id": "trl", "token_count": 800 }
603
# Copyright 2020-2025 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # /// script # dependencies = [ # "trl @ git+https://github.com/huggingface/trl.git", # ] # /// """ Full training: python examples/scripts/prm.py \ --model_name_or_path Qwen/Qwen2-0.5B-Instruct \ --dataset_name trl-lib/prm800k \ --output_dir Qwen2-0.5B-Reward \ --per_device_train_batch_size 8 \ --num_train_epochs 1 \ --gradient_checkpointing True \ --learning_rate 1.0e-5 \ --eval_strategy steps \ --eval_steps 50 LoRA: python examples/scripts/prm.py \ --model_name_or_path Qwen/Qwen2-0.5B-Instruct \ --dataset_name trl-lib/prm800k \ --output_dir Qwen2-0.5B-Reward-LoRA \ --per_device_train_batch_size 8 \ --num_train_epochs 1 \ --gradient_checkpointing True \ --learning_rate 1.0e-4 \ --eval_strategy steps \ --eval_steps 50 --use_peft \ --lora_r 32 \ --lora_alpha 16 """ import torch from accelerate import logging from datasets import load_dataset from transformers import AutoModelForTokenClassification, AutoTokenizer, HfArgumentParser from trl import ( ModelConfig, PRMConfig, PRMTrainer, ScriptArguments, get_kbit_device_map, get_peft_config, get_quantization_config, ) logger = logging.get_logger(__name__) if __name__ == "__main__": parser = HfArgumentParser((ScriptArguments, PRMConfig, ModelConfig)) script_args, training_args, model_config = parser.parse_args_into_dataclasses() training_args.gradient_checkpointing_kwargs = dict(use_reentrant=False) ################ # Model & Tokenizer ################ torch_dtype = ( model_config.torch_dtype if model_config.torch_dtype in ["auto", None] else getattr(torch, model_config.torch_dtype) ) quantization_config = get_quantization_config(model_config) model_kwargs = dict( revision=model_config.model_revision, device_map=get_kbit_device_map() if quantization_config is not None else None, quantization_config=quantization_config, use_cache=False if training_args.gradient_checkpointing else True, ) tokenizer = AutoTokenizer.from_pretrained( model_config.model_name_or_path, trust_remote_code=model_config.trust_remote_code, use_fast=True ) model = AutoModelForTokenClassification.from_pretrained( model_config.model_name_or_path, num_labels=2, trust_remote_code=model_config.trust_remote_code, **model_kwargs ) # Align padding tokens between tokenizer and model model.config.pad_token_id = tokenizer.pad_token_id if model_config.use_peft and model_config.lora_task_type != "TOKEN_CLS": logger.warning( "You are using a `task_type` that is different than `TOKEN_CLS` for PEFT. This will lead to silent bugs" " Make sure to pass --lora_task_type TOKEN_CLS when using this script with PEFT.", ) ############## # Load dataset ############## dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config) dataset = dataset.filter(lambda x: len(x["completions"]) > 0) ########## # Training ########## trainer = PRMTrainer( model=model, processing_class=tokenizer, args=training_args, train_dataset=dataset[script_args.dataset_train_split], eval_dataset=dataset[script_args.dataset_test_split], peft_config=get_peft_config(model_config), ) trainer.train() ############################ # Save model and push to Hub ############################ trainer.save_model(training_args.output_dir) metrics = trainer.evaluate() trainer.log_metrics("eval", metrics) trainer.save_metrics("eval", metrics) # Save and push to hub trainer.save_model(training_args.output_dir) if training_args.push_to_hub: trainer.push_to_hub(dataset_name=script_args.dataset_name)
trl/examples/scripts/prm.py/0
{ "file_path": "trl/examples/scripts/prm.py", "repo_id": "trl", "token_count": 1727 }
604
# Copyright 2020-2025 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from dataclasses import dataclass, field from datasets import Dataset from transformers import HfArgumentParser from transformers.utils import get_json_schema @dataclass class ScriptArguments: r""" Arguments for the script. Args: test_size (`float`, *optional*, defaults to `0.1`): Fraction of the dataset to include in the test split. push_to_hub (`bool`, *optional*, defaults to `False`): Whether to push the dataset to the Hugging Face Hub. repo_id (`str`, *optional*, defaults to `"trl-internal-testing/zen"`): Hugging Face repository ID to push the dataset to. """ test_size: float = field( default=0.1, metadata={"help": "Fraction of the dataset to include in the test split."}, ) push_to_hub: bool = field( default=False, metadata={"help": "Whether to push the dataset to the Hugging Face Hub."}, ) repo_id: str = field( default="trl-internal-testing/toolcall", metadata={"help": "Hugging Face repository ID to push the dataset to."}, ) def main(test_size, push_to_hub, repo_id): # Fictitious functions to simulate tool calls def start_timer(duration: int) -> int: """ Starts a timer for the specified duration in seconds. Args: duration: Duration in seconds to set the timer for. Returns: The duration set for the timer. """ return duration def get_current_time(location: str) -> str: """ Returns the current time in the specified location. Args: location: The location for which to get the current time. Returns: The current time in the specified location. """ return "06:22:48" def get_air_quality_index(location: str) -> int: """ Returns the air quality index for the specified location. Args: location: The location for which to get the air quality index. Returns: The air quality index for the specified location. """ return 53 def play_music(title: str, artist: str) -> dict: """ Plays music by the specified title and artist. Args: title: The title of the music to play. artist: The artist of the music to play. Returns: A dictionary indicating the status of the music playback. """ return {"status": "Playing"} def get_weather_forecast(city: str, date: str) -> dict: """ Returns the weather forecast for the specified city and date. Args: city: The city for which to get the weather forecast. date: The date for which to get the weather forecast. Returns: A dictionary containing the temperature and weather condition. """ return {"temperature": 22, "condition": "partly cloudy"} def control_light(room: str, state: str) -> dict: """ Controls the light in the specified room. Args: room: The room where the light should be controlled. state: The desired state of the light ("on" or "off"). Returns: A dictionary indicating the state of the light. """ return {"state": state} def create_reminder(time: str, note: str) -> str: """ Creates a reminder for the specified time and note. Args: time: The time for the reminder. note: The note for the reminder. Returns: A confirmation message indicating that the reminder has been set. """ return "I'll remind you to call mom at 7 PM." def get_wind_conditions(city: str, unit: str) -> tuple[int, str]: """ Returns the wind conditions for the specified city. Args: city: The city for which to get the wind conditions. unit: The unit of measurement for the wind speed (e.g., "mph"). Returns: A tuple containing the wind speed and direction. """ return 14, "NW" start_timer = get_json_schema(start_timer) get_current_time = get_json_schema(get_current_time) get_air_quality_index = get_json_schema(get_air_quality_index) play_music = get_json_schema(play_music) get_weather_forecast = get_json_schema(get_weather_forecast) control_light = get_json_schema(control_light) create_reminder = get_json_schema(create_reminder) get_wind_conditions = get_json_schema(get_wind_conditions) # fmt: off dataset = Dataset.from_dict({ "messages": [ [ {"role": "user", "content": "Set a timer for 10 minutes."}, {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "start_timer", "arguments": {"duration": 600}}}]}, {"role": "tool", "name": "start_timer", "content": "600"}, {"role": "assistant", "content": "Timer set for 10 minutes."}, ], [ {"role": "user", "content": "What time is it in Tokyo?"}, {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "get_current_time", "arguments": {"location": "Tokyo"}}}]}, {"role": "tool", "name": "get_current_time", "content": "06:22:48"}, {"role": "assistant", "content": "The current time in Tokyo is 06:22 AM."}, ], [ {"role": "user", "content": "Is the air clean today in Lisbon?"}, {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "get_air_quality", "arguments": {"location": "Lisbon, Portugal"}}}]}, {"role": "tool", "name": "get_air_quality", "content": "53"}, {"role": "assistant", "content": "The air quality is moderate."}, ], [ {"role": "user", "content": "Play some music."}, {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "play_music", "arguments": {"title": "Take Five", "artist": "Dave Brubeck"}}}]}, {"role": "tool", "name": "play_music", "content": "{'status': 'Playing'}"}, {"role": "assistant", "content": "Enjoy the jazz tunes!"}, ], [ {"role": "user", "content": "What's the weather like tomorrow in Berlin?"}, {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "get_weather_forecast", "arguments": {"city": "Berlin", "date": "2025-06-16"}}}]}, {"role": "tool", "name": "get_weather_forecast", "content": "{'temperature': 22, 'condition': 'partly cloudy'}"}, {"role": "assistant", "content": "Tomorrow in Berlin will be partly cloudy with a high of 22°C."} ], [ {"role": "user", "content": "Turn on the living room lights."}, {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "control_light", "arguments": {"room": "living room", "state": "on"}}}]}, {"role": "tool", "name": "control_light", "content": "{'state': 'on'}"}, {"role": "assistant", "content": "The living room lights are now on."} ], [ {"role": "user", "content": "Remind me to call mom at 7 PM."}, {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "create_reminder", "arguments": {"time": "19:00", "note": "Call mom"}}}]}, {"role": "tool", "name": "create_reminder", "content": "Reminder set"}, {"role": "assistant", "content": "Okay, I’ll remind you to call mom at 7 PM."} ], [ {"role": "user", "content": "How strong is the wind in Chicago right now?"}, {"role": "assistant", "tool_calls": [{"type": "function", "function": {"name": "get_wind_conditions", "arguments": {"city": "Chicago", "unit": "mph"}}}]}, {"role": "tool", "name": "get_wind_conditions", "content": "(14, 'NW')"}, {"role": "assistant", "content": "The wind in Chicago is blowing at 14 mph from the northwest."} ] ], "tools": [ [start_timer, create_reminder], [get_current_time], [get_air_quality_index, get_weather_forecast, get_wind_conditions], [play_music, control_light], [get_weather_forecast, get_wind_conditions], [control_light], [start_timer, create_reminder], [get_weather_forecast, get_wind_conditions], ] }) dataset = dataset.train_test_split(test_size=test_size, shuffle=False) if push_to_hub: dataset.push_to_hub(repo_id) # fmt: on if __name__ == "__main__": parser = HfArgumentParser(ScriptArguments) script_args = parser.parse_args_into_dataclasses()[0] main(script_args.test_size, script_args.push_to_hub, script_args.repo_id)
trl/scripts/generate_toolcall_dataset.py/0
{ "file_path": "trl/scripts/generate_toolcall_dataset.py", "repo_id": "trl", "token_count": 4074 }
605
# Copyright 2020-2025 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import gc import pytest import torch from parameterized import parameterized from transformers.utils import is_peft_available from trl.import_utils import is_diffusers_available from .testing_utils import TrlTestCase, require_diffusers if is_diffusers_available() and is_peft_available(): from trl import AlignPropConfig, AlignPropTrainer, DefaultDDPOStableDiffusionPipeline def scorer_function(images, prompts, metadata): return torch.randn(1) * 3.0, {} def prompt_function(): return ("cabbages", {}) @pytest.mark.low_priority @require_diffusers class AlignPropTrainerTester(TrlTestCase): """ Test the AlignPropTrainer class. """ def setUp(self): super().setUp() training_args = AlignPropConfig( num_epochs=2, train_gradient_accumulation_steps=1, train_batch_size=2, truncated_backprop_rand=False, mixed_precision=None, save_freq=1000000, ) pretrained_model = "hf-internal-testing/tiny-stable-diffusion-torch" pretrained_revision = "main" pipeline_with_lora = DefaultDDPOStableDiffusionPipeline( pretrained_model, pretrained_model_revision=pretrained_revision, use_lora=True ) pipeline_without_lora = DefaultDDPOStableDiffusionPipeline( pretrained_model, pretrained_model_revision=pretrained_revision, use_lora=False ) self.trainer_with_lora = AlignPropTrainer(training_args, scorer_function, prompt_function, pipeline_with_lora) self.trainer_without_lora = AlignPropTrainer( training_args, scorer_function, prompt_function, pipeline_without_lora ) def tearDown(self) -> None: gc.collect() @parameterized.expand([True, False]) def test_generate_samples(self, use_lora): trainer = self.trainer_with_lora if use_lora else self.trainer_without_lora output_pairs = trainer._generate_samples(2, with_grad=True) self.assertEqual(len(output_pairs.keys()), 3) self.assertEqual(len(output_pairs["images"]), 2) @parameterized.expand([True, False]) def test_calculate_loss(self, use_lora): trainer = self.trainer_with_lora if use_lora else self.trainer_without_lora sample = trainer._generate_samples(2) images = sample["images"] prompts = sample["prompts"] self.assertTupleEqual(images.shape, (2, 3, 128, 128)) self.assertEqual(len(prompts), 2) rewards = trainer.compute_rewards(sample) loss = trainer.calculate_loss(rewards) self.assertTrue(torch.isfinite(loss.cpu()))
trl/tests/test_alignprop_trainer.py/0
{ "file_path": "trl/tests/test_alignprop_trainer.py", "repo_id": "trl", "token_count": 1265 }
606
# Copyright 2020-2025 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import time import unittest from trl import AllTrueJudge, HfPairwiseJudge, PairRMJudge from .testing_utils import RandomBinaryJudge, TrlTestCase, require_llm_blender class TestJudges(TrlTestCase): def _get_prompts_and_pairwise_completions(self): prompts = ["The capital of France is", "The biggest planet in the solar system is"] completions = [["Paris", "Marseille"], ["Saturn", "Jupiter"]] return prompts, completions def _get_prompts_and_single_completions(self): prompts = ["What's the capital of France?", "What's the color of the sky?"] completions = ["Marseille", "blue"] return prompts, completions def test_all_true_judge(self): judge = AllTrueJudge(judges=[RandomBinaryJudge(), RandomBinaryJudge()]) prompts, completions = self._get_prompts_and_single_completions() judgements = judge.judge(prompts=prompts, completions=completions) self.assertEqual(len(judgements), 2) self.assertTrue(all(judgement in {0, 1, -1} for judgement in judgements)) @unittest.skip("This test needs to be run manually since it requires a valid Hugging Face API key.") def test_hugging_face_judge(self): judge = HfPairwiseJudge() prompts, completions = self._get_prompts_and_pairwise_completions() ranks = judge.judge(prompts=prompts, completions=completions) self.assertEqual(len(ranks), 2) self.assertTrue(all(isinstance(rank, int) for rank in ranks)) self.assertEqual(ranks, [0, 1]) def load_pair_rm_judge(self): # When using concurrent tests, PairRM may fail to load the model while another job is still downloading. # This is a workaround to retry loading the model a few times. for _ in range(5): try: return PairRMJudge() except ValueError: time.sleep(5) raise ValueError("Failed to load PairRMJudge") @require_llm_blender def test_pair_rm_judge(self): judge = self.load_pair_rm_judge() prompts, completions = self._get_prompts_and_pairwise_completions() ranks = judge.judge(prompts=prompts, completions=completions) self.assertEqual(len(ranks), 2) self.assertTrue(all(isinstance(rank, int) for rank in ranks)) self.assertEqual(ranks, [0, 1]) @require_llm_blender def test_pair_rm_judge_return_scores(self): judge = self.load_pair_rm_judge() prompts, completions = self._get_prompts_and_pairwise_completions() probs = judge.judge(prompts=prompts, completions=completions, return_scores=True) self.assertEqual(len(probs), 2) self.assertTrue(all(isinstance(prob, float) for prob in probs)) self.assertTrue(all(0 <= prob <= 1 for prob in probs))
trl/tests/test_judges.py/0
{ "file_path": "trl/tests/test_judges.py", "repo_id": "trl", "token_count": 1303 }
607
# Copyright 2020-2025 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import textwrap from io import StringIO from unittest.mock import patch import numpy as np import torch from datasets import load_dataset from parameterized import parameterized from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig from transformers.testing_utils import require_peft from transformers.utils import is_peft_available from trl import ModelConfig from trl.trainer import compute_accuracy from trl.trainer.utils import ( DataCollatorForChatML, batch_generation, decode_and_strip_padding, entropy_from_logits, flush_left, flush_right, generate_model_card, get_peft_config, pad, print_prompt_completions_sample, selective_log_softmax, ) from .testing_utils import TrlTestCase, require_rich if is_peft_available(): from peft import LoraConfig class TestPad(TrlTestCase): def test_pad_1_dim_left(self): x = torch.tensor([1, 2, 3]) y = torch.tensor([4, 5]) output = pad((x, y), padding_value=0, padding_side="left") expected = torch.tensor([[1, 2, 3], [0, 4, 5]]) self.assertTrue(torch.equal(output, expected)) def test_pad_1_dim_right(self): x = torch.tensor([1, 2, 3]) y = torch.tensor([4, 5]) output = pad((x, y), padding_value=0, padding_side="right") expected = torch.tensor([[1, 2, 3], [4, 5, 0]]) self.assertTrue(torch.equal(output, expected)) def test_pad_2_dim_left(self): x = torch.tensor([[1, 2], [3, 4]]) y = torch.tensor([[5, 6]]) output = pad((x, y), padding_value=0, padding_side="left") expected = torch.tensor( [ [[1, 2], [3, 4]], [[0, 0], [5, 6]], ] ) self.assertTrue(torch.equal(output, expected)) def test_pad_2_dim_right(self): x = torch.tensor([[1, 2], [3, 4]]) y = torch.tensor([[5, 6]]) output = pad((x, y), padding_value=0, padding_side="right") expected = torch.tensor( [ [[1, 2], [3, 4]], [[5, 6], [0, 0]], ] ) self.assertTrue(torch.equal(output, expected)) def test_pad_2_dim_right_multidim(self): x = torch.tensor([[1, 2], [3, 4]]) y = torch.tensor([[5]]) output = pad((x, y), padding_value=0, padding_side="right") expected = torch.tensor( [ [[1, 2], [3, 4]], [[5, 0], [0, 0]], ] ) self.assertTrue(torch.equal(output, expected)) def test_pad_to_multiple_of_1(self): x = torch.tensor([1, 2, 3]) y = torch.tensor([4, 5]) # Max length is 3, pad to multiple of 4 output = pad((x, y), padding_value=0, padding_side="right", pad_to_multiple_of=4) expected = torch.tensor([[1, 2, 3, 0], [4, 5, 0, 0]]) self.assertTrue(torch.equal(output, expected)) def test_pad_to_multiple_of_2(self): x = torch.tensor([1, 2, 3, 4, 5]) y = torch.tensor([6, 7, 8]) # Max length is 3, pad to multiple of 4 output = pad((x, y), padding_value=0, padding_side="right", pad_to_multiple_of=4) expected = torch.tensor([[1, 2, 3, 4, 5, 0, 0, 0], [6, 7, 8, 0, 0, 0, 0, 0]]) self.assertTrue(torch.equal(output, expected)) def test_pad_to_multiple_of_side_left(self): x = torch.tensor([1, 2, 3, 4, 5]) y = torch.tensor([6, 7, 8]) # Max length is 3, pad to multiple of 4 output = pad((x, y), padding_value=0, padding_side="left", pad_to_multiple_of=4) expected = torch.tensor([[0, 0, 0, 1, 2, 3, 4, 5], [0, 0, 0, 0, 0, 6, 7, 8]]) self.assertTrue(torch.equal(output, expected)) def test_pad_to_multiple_of_no_extra_padding(self): x = torch.tensor([1, 2, 3, 4]) y = torch.tensor([5, 6, 7, 8]) # Already multiple of 4 output = pad((x, y), padding_value=0, padding_side="left", pad_to_multiple_of=4) expected = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]]) self.assertTrue(torch.equal(output, expected)) @require_peft class TestGetPEFTConfig(TrlTestCase): def test_create_peft_config_use_peft_false(self): """Test that when use_peft is False, the function returns None.""" model_args = ModelConfig(use_peft=False) peft_config = get_peft_config(model_args) self.assertIsNone(peft_config) def test_create_peft_config_use_peft_true(self): """Test that when use_peft is True, the function returns a LoraConfig object.""" # Provide non-default values to the model config for testing peft_kwargs = { "lora_r": 8, "lora_alpha": 16, "lora_dropout": 0.1, "lora_task_type": "SEQ_CLS", "use_rslora": True, "lora_target_modules": ["up_proj", "down_proj"], "lora_modules_to_save": ["up_proj"], } model_args = ModelConfig(use_peft=True, **peft_kwargs) peft_config = get_peft_config(model_args) self.assertTrue(isinstance(peft_config, LoraConfig)) for arg, value in peft_kwargs.items(): # Test that lists of modules are converted to sets if arg == "lora_target_modules": value = set(value) # Rename the argument to match the LoraConfig attribute name if arg in ["lora_r", "lora_task_type", "lora_target_modules", "lora_modules_to_save"]: arg = arg[len("lora_") :] if arg.startswith("lora_") else arg self.assertEqual(getattr(peft_config, arg), value) class TestDecodeAndStripPadding(TrlTestCase): def setUp(self): super().setUp() self.tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5") def test_example_with_padding(self): inputs = self.tokenizer(["Hello world", "Hello"], padding=True, return_tensors="pt") decoded = decode_and_strip_padding(inputs["input_ids"], self.tokenizer) self.assertEqual(decoded, ["Hello world", "Hello"]) def test_example_without_padding(self): inputs = self.tokenizer(["Hello", "Hello"], padding=False, return_tensors="pt") decoded = decode_and_strip_padding(inputs["input_ids"], self.tokenizer) self.assertEqual(decoded, ["Hello", "Hello"]) class TestGenerateModelCard(TrlTestCase): def test_full(self): model_card = generate_model_card( base_model="username/my_base_model", model_name="my_model", hub_model_id="username/my_hub_model", dataset_name="username/my_dataset", tags=["trl", "trainer-tag"], wandb_url="https://wandb.ai/username/project_id/runs/abcd1234", comet_url="https://www.comet.com/username/project_id/experiment_id", trainer_name="My Trainer", trainer_citation="@article{my_trainer, ...}", paper_title="My Paper", paper_id="1234.56789", ) card_text = str(model_card) self.assertIn("[username/my_base_model](https://huggingface.co/username/my_base_model)", card_text) self.assertIn("my_model", card_text) self.assertIn('pipeline("text-generation", model="username/my_hub_model", device="cuda")', card_text) self.assertIn("datasets: username/my_dataset", card_text) self.assertIn("](https://wandb.ai/username/project_id/runs/abcd1234)", card_text) self.assertIn("](https://www.comet.com/username/project_id/experiment_id", card_text) self.assertIn("My Trainer", card_text) self.assertIn("```bibtex\n@article{my_trainer, ...}\n```", card_text) self.assertIn("[My Paper](https://huggingface.co/papers/1234.56789)", card_text) def test_val_none(self): model_card = generate_model_card( base_model=None, model_name="my_model", hub_model_id="username/my_hub_model", dataset_name=None, tags=[], wandb_url=None, comet_url=None, trainer_name="My Trainer", trainer_citation=None, paper_title=None, paper_id=None, ) card_text = str(model_card) self.assertIn("my_model", card_text) self.assertIn('pipeline("text-generation", model="username/my_hub_model", device="cuda")', card_text) self.assertIn("My Trainer", card_text) class TestDataCollatorForChatML(TrlTestCase): def setUp(self): super().setUp() # Initialize the tokenizer self.tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5") if self.tokenizer.pad_token is None: self.tokenizer.pad_token = self.tokenizer.eos_token # Define token IDs self.bos_token_id = self.tokenizer.bos_token_id if self.tokenizer.bos_token_id is not None else 1 self.eos_token_id = self.tokenizer.eos_token_id if self.tokenizer.eos_token_id is not None else 2 # Token ID for "true", the last assistant's response in the example: self.ignore_index = -100 self.max_length = 1024 self.messages_key = "messages" # Example input dataset = load_dataset("trl-internal-testing/zen", "conversational_language_modeling", split="train") self.examples = dataset.to_list() # Initialize the data collator self.collator = DataCollatorForChatML( tokenizer=self.tokenizer, max_length=self.max_length, ignore_index=self.ignore_index, ) def test_data_collator_for_chatml(self): # Process the data data = self.collator(self.examples) # Verify basic shapes and types self.assertIn("input_ids", data) self.assertIn("attention_mask", data) self.assertIn("labels", data) self.assertIn("prompts", data) self.assertIn("prompt_attention_mask", data) # Decode input_ids and labels for verification input_ids = data["input_ids"][0].tolist() labels = data["labels"][0].tolist() prompt_only = data["prompts"][0].tolist() # Get the last assistant's response for comparison last_message = self.examples[0][self.messages_key][-1] self.assertEqual(last_message["role"], "assistant", "Last message should be from assistant") last_assistant_response = last_message["content"] # Verify that input_ids contain both prompt and response decoded_input = self.tokenizer.decode(input_ids) self.assertIn(last_assistant_response, decoded_input, "Input should contain assistant's response") # Verify that prompts only contain the conversation up to the last response decoded_prompt = self.tokenizer.decode(prompt_only) self.assertNotIn(last_assistant_response, decoded_prompt, "Prompt should not contain assistant's response") # Verify labels are -100 for non-assistant parts prompt_length = len(prompt_only) self.assertTrue( all(label == self.ignore_index for label in labels[:prompt_length]), "Labels should be ignore_index for prompt tokens", ) # Verify labels match assistant response after prompt # Add a filter to remove any trailing tokens after the first <|im_end|> last_assistant_response_with_end = last_assistant_response + self.tokenizer.eos_token last_assistant_response_tokens = self.tokenizer.encode( last_assistant_response_with_end, add_special_tokens=False ) response_labels = [] for label in labels[prompt_length:]: if label == self.ignore_index: continue response_labels.append(label) if label == self.tokenizer.convert_tokens_to_ids("<|im_end|>"): break self.assertEqual( response_labels, last_assistant_response_tokens, "Labels should match assistant response tokens", ) # Verify there isn't a generation prompt at the end generation_prompt = "<|im_start|>assistant" self.assertFalse( decoded_input.strip().endswith(generation_prompt), f"Input should not end with generation prompt '{generation_prompt}'", ) self.assertEqual( response_labels, last_assistant_response_tokens, "Labels should match assistant response tokens", ) class TestBatchGeneration(TrlTestCase): def setUp(self): super().setUp() # Initialize the tokenizer self.model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" self.model = AutoModelForCausalLM.from_pretrained(self.model_id) self.tokenizer = AutoTokenizer.from_pretrained(self.model_id) self.generation_config = GenerationConfig( max_new_tokens=128, temperature=0.5, do_sample=True, top_k=0, pad_token_id=self.tokenizer.pad_token_id, ) # Example input dataset = load_dataset("trl-internal-testing/zen", "conversational_language_modeling", split="train") self.examples = dataset["messages"] self.mini_batch_size = 3 def test_mini_batch_generation(self): batch = [ self.tokenizer.apply_chat_template(example[:-1], add_generation_prompt=True, tokenize=False) for example in self.examples ] queries = self.tokenizer(batch, padding=True, return_tensors="pt")["input_ids"] bs, context_length = queries.shape query_responses, logits = batch_generation( self.model, queries, self.mini_batch_size, self.tokenizer.pad_token_id, self.generation_config ) max_length_query = query_responses.shape[1] max_length_logits = max_length_query - context_length self.assertGreater(max_length_query, context_length) self.assertEqual(query_responses.shape, (bs, max_length_query)) self.assertEqual(logits.shape, (bs, max_length_logits, self.model.config.vocab_size)) def test_single_batch_generation(self): batch = [ self.tokenizer.apply_chat_template(example[:-1], add_generation_prompt=True, tokenize=False) for example in self.examples ] queries = self.tokenizer(batch, padding=True, return_tensors="pt")["input_ids"] bs, context_length = queries.shape query_responses, logits = batch_generation( self.model, queries, bs, self.tokenizer.pad_token_id, self.generation_config ) max_length_query = query_responses.shape[1] max_length_logits = max_length_query - context_length self.assertGreater(max_length_query, context_length) self.assertEqual(query_responses.shape, (bs, max_length_query)) self.assertEqual(logits.shape, (bs, max_length_logits, self.model.config.vocab_size)) class TestComputeAccuracy(TrlTestCase): def test_token_classification_task(self): eval_pred = ( np.array( [ [[0.1, 0.9], [0.8, 0.2]], # Batch 1 [[0.3, 0.7], [0.6, 0.4]], # Batch 2 ] ), np.array([[0, 1], [1, 0]]), ) expected_accuracy = 0.5 # 2 matches, 2 mismatches result = compute_accuracy(eval_pred) self.assertAlmostEqual(result["accuracy"], expected_accuracy) def test_token_classification_task_with_ignored_tokens_0(self): eval_pred = ( np.array( [ [[0.1, 0.9], [0.8, 0.2]], # Batch 1 [[0.3, 0.7], [0.6, 0.4]], # Batch 2 ] ), np.array([[1, 0], [1, -100]]), ) expected_accuracy = 1.0 # All non-ignored tokens match result = compute_accuracy(eval_pred) self.assertAlmostEqual(result["accuracy"], expected_accuracy) def test_token_classification_task_with_ignored_tokens_1(self): eval_pred = ( np.array( [ [[0.1, 0.9], [0.8, 0.2]], # Batch 1 [[0.3, 0.7], [0.6, 0.4]], # Batch 2 ] ), np.array([[1, 1], [0, -100]]), ) expected_accuracy = 1 / 3 # 1 match, 2 mismatch, 1 ignored result = compute_accuracy(eval_pred) self.assertAlmostEqual(result["accuracy"], expected_accuracy) def test_rewards_comparison_task(self): eval_pred = ( np.array( [ [0.9, 0.1], # Batch 1 [0.6, 0.4], # Batch 2 [0.5, 0.5], # Batch 3 (equal) ] ), np.array([0, 1, 1]), ) expected_accuracy = 0.5 # 1 match, 1 mismatch, 1 equal (ignored) with self.assertLogs("trl.trainer.utils", level="WARNING") as cm: result = compute_accuracy(eval_pred) self.assertAlmostEqual(result["accuracy"], expected_accuracy) expected_warning = ( "There are 1 out of 3 instances where the predictions for both options are equal. " "These instances are ignored in the accuracy computation." ) self.assertIn(expected_warning, cm.output[0]) class TestFlushLeft(TrlTestCase): def test_basic_case(self): mask = torch.tensor([[0, 0, 1, 1, 1], [0, 1, 1, 0, 0]]) tensor1 = torch.tensor([[0, 0, 2, 3, 4], [0, 5, 6, 0, 0]]) tensor2 = torch.tensor([[0, 0, 7, 8, 9], [0, 10, 11, 0, 0]]) new_mask, new_tensor1, new_tensor2 = flush_left(mask, tensor1, tensor2) expected_mask = torch.tensor([[1, 1, 1], [1, 1, 0]]) expected_tensor1 = torch.tensor([[2, 3, 4], [5, 6, 0]]) expected_tensor2 = torch.tensor([[7, 8, 9], [10, 11, 0]]) self.assertTrue(torch.equal(new_mask, expected_mask)) self.assertTrue(torch.equal(new_tensor1, expected_tensor1)) self.assertTrue(torch.equal(new_tensor2, expected_tensor2)) def test_single_row(self): mask = torch.tensor([[0, 0, 1, 1]]) tensor1 = torch.tensor([[0, 0, 2, 3]]) new_mask, new_tensor1 = flush_left(mask, tensor1) expected_mask = torch.tensor([[1, 1]]) expected_tensor1 = torch.tensor([[2, 3]]) self.assertTrue(torch.equal(new_mask, expected_mask)) self.assertTrue(torch.equal(new_tensor1, expected_tensor1)) def test_no_shift_needed(self): mask = torch.tensor([[1, 1, 0, 0], [1, 0, 0, 0]]) tensor1 = torch.tensor([[5, 6, 0, 0], [7, 0, 0, 0]]) new_mask, new_tensor1 = flush_left(mask, tensor1) expected_mask = torch.tensor([[1, 1], [1, 0]]) expected_tensor1 = torch.tensor([[5, 6], [7, 0]]) self.assertTrue(torch.equal(new_mask, expected_mask)) self.assertTrue(torch.equal(new_tensor1, expected_tensor1)) def test_no_tensors(self): mask = torch.tensor([[0, 0, 1, 1, 1], [0, 1, 1, 0, 0]]) new_mask = flush_left(mask) expected_mask = torch.tensor([[1, 1, 1], [1, 1, 0]]) self.assertTrue(torch.equal(new_mask, expected_mask)) class TestFlushRight(TrlTestCase): def test_basic_case(self): mask = torch.tensor([[1, 1, 1, 0, 0], [0, 0, 1, 1, 0]]) tensor1 = torch.tensor([[2, 3, 4, 0, 0], [0, 0, 5, 6, 0]]) tensor2 = torch.tensor([[7, 8, 9, 0, 0], [0, 0, 10, 11, 0]]) new_mask, new_tensor1, new_tensor2 = flush_right(mask, tensor1, tensor2) expected_mask = torch.tensor([[1, 1, 1], [0, 1, 1]]) expected_tensor1 = torch.tensor([[2, 3, 4], [0, 5, 6]]) expected_tensor2 = torch.tensor([[7, 8, 9], [0, 10, 11]]) self.assertTrue(torch.equal(new_mask, expected_mask)) self.assertTrue(torch.equal(new_tensor1, expected_tensor1)) self.assertTrue(torch.equal(new_tensor2, expected_tensor2)) def test_single_row(self): mask = torch.tensor([[1, 1, 0, 0]]) tensor1 = torch.tensor([[2, 3, 0, 0]]) new_mask, new_tensor1 = flush_right(mask, tensor1) expected_mask = torch.tensor([[1, 1]]) expected_tensor1 = torch.tensor([[2, 3]]) self.assertTrue(torch.equal(new_mask, expected_mask)) self.assertTrue(torch.equal(new_tensor1, expected_tensor1)) def test_no_shift_needed(self): mask = torch.tensor([[0, 0, 1, 1], [0, 0, 0, 1]]) tensor1 = torch.tensor([[0, 0, 5, 6], [0, 0, 0, 7]]) new_mask, new_tensor1 = flush_right(mask, tensor1) expected_mask = torch.tensor([[1, 1], [0, 1]]) expected_tensor1 = torch.tensor([[5, 6], [0, 7]]) self.assertTrue(torch.equal(new_mask, expected_mask)) self.assertTrue(torch.equal(new_tensor1, expected_tensor1)) def test_no_tensors(self): mask = torch.tensor([[1, 1, 1, 0, 0], [0, 0, 1, 1, 0]]) new_mask = flush_right(mask) expected_mask = torch.tensor([[1, 1, 1], [0, 1, 1]]) self.assertTrue(torch.equal(new_mask, expected_mask)) class TestSelectiveLogSoftmax(TrlTestCase): @parameterized.expand([(torch.float64,), (torch.float32,), (torch.float16,), (torch.bfloat16,)]) def test_selective_log_softmax(self, dtype): """Test selective_log_softmax with logits of different dtypes""" vocab_size = 1024 batch_size = 4 seq_len = 32 input_ids = torch.randint(low=0, high=vocab_size, size=(batch_size, seq_len)) logits = torch.randn(batch_size, seq_len, vocab_size, dtype=dtype) expected_output = torch.gather(logits.log_softmax(-1), dim=-1, index=input_ids.unsqueeze(-1)).squeeze(-1) actual_output = selective_log_softmax(logits, input_ids) if dtype in [torch.float16, torch.bfloat16]: # half-precision dtypes fall back to an exact method self.assertTrue(torch.equal(actual_output, expected_output)) else: torch.testing.assert_close(actual_output, expected_output, rtol=1e-5, atol=1e-5) @require_rich class TestPrintPromptCompletionsSample(TrlTestCase): @patch("sys.stdout", new_callable=StringIO) def test_print_output(self, mock_stdout): prompts = ["The sky is", "The sun is"] completions = [" blue.", " in the sky."] rewards = {"Correctness": [0.123, 0.456], "Format": [0.789, 0.101]} advantages = [0.987, 0.654] step = 42 print_prompt_completions_sample(prompts, completions, rewards, advantages, step) output = mock_stdout.getvalue() # docstyle-ignore expected_output = textwrap.dedent("""\ ╭──────────────────────────── Step 42 ─────────────────────────────╮ │ ┏━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━┓ │ │ ┃ Prompt ┃ Completion ┃ Correctness ┃ Format ┃ Advantage ┃ │ │ ┡━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━┩ │ │ │ The sky is │ blue. │ 0.12 │ 0.79 │ 0.99 │ │ │ ├────────────┼──────────────┼─────────────┼────────┼───────────┤ │ │ │ The sun is │ in the sky. │ 0.46 │ 0.10 │ 0.65 │ │ │ └────────────┴──────────────┴─────────────┴────────┴───────────┘ │ ╰──────────────────────────────────────────────────────────────────╯ """) self.assertEqual(output, expected_output) @patch("sys.stdout", new_callable=StringIO) def test_num_samples(self, mock_stdout): prompts = ["A", "B"] completions = ["1", "2"] rewards = {"Score": [0.1, 0.2]} advantages = [0.3, 0.4] step = 10 print_prompt_completions_sample(prompts, completions, rewards, advantages, step, num_samples=1) output = mock_stdout.getvalue() # docstyle-ignore possible_outputs = [ textwrap.dedent("""\ ╭────────────────── Step 10 ──────────────────╮ │ ┏━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┓ │ │ ┃ Prompt ┃ Completion ┃ Score ┃ Advantage ┃ │ │ ┡━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━┩ │ │ │ A │ 1 │ 0.10 │ 0.30 │ │ │ └────────┴────────────┴───────┴───────────┘ │ ╰─────────────────────────────────────────────╯ """), # docstyle-ignore textwrap.dedent("""\ ╭────────────────── Step 10 ──────────────────╮ │ ┏━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━━━┓ │ │ ┃ Prompt ┃ Completion ┃ Score ┃ Advantage ┃ │ │ ┡━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━━━┩ │ │ │ B │ 2 │ 0.20 │ 0.40 │ │ │ └────────┴────────────┴───────┴───────────┘ │ ╰─────────────────────────────────────────────╯ """), ] self.assertIn(output, possible_outputs) class TestEntropyFromLogits(TrlTestCase): @parameterized.expand( [ (dtype, chunk_size) for dtype in (torch.float64, torch.float32, torch.float16, torch.bfloat16) for chunk_size in (1, 16) ] ) def test_entropy_from_logits(self, dtype, chunk_size): batch_size, seq_len, vocab_size = 64, 384, 768 logits = torch.randn(batch_size, seq_len, vocab_size, dtype=dtype) if dtype in (torch.float64, torch.float32): p = logits.softmax(-1) entropy = -torch.sum(p * p.log(), dim=-1) else: logps = logits.log_softmax(dim=-1) entropy = -(torch.exp(logps) * logps).sum(-1) predicted_entropy = entropy_from_logits(logits, chunk_size=chunk_size) torch.testing.assert_close(predicted_entropy, entropy, rtol=1e-5, atol=1e-5)
trl/tests/test_utils.py/0
{ "file_path": "trl/tests/test_utils.py", "repo_id": "trl", "token_count": 12515 }
608
# Copyright 2020-2025 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys from typing import TYPE_CHECKING from ..import_utils import _LazyModule _import_structure = { "format_rewards": ["think_format_reward"], "other_rewards": ["get_soft_overlong_punishment"], } if TYPE_CHECKING: from .format_rewards import think_format_reward from .other_rewards import get_soft_overlong_punishment else: sys.modules[__name__] = _LazyModule(__name__, __file__, _import_structure, module_spec=__spec__)
trl/trl/rewards/__init__.py/0
{ "file_path": "trl/trl/rewards/__init__.py", "repo_id": "trl", "token_count": 322 }
609
# Copyright 2020-2025 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import inspect import os import random import textwrap from collections import defaultdict from contextlib import contextmanager, nullcontext from operator import itemgetter from pathlib import Path from typing import TYPE_CHECKING, Any, Callable, Literal, Optional, Union import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F from accelerate import PartialState, logging from accelerate.utils import tqdm from datasets import Dataset from torch import autocast from torch.utils.data import DataLoader, SequentialSampler from transformers import ( AutoModelForCausalLM, BaseImageProcessor, DataCollator, FeatureExtractionMixin, PreTrainedModel, PreTrainedTokenizerBase, ProcessorMixin, Trainer, TrainingArguments, is_comet_available, is_sklearn_available, is_wandb_available, ) from transformers.trainer_callback import TrainerCallback from transformers.trainer_utils import EvalLoopOutput, has_length from transformers.utils import is_peft_available from ..data_utils import maybe_apply_chat_template, maybe_extract_prompt, maybe_unpair_preference_dataset from ..import_utils import is_joblib_available from ..models import create_reference_model, prepare_deepspeed from .bco_config import BCOConfig from .utils import ( DPODataCollatorWithPadding, RunningMoments, disable_dropout_in_model, generate_model_card, get_comet_experiment_url, log_table_to_comet_experiment, pad_to_length, peft_module_casting_to_bf16, selective_log_softmax, ) if is_peft_available(): from peft import PeftModel, get_peft_model, prepare_model_for_kbit_training if is_wandb_available(): import wandb if is_sklearn_available(): from sklearn.linear_model import LogisticRegression if is_joblib_available(): import joblib if TYPE_CHECKING: from transformers import PreTrainedTokenizer logger = logging.get_logger(__name__) RUNNING_NAME = "running.json" CLF_NAME = "clf.pkl" def _tokenize( batch: dict[str, list[Any]], tokenizer: "PreTrainedTokenizer", embedding_tokenizer: Optional["PreTrainedTokenizer"] = None, ) -> dict[str, list[Any]]: """Tokenize a batch from a BCO specific dataset.""" prompt_tokenized = tokenizer(batch["prompt"], add_special_tokens=False) prompt_input_ids = prompt_tokenized["input_ids"] prompt_attention_mask = prompt_tokenized["attention_mask"] prompt_and_completion = [prompt + completion for prompt, completion in zip(batch["prompt"], batch["completion"])] full_tokenized = tokenizer(prompt_and_completion, add_special_tokens=False) full_input_ids = full_tokenized["input_ids"] full_attention_mask = full_tokenized["attention_mask"] answer_input_ids = [f[len(p) :] for f, p in zip(full_input_ids, prompt_input_ids)] answer_attention_mask = [f[len(p) :] for f, p in zip(full_attention_mask, prompt_attention_mask)] # Concat tokens to form `enc(a) + enc(a + b)[len(enc(a)):]` full_concat_input_ids = [np.concatenate([p, a]) for p, a in zip(prompt_input_ids, answer_input_ids)] # Prepare input tokens for token by token comparison full_input_ids = [np.array(f) for f in full_input_ids] for full, concat in zip(full_input_ids, full_concat_input_ids): if len(full) != len(concat): raise ValueError( "The elements in 'full_input_ids' and 'full_concat_input_ids' must have the same pairwise length." ) # On some tokenizers, like Llama-2 tokenizer, there are occasions where tokens # can be merged together when tokenizing prompt+answer. This could result # on the last token from the prompt being different when tokenized on its own # vs when done as prompt+answer. response_token_ids_start_idx = [len(p) for p in prompt_input_ids] # If tokenized prompt is different than both prompt+answer, then it means the # last token has changed due to merging. for idx, (p, f, r) in enumerate(zip(prompt_input_ids, full_input_ids, response_token_ids_start_idx)): if not np.array_equal(p, f[:r]): response_token_ids_start_idx[idx] -= 1 prompt_input_ids = [f[:r] for f, r in zip(full_input_ids, response_token_ids_start_idx)] prompt_attention_mask = [f[:r] for f, r in zip(full_attention_mask, response_token_ids_start_idx)] for p, m in zip(prompt_input_ids, prompt_attention_mask): if len(p) != len(m): raise ValueError("Prompt input ids and attention mask should have the same length.") answer_input_ids = [f[r:] for f, r in zip(full_input_ids, response_token_ids_start_idx)] answer_attention_mask = [f[r:] for f, r in zip(full_attention_mask, response_token_ids_start_idx)] output = dict( prompt_input_ids=prompt_input_ids, prompt_attention_mask=prompt_attention_mask, answer_input_ids=answer_input_ids, answer_attention_mask=answer_attention_mask, ) if embedding_tokenizer is not None: embedding_tokenized = embedding_tokenizer(batch["prompt"], truncation=True, add_special_tokens=False) output.update( { "embedding_input_ids": embedding_tokenized["input_ids"], "embedding_attention_mask": embedding_tokenized["attention_mask"], } ) return output def _process_tokens(example: dict[str, Any], model: "PreTrainedModel" = None, **kwargs) -> dict: """Process tokens of a BCO specific dataset. At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation in case the prompt + completion responses is/are too long. First we truncate the prompt; if we're still too long, we truncate the completion. We also create the labels for the completion responses, which are of length equal to the sum of the length of the prompt and the completion response, with label_pad_token_id for the prompt tokens. """ prompt = example["prompt"] completion = example["completion"] batch = { f"{kwargs['prefix']}prompt": prompt, f"{kwargs['prefix']}completion": completion, f"{kwargs['prefix']}label": example["label"], } if not kwargs["is_encoder_decoder"]: # Check issues below for more details # 1. https://github.com/huggingface/trl/issues/907 # 2. https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257 # 3. https://github.com/LianjiaTech/BELLE/issues/337 if not isinstance(prompt, str): raise ValueError(f"prompt should be an str but got {type(prompt)}") if not isinstance(completion, str): raise ValueError(f"completion should be an str but got {type(completion)}") # keys of format prompt_* refers to just the prompt and answer_* refers to just the answer all_tokens = { "prompt_input_ids": example["prompt_input_ids"], "prompt_attention_mask": example["prompt_attention_mask"], "answer_input_ids": example["answer_input_ids"], "answer_attention_mask": example["answer_attention_mask"], } # calculate max length by checking if BOS/EOS is already there max_length = kwargs["max_length"] bos_token_id = kwargs["tokenizer"].bos_token_id eos_token_id = kwargs["tokenizer"].eos_token_id if bos_token_id != all_tokens["prompt_input_ids"][0]: max_length -= 1 if eos_token_id != all_tokens["answer_input_ids"][-1]: max_length -= 1 # if combined sequence is too long (> max_length - 1 for BOS token - 1 for EOS), truncate the prompt if len(all_tokens["prompt_input_ids"]) + len(all_tokens["answer_input_ids"]) > max_length: for k in ["prompt_input_ids", "prompt_attention_mask"]: if kwargs["truncation_mode"] == "keep_start": all_tokens[k] = all_tokens[k][: kwargs["max_prompt_length"]] elif kwargs["truncation_mode"] == "keep_end": all_tokens[k] = all_tokens[k][-kwargs["max_prompt_length"] :] else: raise ValueError(f"Unknown truncation mode: {kwargs['truncation_mode']}") # if that's still too long, truncate the response if len(all_tokens["prompt_input_ids"]) + len(all_tokens["answer_input_ids"]) > max_length: for k in ["answer_input_ids", "answer_attention_mask"]: all_tokens[k] = all_tokens[k][: max_length - kwargs["max_prompt_length"]] # all input_ids and attention mask as is. We then check if we need to add BOS/EOS tokens batch[f"{kwargs['prefix']}prompt_input_ids"] = all_tokens["prompt_input_ids"] batch[f"{kwargs['prefix']}prompt_attention_mask"] = all_tokens["prompt_attention_mask"] batch[f"{kwargs['prefix']}completion_input_ids"] = ( all_tokens["prompt_input_ids"] + all_tokens["answer_input_ids"] ) batch[f"{kwargs['prefix']}completion_attention_mask"] = ( all_tokens["prompt_attention_mask"] + all_tokens["answer_attention_mask"] ) # add BOS, which affects both prompt and the full completion if bos_token_id is not None: if len(all_tokens["prompt_input_ids"]) == 0 or bos_token_id != all_tokens["prompt_input_ids"][0]: batch[f"{kwargs['prefix']}prompt_input_ids"] = [bos_token_id] + batch[ f"{kwargs['prefix']}prompt_input_ids" ] batch[f"{kwargs['prefix']}prompt_attention_mask"] = [1] + batch[ f"{kwargs['prefix']}prompt_attention_mask" ] batch[f"{kwargs['prefix']}completion_input_ids"] = [bos_token_id] + batch[ f"{kwargs['prefix']}completion_input_ids" ] batch[f"{kwargs['prefix']}completion_attention_mask"] = [1] + batch[ f"{kwargs['prefix']}completion_attention_mask" ] # add EOS, which affects only the full completion if len(all_tokens["answer_input_ids"]) == 0 or eos_token_id != all_tokens["answer_input_ids"][-1]: batch[f"{kwargs['prefix']}completion_input_ids"] = batch[f"{kwargs['prefix']}completion_input_ids"] + [ eos_token_id ] batch[f"{kwargs['prefix']}completion_attention_mask"] = batch[ f"{kwargs['prefix']}completion_attention_mask" ] + [1] batch[f"{kwargs['prefix']}completion_labels"] = batch[f"{kwargs['prefix']}completion_input_ids"][:] batch[f"{kwargs['prefix']}completion_labels"][: len(batch[f"{kwargs['prefix']}prompt_input_ids"])] = [ kwargs["label_pad_token_id"] ] * len(batch[f"{kwargs['prefix']}prompt_input_ids"]) else: completion_tokens = kwargs["tokenizer"]( completion, truncation=True, max_length=kwargs["max_completion_length"], add_special_tokens=True ) prompt_tokens = kwargs["tokenizer"]( prompt, truncation=True, max_length=kwargs["max_prompt_length"], add_special_tokens=True ) batch[f"{kwargs['prefix']}prompt_input_ids"] = prompt_tokens["input_ids"] batch[f"{kwargs['prefix']}prompt_attention_mask"] = prompt_tokens["attention_mask"] batch[f"{kwargs['prefix']}completion_labels"] = completion_tokens["input_ids"] batch[f"{kwargs['prefix']}completion_attention_mask"] = completion_tokens["attention_mask"] if model is not None and hasattr(model, "prepare_decoder_input_ids_from_labels"): batch[f"{kwargs['prefix']}completion_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels( labels=torch.tensor(batch["completion_labels"]) ) return batch class BCOTrainer(Trainer): r""" Initialize BCOTrainer from [BCO](https://huggingface.co/papers/2404.04656) paper. Args: model (`transformers.PreTrainedModel`): The model to train, preferably an `AutoModelForSequenceClassification`. ref_model (`PreTrainedModelWrapper`): Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation and loss. If no reference model is provided, the trainer will create a reference model with the same architecture as the model to be optimized. args (`BCOConfig`): The arguments to use for training. train_dataset (`datasets.Dataset`): The dataset to use for training. eval_dataset (`datasets.Dataset`): The dataset to use for evaluation. processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*, defaults to `None`): Processing class used to process the data. If provided, will be used to automatically process the inputs for the model, and it will be saved along the model to make it easier to rerun an interrupted training or reuse the fine-tuned model. data_collator (`transformers.DataCollator`, *optional*, defaults to `None`): The data collator to use for training. If None is specified, the default data collator (`DPODataCollatorWithPadding`) will be used which will pad the sequences to the maximum length of the sequences in the batch, given a dataset of paired sequences. model_init (`Callable[[], transformers.PreTrainedModel]`): The model initializer to use for training. If None is specified, the default model initializer will be used. callbacks (`list[transformers.TrainerCallback]`): The callbacks to use for training. optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): The optimizer and scheduler to use for training. preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): The function to use to preprocess the logits before computing the metrics. peft_config (`dict`, defaults to `None`): The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in a PEFT model. compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*): The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to metric values. model_adapter_name (`str`, defaults to `None`): Name of the train target PEFT adapter, when using LoRA with multiple adapters. ref_adapter_name (`str`, defaults to `None`): Name of the reference PEFT adapter, when using LoRA with multiple adapters. """ _tag_names = ["trl", "bco"] def __init__( self, model: Union[PreTrainedModel, nn.Module, str] = None, ref_model: Optional[Union[PreTrainedModel, nn.Module, str]] = None, args: BCOConfig = None, train_dataset: Optional[Dataset] = None, eval_dataset: Optional[Union[Dataset, dict[str, Dataset]]] = None, processing_class: Optional[ Union[PreTrainedTokenizerBase, BaseImageProcessor, FeatureExtractionMixin, ProcessorMixin] ] = None, data_collator: Optional[DataCollator] = None, model_init: Optional[Callable[[], PreTrainedModel]] = None, callbacks: Optional[list[TrainerCallback]] = None, optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None, peft_config: Optional[dict] = None, compute_metrics: Optional[Callable[[EvalLoopOutput], dict]] = None, model_adapter_name: Optional[str] = None, ref_adapter_name: Optional[str] = None, embedding_func: Optional[Callable] = None, embedding_tokenizer: Optional[PreTrainedTokenizerBase] = None, ): if embedding_func is not None and not (is_sklearn_available() and is_joblib_available()): raise ImportError( "BCOTrainer with UDM requires the scikit-learn and joblib libraries. Please install it with `pip install scikit-learn joblib`." ) if type(args) is TrainingArguments: raise ValueError("Please use `BCOConfig` instead `TrainingArguments`.") if not isinstance(model, str) and model is not None and ref_model is model: raise ValueError( "`model` and `ref_model` cannot be the same object. If you want `ref_model` to be the " "same as `model`, you must mass a copy of it, or `None` if you use peft." ) if args.model_init_kwargs is None: model_init_kwargs = {} elif not isinstance(model, str): raise ValueError("You passed model_kwargs to the BCOTrainer. But your model is already instantiated.") else: model_init_kwargs = args.model_init_kwargs torch_dtype = model_init_kwargs.get("torch_dtype") if torch_dtype is not None: # Convert to `torch.dtype` if an str is passed if isinstance(torch_dtype, str) and torch_dtype != "auto": torch_dtype = getattr(torch, torch_dtype) if torch_dtype != "auto" and not isinstance(torch_dtype, torch.dtype): raise ValueError( f"Invalid `torch_dtype` passed to the BCOConfig. Expected a string with either `torch.dtype` or 'auto', but got {torch_dtype}." ) model_init_kwargs["torch_dtype"] = torch_dtype if args.ref_model_init_kwargs is None: ref_model_init_kwargs = {} elif not isinstance(ref_model, str): raise ValueError( "You passed ref_model_kwargs to the BCOTrainer. But your ref_model is already instantiated." ) else: ref_model_init_kwargs = args.ref_model_init_kwargs torch_dtype = ref_model_init_kwargs.get("torch_dtype") if torch_dtype is not None: # Convert to `torch.dtype` if an str is passed if isinstance(torch_dtype, str) and torch_dtype != "auto": torch_dtype = getattr(torch, torch_dtype) if torch_dtype != "auto" and not isinstance(torch_dtype, torch.dtype): raise ValueError( f"Invalid `torch_dtype` passed to the BCOConfig. Expected a string with either `torch.dtype` or 'auto', but got {torch_dtype}." ) ref_model_init_kwargs["torch_dtype"] = torch_dtype if isinstance(model, str): model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs) if isinstance(ref_model, str): ref_model = AutoModelForCausalLM.from_pretrained(ref_model, **ref_model_init_kwargs) # Initialize this variable to False. This helps tracking the case when `peft_module_casting_to_bf16` # has been called in order to properly call autocast if needed. self._peft_has_been_casted_to_bf16 = False if not is_peft_available() and peft_config is not None: raise ValueError( "PEFT is not installed and you passed a `peft_config` in the trainer's kwargs, please install it with `pip install peft` to use the PEFT models" ) elif is_peft_available() and peft_config is not None: # if model is a peft model and we have a peft_config, we merge and unload it first if isinstance(model, PeftModel): model = model.merge_and_unload() if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False): _support_gc_kwargs = hasattr( args, "gradient_checkpointing_kwargs" ) and "gradient_checkpointing_kwargs" in list( inspect.signature(prepare_model_for_kbit_training).parameters ) prepare_model_kwargs = {"use_gradient_checkpointing": args.gradient_checkpointing} if _support_gc_kwargs: prepare_model_kwargs["gradient_checkpointing_kwargs"] = args.gradient_checkpointing_kwargs model = prepare_model_for_kbit_training(model, **prepare_model_kwargs) elif args.gradient_checkpointing: # For backward compatibility with older versions of transformers if hasattr(model, "enable_input_require_grads"): model.enable_input_require_grads() else: def make_inputs_require_grad(module, input, output): output.requires_grad_(True) model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) # get peft model with the given config model = get_peft_model(model, peft_config) if args.bf16 and getattr(model, "is_loaded_in_4bit", False): peft_module_casting_to_bf16(model) # If args.bf16 we need to explicitly call `generate` with torch amp autocast context manager self._peft_has_been_casted_to_bf16 = True # For models that use gradient_checkpointing, we need to attach a hook that enables input # to explicitly have `requires_grad=True`, otherwise training will either silently # fail or completely fail. elif args.gradient_checkpointing: # For backward compatibility with older versions of transformers if hasattr(model, "enable_input_require_grads"): model.enable_input_require_grads() else: def make_inputs_require_grad(module, input, output): output.requires_grad_(True) model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) if args.generate_during_eval and not (is_wandb_available() or is_comet_available()): raise ValueError( "`generate_during_eval=True` requires Weights and Biases or Comet to be installed." " Please install `wandb` or `comet-ml` to resolve." ) if model is not None: self.is_encoder_decoder = model.config.is_encoder_decoder elif args.is_encoder_decoder is None: raise ValueError("When no model is provided, you need to pass the parameter is_encoder_decoder.") else: self.is_encoder_decoder = args.is_encoder_decoder self.is_peft_model = is_peft_available() and isinstance(model, PeftModel) self.model_adapter_name = model_adapter_name self.ref_adapter_name = ref_adapter_name if ref_model: self.ref_model = ref_model elif self.is_peft_model or args.precompute_ref_log_probs: # The `model` with adapters turned off will be used as the reference model self.ref_model = None else: self.ref_model = create_reference_model(model) if processing_class is None: raise ValueError( "max_length or a processing_class must be specified when using the default DPODataCollatorWithPadding" ) if args.max_length is None: logger.warning( "When using DPODataCollatorWithPadding, you should set `max_length` in the `BCOConfig`. " "It will be set to `512` by default, but you should do it yourself in the future.", ) max_length = 512 if args.max_length is not None: max_length = args.max_length if args.max_prompt_length is None: logger.warning( "When using DPODataCollatorWithPadding, you should set `max_prompt_length` in the `BCOConfig`. " "It will be set to `128` by default, but you should do it yourself in the future.", ) max_prompt_length = 128 if args.max_prompt_length is not None: max_prompt_length = args.max_prompt_length max_completion_length = None if args.max_completion_length is None and self.is_encoder_decoder: logger.warning( "When using DPODataCollatorWithPadding with an encoder decoder architecture, you should set `max_completion_length` in the BCOTrainer's init" " it will be set to `128` by default, but you should do it yourself in the future.", ) max_completion_length = 128 if args.max_completion_length is not None and self.is_encoder_decoder: max_completion_length = args.max_completion_length if data_collator is None: data_collator = DPODataCollatorWithPadding( pad_token_id=processing_class.pad_token_id, label_pad_token_id=args.label_pad_token_id, is_encoder_decoder=self.is_encoder_decoder, ) if args.remove_unused_columns: args.remove_unused_columns = False # warn users logger.warning( "When using DPODataCollatorWithPadding, you should set `remove_unused_columns=False` in your BCOConfig" " we have set it for you, but you should do it yourself in the future.", ) self.use_dpo_data_collator = True else: self.use_dpo_data_collator = False # Disable dropout in the model and reference model if args.disable_dropout: disable_dropout_in_model(model) if self.ref_model is not None: disable_dropout_in_model(self.ref_model) self.max_length = max_length self.generate_during_eval = args.generate_during_eval self.label_pad_token_id = args.label_pad_token_id self.padding_value = args.padding_value if args.padding_value is not None else processing_class.pad_token_id self.max_prompt_length = max_prompt_length self.truncation_mode = args.truncation_mode self.max_completion_length = max_completion_length self.precompute_ref_log_probs = args.precompute_ref_log_probs # Since ref_logs are precomputed on the first call to get_train/eval_dataloader # keep track of first called to avoid computation of future calls self._precomputed_train_ref_log_probs = False self._precomputed_eval_ref_log_probs = False # metric self._stored_metrics = defaultdict(lambda: defaultdict(list)) # BCO parameter self.beta = args.beta self.aux_loss_enabled = getattr(model.config, "output_router_logits", False) self.aux_loss_coef = getattr(model.config, "router_aux_loss_coef", 0.0) if self.aux_loss_enabled and self.aux_loss_coef == 0.0: logger.warning( "You set `output_router_logits` to `True` in the model config, but `router_aux_loss_coef` is set to " "`0.0`, meaning the auxiliary loss will not be used. Either set `router_aux_loss_coef` to a value " "greater than `0.0`, or set `output_router_logits` to `False` if you don't want to use the auxiliary " "loss.", ) # Underlying Distribution Matching argument self.embedding_func = embedding_func self.embedding_tokenizer = embedding_tokenizer # The trainer estimates the number of FLOPs (floating-point operations) using the number of elements in the # input tensor associated with the key "input_ids". However, in BCO, the sampled data does not include the # "input_ids" key. Instead, the available keys are "prompt_input_ids" and "completion_input_ids". As a result, # the trainer issues the warning: "Could not estimate the number of tokens of the input, floating-point # operations will not be computed." To suppress this warning, we set the "estimate_tokens" key in the model's # "warnings_issued" dictionary to True. This acts as a flag to indicate that the warning has already been # issued. model.warnings_issued["estimate_tokens"] = True with PartialState().main_process_first(): # Extract the prompt if needed train_dataset = train_dataset.map( maybe_extract_prompt, num_proc=args.dataset_num_proc, desc="Extracting prompt from train dataset" ) # Unpair the dataset if needed train_dataset = maybe_unpair_preference_dataset( train_dataset, args.dataset_num_proc, desc="Unpairing train dataset" ) # Apply the chat template if needed train_dataset = train_dataset.map( maybe_apply_chat_template, fn_kwargs={"tokenizer": processing_class}, num_proc=args.dataset_num_proc ) if eval_dataset is not None: # Extract the prompt if needed eval_dataset = eval_dataset.map( maybe_extract_prompt, num_proc=args.dataset_num_proc, desc="Extracting prompt from eval dataset" ) # Unpair the dataset if needed eval_dataset = maybe_unpair_preference_dataset( eval_dataset, args.dataset_num_proc, desc="Unpairing eval dataset" ) eval_dataset = eval_dataset.map( maybe_apply_chat_template, fn_kwargs={"tokenizer": processing_class}, num_proc=args.dataset_num_proc, ) # Tokenize and prepare the training datasets train_dataset = train_dataset.map( _tokenize, batched=True, fn_kwargs={"tokenizer": processing_class, "embedding_tokenizer": self.embedding_tokenizer}, num_proc=args.dataset_num_proc, desc="Tokenizing train dataset", ) # Prepare the datasets fn_kwargs = { "prefix": "", "is_encoder_decoder": self.is_encoder_decoder, "tokenizer": processing_class, "max_length": self.max_length, "truncation_mode": self.truncation_mode, "label_pad_token_id": self.label_pad_token_id, "max_prompt_length": self.max_prompt_length, "max_completion_length": self.max_completion_length, } train_dataset = train_dataset.map( _process_tokens, fn_kwargs=fn_kwargs, num_proc=args.dataset_num_proc, desc="Processing tokenized train dataset", ) if eval_dataset is not None: # Tokenize eval_dataset = eval_dataset.map( _tokenize, fn_kwargs={"tokenizer": processing_class, "embedding_tokenizer": self.embedding_tokenizer}, batched=True, num_proc=args.dataset_num_proc, desc="Tokenizing eval dataset", ) # Process fn_kwargs = { "prefix": "", "is_encoder_decoder": self.is_encoder_decoder, "tokenizer": processing_class, "max_length": self.max_length, "truncation_mode": self.truncation_mode, "label_pad_token_id": self.label_pad_token_id, "max_prompt_length": self.max_prompt_length, "max_completion_length": self.max_completion_length, } eval_dataset = eval_dataset.map( _process_tokens, fn_kwargs=fn_kwargs, num_proc=args.dataset_num_proc, desc="Processing tokenized eval dataset", ) desirable = train_dataset.filter( lambda x: x["label"], num_proc=args.dataset_num_proc, desc="Filtering desirable examples" ) undesirable = train_dataset.filter( lambda x: not x["label"], num_proc=args.dataset_num_proc, desc="Filtering undesirable examples" ) super().__init__( model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, eval_dataset=eval_dataset, processing_class=processing_class, model_init=model_init, compute_metrics=compute_metrics, callbacks=callbacks, optimizers=optimizers, preprocess_logits_for_metrics=preprocess_logits_for_metrics, ) # Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set # self.model_accepts_loss_kwargs to False to enable scaling. self.model_accepts_loss_kwargs = False # Add tags for models that have been loaded with the correct transformers version if hasattr(self.model, "add_model_tags"): self.model.add_model_tags(self._tag_names) if not hasattr(self, "accelerator"): raise AttributeError( "Your `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`." ) # Deepspeed Zero-3 does not support precompute_ref_log_probs if self.is_deepspeed_enabled: if self.accelerator.state.deepspeed_plugin.zero_stage == 3 and self.precompute_ref_log_probs: raise ValueError( "You cannot use `precompute_ref_log_probs=True` with Deepspeed ZeRO-3. Please set `precompute_ref_log_probs=False`." ) if self.ref_model is None: if not (self.is_peft_model or self.precompute_ref_log_probs): raise ValueError( "No reference model and model is not a Peft model. Try setting `precompute_ref_log_probs=True`" ) else: if self.is_deepspeed_enabled: self.ref_model = prepare_deepspeed(self.ref_model, self.accelerator) else: self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True) self.running = RunningMoments(accelerator=self.accelerator) if self.embedding_func is None or args.resume_from_checkpoint: return chosen_embeddings = self._get_sample_prompt_embeddings(desirable, sample_size=self.args.prompt_sample_size) rejected_embeddings = self._get_sample_prompt_embeddings(undesirable, sample_size=self.args.prompt_sample_size) embeddings = torch.cat((chosen_embeddings, rejected_embeddings), dim=0) labels = torch.cat( (torch.ones_like(chosen_embeddings[:, 0]), torch.zeros_like(rejected_embeddings[:, 0])), dim=0 ) self.clf = LogisticRegression(class_weight="balanced").fit( embeddings.cpu().float().numpy(), labels.cpu().numpy() ) chosen_mean = self.clf.score( chosen_embeddings.cpu().float().numpy(), torch.ones_like(chosen_embeddings[:, 0]).cpu().numpy() ) rejected_mean = self.clf.score( rejected_embeddings.cpu().float().numpy(), torch.zeros_like(rejected_embeddings[:, 0]).cpu().numpy() ) logger.info(f"UDM classifier training scores: chosen: {chosen_mean}, rejected: {rejected_mean}") @property def match_underlying_distribution(self): return self.embedding_func is not None and self.embedding_tokenizer is not None def _get_chosen_prob(self, prompt_embeddings: torch.FloatTensor) -> torch.FloatTensor: """ Calculates the probability if the given prompt embedding is from desirable dataset. This function calculates the probability in the process and ensemble across processes. """ dtype = prompt_embeddings.dtype device = prompt_embeddings.device rank = self.accelerator.process_index padded_prompt_embeddings = self.accelerator.pad_across_processes( prompt_embeddings, pad_index=self.embedding_tokenizer.pad_token_id ) sample_size = padded_prompt_embeddings.shape[0] nonzero = padded_prompt_embeddings.mean(dim=1) != self.embedding_tokenizer.pad_token_id prompt_embeddings = self.accelerator.gather(padded_prompt_embeddings) # cannot predict for all empty values if prompt_embeddings.shape[0] == 0: return torch.tensor([], device=device, dtype=dtype) prob = self.clf.predict_proba(prompt_embeddings.cpu().float().numpy())[:, 1] prob = torch.as_tensor(prob, dtype=dtype, device=device) prob = self.accelerator.reduce(prob, reduction="mean") prob = prob[sample_size * rank : sample_size * (rank + 1)] prob = prob[nonzero] return prob def _vectorize_prompt(self, input_ids: torch.LongTensor, attention_mask: torch.LongTensor) -> torch.FloatTensor: """ Replaces processing_class.pad_token_id to embedding_tokenizer.pad_token_id and applies self.embedding_func """ input_ids = torch.where( input_ids == self.processing_class.pad_token_id, self.embedding_tokenizer.pad_token_id, input_ids, ) with torch.no_grad(): embeddings = self.embedding_func( input_ids=input_ids, attention_mask=attention_mask, ) return embeddings def _get_prompt_embeddings( self, batch: dict[str, Union[list, torch.LongTensor]] ) -> tuple[torch.FloatTensor, torch.FloatTensor]: """Extract embeddings from frozen embedding model""" if not self.match_underlying_distribution: return None, None embeddings = self._vectorize_prompt( input_ids=batch["embedding_input_ids"], attention_mask=batch["embedding_attention_mask"], ) labels = torch.tensor(batch["label"], dtype=torch.bool, device=embeddings.device) chosen_idx = torch.where(labels)[0] rejected_idx = torch.where(~labels)[0] chosen_embeddings = embeddings[chosen_idx, ...] rejected_embeddings = embeddings[rejected_idx, ...] return (chosen_embeddings, rejected_embeddings) def _get_sample_prompt_embeddings(self, dataset: Dataset, sample_size: int = 512) -> torch.FloatTensor: """ Sample instances from dataset and get prompt embeddings. Used for density ratio classifier training. """ n_samples = min(len(dataset), sample_size) rand_indices = np.random.choice(len(dataset), size=(n_samples,)) embedding_dataset = dataset.select(rand_indices) dataloader_params = { "batch_size": self.args.per_device_train_batch_size, "collate_fn": self.data_collator, "num_workers": self.args.dataloader_num_workers, "pin_memory": self.args.dataloader_pin_memory, "shuffle": False, } # prepare dataloader data_loader = self.accelerator.prepare(DataLoader(embedding_dataset, **dataloader_params)) with torch.no_grad(): all_embeddings = torch.empty(0) for padded_batch in tqdm(iterable=data_loader, desc="Building sample prompt embeddings"): embeddings = self._vectorize_prompt( input_ids=padded_batch["embedding_input_ids"], attention_mask=padded_batch["embedding_attention_mask"], ) embeddings = self.accelerator.gather_for_metrics(embeddings) all_embeddings = torch.cat((all_embeddings, embeddings.cpu())) return all_embeddings def _save_optimizer_and_scheduler(self, output_dir): output_dir = output_dir if output_dir is not None else self.args.output_dir super()._save_optimizer_and_scheduler(output_dir) if self.accelerator.is_main_process: # When saving optimizer and scheduler to checkpoint, save also the running delta object. self.running.save_to_json(os.path.join(output_dir, RUNNING_NAME)) if self.match_underlying_distribution: joblib.dump(self.clf, os.path.join(output_dir, CLF_NAME), compress=True) def _load_optimizer_and_scheduler(self, checkpoint): if checkpoint is None: logger.warning_once(f"Missing Checkpoint {checkpoint}") return super()._load_optimizer_and_scheduler(checkpoint) # when loading optimizer and scheduler from checkpoint, also load the running delta object. running_file = os.path.join(checkpoint, RUNNING_NAME) if os.path.isfile(running_file): self.running = RunningMoments.load_from_json(self.accelerator, running_file) if self.match_underlying_distribution: clf_file = os.path.join(checkpoint, CLF_NAME) if os.path.isfile(clf_file): self.clf = joblib.load(clf_file) @contextmanager def null_ref_context(self): """Context manager for handling null reference model (that is, peft adapter manipulation).""" with ( self.accelerator.unwrap_model(self.model).disable_adapter() if self.is_peft_model and not self.ref_adapter_name else nullcontext() ): if self.ref_adapter_name: self.model.set_adapter(self.ref_adapter_name) yield if self.ref_adapter_name: self.model.set_adapter(self.model_adapter_name or "default") def get_train_dataloader(self) -> DataLoader: """ Returns the training [`~torch.utils.data.DataLoader`]. Subclass of transformers.src.transformers.trainer.get_train_dataloader to precompute `ref_log_probs`. """ if self.precompute_ref_log_probs and not self._precomputed_train_ref_log_probs: dataloader_params = { "batch_size": self.args.per_device_train_batch_size, "collate_fn": self.data_collator, "num_workers": self.args.dataloader_num_workers, "pin_memory": self.args.dataloader_pin_memory, "shuffle": False, } # prepare dataloader data_loader = self.accelerator.prepare(DataLoader(self.train_dataset, **dataloader_params)) reference_completion_logps = [] for padded_batch in tqdm(iterable=data_loader, desc="Train dataset reference log probs"): reference_completion_logp = self.compute_reference_log_probs(padded_batch) reference_completion_logp = self.accelerator.gather_for_metrics(reference_completion_logp) reference_completion_logps.append(reference_completion_logp.cpu()) self.train_dataset = self.train_dataset.add_column( name="reference_logps", column=torch.cat(reference_completion_logps).float().numpy() ) self._precomputed_train_ref_log_probs = True return super().get_train_dataloader() def get_eval_dataloader(self, eval_dataset: Optional[Dataset] = None) -> DataLoader: """ Returns the evaluation [`~torch.utils.data.DataLoader`]. Subclass of transformers.src.transformers.trainer.get_eval_dataloader to precompute `ref_log_probs`. Args: eval_dataset (`torch.utils.data.Dataset`, *optional*): If provided, will override `self.eval_dataset`. If it is a [`~datasets.Dataset`], columns not accepted by the `model.forward()` method are automatically removed. It must implement `__len__`. """ if eval_dataset is None and self.eval_dataset is None: raise ValueError("Trainer: evaluation requires an eval_dataset.") eval_dataset = eval_dataset if eval_dataset is not None else self.eval_dataset if self.precompute_ref_log_probs and not self._precomputed_eval_ref_log_probs: dataloader_params = { "batch_size": self.args.per_device_eval_batch_size, "collate_fn": self.data_collator, "num_workers": self.args.dataloader_num_workers, "pin_memory": self.args.dataloader_pin_memory, "shuffle": False, } # prepare dataloader data_loader = self.accelerator.prepare(DataLoader(eval_dataset, **dataloader_params)) reference_completion_logps = [] for padded_batch in tqdm(iterable=data_loader, desc="Eval dataset reference log probs"): reference_completion_logp = self.compute_reference_log_probs(padded_batch) reference_completion_logp = self.accelerator.gather_for_metrics(reference_completion_logp) reference_completion_logps.append(reference_completion_logp.cpu()) eval_dataset = eval_dataset.add_column( name="reference_logps", column=torch.cat(reference_completion_logps).float().numpy() ) # Save calculated reference_chosen_logps and reference_rejected_logps to the eval_dataset for subsequent runs if self.eval_dataset is not None: self.eval_dataset = eval_dataset self._precomputed_eval_ref_log_probs = True return super().get_eval_dataloader(eval_dataset=eval_dataset) def compute_reference_log_probs(self, padded_batch: dict) -> dict: """Computes log probabilities of the reference model for a single padded batch of a BCO specific dataset.""" with torch.no_grad(): if self.ref_model is None: with self.null_ref_context(): if self.is_encoder_decoder: completion_logits = self.model( padded_batch["prompt_input_ids"], attention_mask=padded_batch["prompt_attention_mask"], decoder_input_ids=padded_batch.get("completion_decoder_input_ids"), labels=padded_batch["completion_labels"], ).logits else: completion_logits = self.model( padded_batch["completion_input_ids"], attention_mask=padded_batch["completion_attention_mask"], ).logits else: if self.is_encoder_decoder: completion_logits = self.ref_model( padded_batch["prompt_input_ids"], attention_mask=padded_batch["prompt_attention_mask"], decoder_input_ids=padded_batch.get("completion_decoder_input_ids"), labels=padded_batch["completion_labels"], ).logits else: completion_logits = self.ref_model( padded_batch["completion_input_ids"], attention_mask=padded_batch["completion_attention_mask"] ).logits completion_logps = self.get_batch_logps( completion_logits, padded_batch["completion_labels"], average_log_prob=False, is_encoder_decoder=self.is_encoder_decoder, label_pad_token_id=self.label_pad_token_id, ) return completion_logps @staticmethod def get_batch_logps( logits: torch.FloatTensor, labels: torch.LongTensor, average_log_prob: bool = False, label_pad_token_id: int = -100, is_encoder_decoder: bool = False, ) -> torch.FloatTensor: """Compute the log probabilities of the given labels under the given logits. Args: logits: Logits of the model (unnormalized). Shape: (batch_size, sequence_length, vocab_size) labels: Labels for which to compute the log probabilities. Label tokens with a value of label_pad_token_id are ignored. Shape: (batch_size, sequence_length) average_log_prob: If True, return the average log probability per (non-masked) token. Otherwise, return the sum of the log probabilities of the (non-masked) tokens. Returns: A tensor of shape (batch_size,) containing the average/sum log probabilities of the given labels under the given logits. """ if logits.shape[:-1] != labels.shape: raise ValueError("Logits (batch and sequence length dim) and labels must have the same shape.") if not is_encoder_decoder: labels = labels[:, 1:].clone() logits = logits[:, :-1, :] else: # Fixes end-dec RuntimeError labels = labels.clone() loss_mask = labels != label_pad_token_id # dummy token; we'll ignore the losses on these tokens later labels[labels == label_pad_token_id] = 0 per_token_logps = selective_log_softmax(logits, labels) if average_log_prob: return (per_token_logps * loss_mask).sum(-1) / loss_mask.sum(-1) else: return (per_token_logps * loss_mask).sum(-1) def forward( self, model: nn.Module, batch: dict[str, Union[list, torch.LongTensor]] ) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: model_kwargs = ( { "labels": batch["completion_labels"], "decoder_input_ids": batch.get("completion_decoder_input_ids"), } if self.is_encoder_decoder else {} ) if self.aux_loss_enabled: model_kwargs["output_router_logits"] = True outputs = model( batch["completion_input_ids"], attention_mask=batch["completion_attention_mask"], **model_kwargs, ) completion_logits = outputs.logits completion_logps = self.get_batch_logps( completion_logits, batch["completion_labels"], average_log_prob=False, is_encoder_decoder=self.is_encoder_decoder, label_pad_token_id=self.label_pad_token_id, ) if completion_logps.shape[0] != len(batch["label"]): raise ValueError( "There is a mismatch between the number of examples in this batch and the number of " "examples for which an output sequence was predicted." ) chosen_idx = [i for i in range(completion_logps.shape[0]) if batch["label"][i] is True] rejected_idx = [i for i in range(completion_logps.shape[0]) if batch["label"][i] is False] chosen_logps = completion_logps[chosen_idx, ...] rejected_logps = completion_logps[rejected_idx, ...] chosen_logits = completion_logits[chosen_idx, ...] rejected_logits = completion_logits[rejected_idx, ...] if self.aux_loss_enabled: return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, outputs.aux_loss) else: return (chosen_logps, rejected_logps, chosen_logits, rejected_logits) def _get_udm_weight(self, rejected_embeddings: torch.FloatTensor) -> torch.FloatTensor: prob_desirable = self._get_chosen_prob(rejected_embeddings) min_ratio = self.args.min_density_ratio max_ratio = self.args.max_density_ratio weight = (prob_desirable / (1 - prob_desirable + 1e-8)).clamp(min=min_ratio, max=max_ratio) return weight def bco_loss( self, policy_chosen_logps: torch.FloatTensor, policy_rejected_logps: torch.FloatTensor, reference_chosen_logps: torch.FloatTensor, reference_rejected_logps: torch.FloatTensor, chosen_embeddings: Optional[torch.FloatTensor], rejected_embeddings: Optional[torch.FloatTensor], do_train: bool = True, ) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: """Compute the BCO loss for a batch of policy and reference model log probabilities. Args: policy_chosen_logps: Log probabilities of the policy model for the chosen responses. Shape: (num(chosen) in batch_size,) policy_rejected_logps: Log probabilities of the policy model for the rejected responses. Shape: (num(rejected) in batch_size,) reference_chosen_logps: Log probabilities of the reference model for the chosen responses. Shape: (num(chosen) in batch_size,) reference_rejected_logps: Log probabilities of the reference model for the rejected responses. Shape: (num(rejected) in batch_size,) chosen_embeddings: embeddings of desirable prompts rejected_embeddings: embeddings of undesirable prompts Returns: A tuple of four tensors: (losses, chosen_rewards, rejected_rewards, delta). The losses tensor contains the BCO loss for each example in the batch. The chosen_rewards and rejected_rewards tensors contain the rewards for the chosen and rejected responses, respectively. The delta value contains the moving average of all implicit rewards. """ chosen_logratios = policy_chosen_logps - reference_chosen_logps chosen_rewards = self.beta * chosen_logratios rejected_logratios = policy_rejected_logps - reference_rejected_logps rejected_rewards = self.beta * rejected_logratios if do_train: self.running.update(torch.cat((chosen_rewards, rejected_rewards), 0).detach()) delta = torch.as_tensor(self.running.mean, device=chosen_rewards.device) chosen_losses = -F.logsigmoid(chosen_rewards - delta) rejected_losses = -F.logsigmoid(-(rejected_rewards - delta)) if self.match_underlying_distribution: chosen_weight = torch.ones_like(chosen_losses) rejected_weight = self._get_udm_weight(rejected_embeddings) losses = torch.cat((chosen_weight * chosen_losses, rejected_weight * rejected_losses), dim=0) else: losses = torch.cat((chosen_losses, rejected_losses), dim=0) return losses, chosen_rewards, rejected_rewards, delta def get_batch_loss_metrics( self, model, batch: dict[str, Union[list, torch.LongTensor]], do_train: bool = True, ): """Compute the BCO loss and other metrics for the given batch of inputs for train or test.""" metrics = {} batch = {k: (v.to(self.accelerator.device) if isinstance(v, torch.Tensor) else v) for k, v in batch.items()} forward_output = self.forward(model, batch) ( policy_chosen_logps, policy_rejected_logps, policy_chosen_logits, policy_rejected_logits, ) = forward_output[:4] if self.aux_loss_enabled: aux_loss = forward_output[4] # if reference_logps in batch use them, otherwise use the reference model if "reference_logps" in batch: chosen_idx = [i for i in range(batch["reference_logps"].shape[0]) if batch["label"][i] is True] rejected_idx = [i for i in range(batch["reference_logps"].shape[0]) if batch["label"][i] is False] reference_chosen_logps = batch["reference_logps"][chosen_idx, ...] reference_rejected_logps = batch["reference_logps"][rejected_idx, ...] else: with torch.no_grad(): if self.ref_model is None: with self.null_ref_context(): ( reference_chosen_logps, reference_rejected_logps, _, _, ) = self.forward(self.model, batch)[:4] else: ( reference_chosen_logps, reference_rejected_logps, _, _, ) = self.forward(self.ref_model, batch)[:4] chosen_embeddings, rejected_embeddings = self._get_prompt_embeddings(batch) losses, chosen_rewards, rejected_rewards, delta = self.bco_loss( policy_chosen_logps, policy_rejected_logps, reference_chosen_logps, reference_rejected_logps, chosen_embeddings, rejected_embeddings, do_train=do_train, ) metrics["delta"] = self.accelerator.gather_for_metrics(delta).mean().item() num_chosen = torch.Tensor([len(chosen_rewards)]).to(self.accelerator.device) num_rejected = torch.Tensor([len(rejected_rewards)]).to(self.accelerator.device) all_num_chosen = self.accelerator.gather_for_metrics(num_chosen).sum().item() all_num_rejected = self.accelerator.gather_for_metrics(num_rejected).sum().item() if all_num_chosen > 0: metrics["rewards/chosen_sum"] = ( self.accelerator.gather_for_metrics(chosen_rewards.nansum()).nansum().item() ) metrics["logps/chosen_sum"] = ( self.accelerator.gather_for_metrics(policy_chosen_logps.nansum()).nansum().item() ) metrics["logits/chosen_sum"] = ( self.accelerator.gather_for_metrics(policy_chosen_logits.nansum()).nansum().item() ) metrics["count/chosen"] = all_num_chosen if all_num_rejected > 0: metrics["rewards/rejected_sum"] = ( self.accelerator.gather_for_metrics(rejected_rewards.nansum()).nansum().item() ) metrics["logps/rejected_sum"] = ( self.accelerator.gather_for_metrics(policy_rejected_logps.nansum()).nansum().item() ) metrics["logits/rejected_sum"] = ( self.accelerator.gather_for_metrics(policy_rejected_logits.nansum()).nansum().item() ) metrics["count/rejected"] = all_num_rejected loss = losses.nanmean() if self.aux_loss_enabled: loss += self.aux_loss_coef * aux_loss return loss, metrics def compute_loss( self, model: Union[PreTrainedModel, nn.Module], inputs: dict[str, Union[torch.Tensor, Any]], return_outputs=False, num_items_in_batch=None, ) -> Union[torch.Tensor, tuple[torch.Tensor, dict[str, torch.Tensor]]]: compute_loss_context_manager = ( autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext() ) with compute_loss_context_manager: loss, metrics = self.get_batch_loss_metrics(model, inputs) # Make sure to move the loss to the device the original accumulating loss is at back in the `Trainer` class: loss = loss.to(self.args.device) # force log the metrics if self.accelerator.is_main_process: self.store_metrics(metrics, train_eval="train") if return_outputs: return (loss, metrics) return loss def store_metrics(self, metrics: dict[str, float], train_eval: Literal["train", "eval"] = "train") -> None: for key, value in metrics.items(): self._stored_metrics[train_eval][key].append(value) def _get_train_sampler(self, dataset: Optional[Dataset] = None) -> Optional[torch.utils.data.Sampler]: if dataset is None: dataset = self.train_dataset if dataset is None or not has_length(dataset): return None return SequentialSampler(dataset) def generate_from_model_and_ref(self, model, batch: dict[str, torch.LongTensor]) -> tuple[str, str]: """Generate samples from the model and reference model for the given batch of inputs.""" # If one uses `generate_during_eval` with peft + bf16, we need to explicitly call generate with # the torch amp context manager as some hidden states are silently casted to full precision. generate_context_manager = ( autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext() ) with generate_context_manager: policy_output = model.generate( input_ids=batch["prompt_input_ids"], attention_mask=batch["prompt_attention_mask"], max_length=self.max_length, do_sample=True, pad_token_id=self.processing_class.pad_token_id, ) # if reference_output in batch use that otherwise use the reference model if "reference_output" in batch: reference_output = batch["reference_output"] else: if self.ref_model is None: with self.null_ref_context(): reference_output = self.model.generate( input_ids=batch["prompt_input_ids"], attention_mask=batch["prompt_attention_mask"], max_length=self.max_length, do_sample=True, pad_token_id=self.processing_class.pad_token_id, ) else: reference_output = self.ref_model.generate( input_ids=batch["prompt_input_ids"], attention_mask=batch["prompt_attention_mask"], max_length=self.max_length, do_sample=True, pad_token_id=self.processing_class.pad_token_id, ) policy_output = pad_to_length(policy_output, self.max_length, self.processing_class.pad_token_id) policy_output_decoded = self.processing_class.batch_decode(policy_output, skip_special_tokens=True) reference_output = pad_to_length(reference_output, self.max_length, self.processing_class.pad_token_id) reference_output_decoded = self.processing_class.batch_decode(reference_output, skip_special_tokens=True) return policy_output_decoded, reference_output_decoded def prediction_step( self, model: Union[PreTrainedModel, nn.Module], inputs: dict[str, Union[torch.Tensor, Any]], prediction_loss_only: bool, ignore_keys: Optional[list[str]] = None, ): if ignore_keys is None: if hasattr(model, "config"): ignore_keys = getattr(model.config, "keys_to_ignore_at_inference", []) else: ignore_keys = [] prediction_context_manager = ( autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext() ) with torch.no_grad(), prediction_context_manager: loss, metrics = self.get_batch_loss_metrics(model, inputs, do_train=False) # force log the metrics if self.accelerator.is_main_process: self.store_metrics(metrics, train_eval="eval") if prediction_loss_only: return (loss.detach(), None, None) # logits for the chosen and rejected samples from model logits_dict = {} if "logits/chosen_sum" in metrics: logits_dict["eval_logits/chosen"] = metrics["logits/chosen_sum"] if "logits/rejected_sum" in metrics: logits_dict["eval_logits/rejected"] = metrics["logits/rejected_sum"] logits = [v for k, v in logits_dict.items() if k not in ignore_keys] logits = torch.tensor(logits, device=self.accelerator.device) labels = torch.zeros(logits.shape[0], device=self.accelerator.device) return (loss.detach(), logits, labels) def evaluation_loop( self, dataloader: DataLoader, description: str, prediction_loss_only: Optional[bool] = None, ignore_keys: Optional[list[str]] = None, metric_key_prefix: str = "eval", ) -> EvalLoopOutput: """ Overriding built-in evaluation loop to store metrics for each batch. Prediction/evaluation loop, shared by `Trainer.evaluate()` and `Trainer.predict()`. Works both with or without labels. """ # Sample and save to game log if requested (for one batch to save time) if self.generate_during_eval: # Generate random indices within the range of the total number of samples num_samples = len(dataloader.dataset) random_indices = random.sample(range(num_samples), k=self.args.eval_batch_size) # Use dataloader.dataset.select to get the random batch without iterating over the DataLoader random_batch_dataset = dataloader.dataset.select(random_indices) random_batch = self.data_collator(random_batch_dataset) random_batch = self._prepare_inputs(random_batch) target_labels = torch.tensor(random_batch["label"], dtype=torch.bool, device=self.accelerator.device) target_indices = torch.where(~target_labels)[0] target_batch = { "prompt_input_ids": random_batch["prompt_input_ids"][target_indices], "prompt_attention_mask": random_batch["prompt_attention_mask"][target_indices], "prompt": itemgetter(*target_indices)(random_batch["prompt"]), } policy_output_decoded, ref_output_decoded = self.generate_from_model_and_ref(self.model, target_batch) table = pd.DataFrame( columns=["Prompt", "Policy", "Ref Model"], data=[ [prompt, pol[len(prompt) :], ref[len(prompt) :]] for prompt, pol, ref in zip(target_batch["prompt"], policy_output_decoded, ref_output_decoded) ], ) if "wandb" in self.args.report_to: wandb.log({"game_log": wandb.Table(data=table)}) if "comet_ml" in self.args.report_to: log_table_to_comet_experiment( name="game_log.csv", table=table, ) # Base evaluation initial_output = super().evaluation_loop( dataloader, description, prediction_loss_only, ignore_keys, metric_key_prefix ) return initial_output def log(self, logs: dict[str, float], start_time: Optional[float] = None) -> None: """ Log `logs` on the various objects watching training, including stored metrics. Args: logs (`dict[str, float]`): The values to log. start_time (`float` or `None`, *optional*, defaults to `None`): Start time of the training. """ # logs either has 'loss' or 'eval_loss' train_eval = "train" if "loss" in logs else "eval" # train metrics should have no prefix, eval should have 'eval_' prefix = "eval_" if train_eval == "eval" else "" # accumulate average metrics from sums and lengths for split in ["chosen", "rejected"]: if f"count/{split}" in self._stored_metrics[train_eval]: count_sum = torch.Tensor(self._stored_metrics[train_eval][f"count/{split}"]).sum().item() for metric in ["rewards", "logps", "logits"]: logs[f"{prefix}{metric}/{split}"] = ( torch.Tensor(self._stored_metrics[train_eval][f"{metric}/{split}_sum"]).sum().item() / count_sum ) # delete obsolete metric del self._stored_metrics[train_eval][f"{metric}/{split}_sum"] del self._stored_metrics[train_eval][f"count/{split}"] # calculate reward margin if f"{prefix}rewards/chosen" in logs and f"{prefix}rewards/rejected" in logs: logs[f"{prefix}rewards/margins"] = logs[f"{prefix}rewards/chosen"] - logs[f"{prefix}rewards/rejected"] # Add averaged stored metrics to logs for key, metrics in self._stored_metrics[train_eval].items(): logs[f"{prefix}{key}"] = torch.Tensor(metrics).mean().item() del self._stored_metrics[train_eval] return super().log(logs, start_time) # Ensure the model card is saved along with the checkpoint def _save_checkpoint(self, model, trial): if self.args.hub_model_id is None: model_name = Path(self.args.output_dir).name else: model_name = self.args.hub_model_id.split("/")[-1] self.create_model_card(model_name=model_name) super()._save_checkpoint(model, trial) def create_model_card( self, model_name: Optional[str] = None, dataset_name: Optional[str] = None, tags: Union[str, list[str], None] = None, ): """ Creates a draft of a model card using the information available to the `Trainer`. Args: model_name (`str` or `None`, *optional*, defaults to `None`): Name of the model. dataset_name (`str` or `None`, *optional*, defaults to `None`): Name of the dataset used for training. tags (`str`, `list[str]` or `None`, *optional*, defaults to `None`): Tags to be associated with the model card. """ if not self.is_world_process_zero(): return if hasattr(self.model.config, "_name_or_path") and not os.path.isdir(self.model.config._name_or_path): base_model = self.model.config._name_or_path else: base_model = None # normalize `tags` to a mutable set if tags is None: tags = set() elif isinstance(tags, str): tags = {tags} else: tags = set(tags) if hasattr(self.model.config, "unsloth_version"): tags.add("unsloth") tags.update(self._tag_names) # docstyle-ignore citation = textwrap.dedent("""\ @article{jung2024binary, title = {{Binary Classifier Optimization for Large Language Model Alignment}}, author = {Seungjae Jung and Gunsoo Han and Daniel Wontae Nam and Kyoung{-}Woon On}, year = 2024, eprint = {arXiv:2404.04656} }""") model_card = generate_model_card( base_model=base_model, model_name=model_name, hub_model_id=self.hub_model_id, dataset_name=dataset_name, tags=tags, wandb_url=wandb.run.url if is_wandb_available() and wandb.run is not None else None, comet_url=get_comet_experiment_url(), trainer_name="BCO", trainer_citation=citation, paper_title="Binary Classifier Optimization for Large Language Model Alignment", paper_id="2404.04656", ) model_card.save(os.path.join(self.args.output_dir, "README.md"))
trl/trl/trainer/bco_trainer.py/0
{ "file_path": "trl/trl/trainer/bco_trainer.py", "repo_id": "trl", "token_count": 32651 }
610
# Copyright 2020-2025 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import inspect import os import random import textwrap from collections import defaultdict from contextlib import contextmanager, nullcontext from operator import itemgetter from pathlib import Path from typing import TYPE_CHECKING, Any, Callable, Literal, Optional, Union import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F from accelerate import PartialState, logging from accelerate.utils import tqdm from datasets import Dataset, concatenate_datasets from torch import autocast from torch.utils.data import DataLoader, SequentialSampler from transformers import ( AutoModelForCausalLM, BaseImageProcessor, DataCollator, FeatureExtractionMixin, PreTrainedModel, PreTrainedTokenizerBase, ProcessorMixin, Trainer, TrainerCallback, TrainingArguments, is_comet_available, is_wandb_available, ) from transformers.trainer_utils import EvalLoopOutput, has_length from transformers.utils import is_peft_available from ..data_utils import maybe_apply_chat_template, maybe_extract_prompt, maybe_unpair_preference_dataset from ..import_utils import is_liger_kernel_available from ..models import create_reference_model, prepare_deepspeed from .kto_config import KTOConfig from .utils import ( DPODataCollatorWithPadding, disable_dropout_in_model, generate_model_card, get_comet_experiment_url, log_table_to_comet_experiment, pad_to_length, peft_module_casting_to_bf16, selective_log_softmax, ) if is_liger_kernel_available(): from liger_kernel.chunked_loss import LigerFusedLinearKTOLoss if is_peft_available(): from peft import PeftModel, get_peft_model, prepare_model_for_kbit_training if is_wandb_available(): import wandb if TYPE_CHECKING: from transformers import PreTrainedModel, PreTrainedTokenizer logger = logging.get_logger(__name__) RUNNING_NAME = "running.pt" def _get_kl_dataset(batch: dict[str, list[Any]]) -> dict[str, list[Any]]: """ Creates mismatched pairs of prompts and completions for the KL dataset by adding a +1 offset to the order of completions. For best results, the mismatched outputs y' used to estimate the KL term for a batch should be the same set as the matched outputs y used to estimate the rewards in that batch, just paired with different x. """ batch["answer_input_ids"] = [batch["answer_input_ids"][-1]] + batch["answer_input_ids"][:-1] batch["answer_attention_mask"] = [batch["answer_attention_mask"][-1]] + batch["answer_attention_mask"][:-1] return batch def _tokenize( batch: dict[str, list[Any]], tokenizer: "PreTrainedTokenizer", ) -> dict[str, list[Any]]: """Tokenize a batch from a KTO specific dataset.""" prompt_tokenized = tokenizer(batch["prompt"], add_special_tokens=False) prompt_input_ids = prompt_tokenized["input_ids"] prompt_attention_mask = prompt_tokenized["attention_mask"] prompt_and_completion = [prompt + completion for prompt, completion in zip(batch["prompt"], batch["completion"])] full_tokenized = tokenizer(prompt_and_completion, add_special_tokens=False) full_input_ids = full_tokenized["input_ids"] full_attention_mask = full_tokenized["attention_mask"] answer_input_ids = [f[len(p) :] for f, p in zip(full_input_ids, prompt_input_ids)] answer_attention_mask = [f[len(p) :] for f, p in zip(full_attention_mask, prompt_attention_mask)] # Concat tokens to form `enc(a) + enc(a + b)[len(enc(a)):]` full_concat_input_ids = [np.concatenate([p, a]) for p, a in zip(prompt_input_ids, answer_input_ids)] # Prepare input tokens for token by token comparison full_input_ids = [np.array(f) for f in full_input_ids] for full, concat in zip(full_input_ids, full_concat_input_ids): if len(full) != len(concat): raise ValueError( "The elements in 'full_input_ids' and 'full_concat_input_ids' must have the same pairwise length." ) # On some tokenizers, like Llama-2 tokenizer, there are occasions where tokens # can be merged together when tokenizing prompt+answer. This could result # on the last token from the prompt being different when tokenized on its own # vs when done as prompt+answer. response_token_ids_start_idx = [len(p) for p in prompt_input_ids] # If tokenized prompt is different than both prompt+answer, then it means the # last token has changed due to merging. for idx, (p, f, r) in enumerate(zip(prompt_input_ids, full_input_ids, response_token_ids_start_idx)): if not np.array_equal(p, f[:r]): response_token_ids_start_idx[idx] -= 1 prompt_input_ids = [f[:r] for f, r in zip(full_input_ids, response_token_ids_start_idx)] prompt_attention_mask = [f[:r] for f, r in zip(full_attention_mask, response_token_ids_start_idx)] for p, m in zip(prompt_input_ids, prompt_attention_mask): if len(p) != len(m): raise ValueError("Prompt input ids and attention mask should have the same length.") answer_input_ids = [f[r:] for f, r in zip(full_input_ids, response_token_ids_start_idx)] answer_attention_mask = [f[r:] for f, r in zip(full_attention_mask, response_token_ids_start_idx)] output = dict( prompt_input_ids=prompt_input_ids, prompt_attention_mask=prompt_attention_mask, answer_input_ids=answer_input_ids, answer_attention_mask=answer_attention_mask, ) return output def _process_tokens(example: dict[str, Any], model: "PreTrainedModel" = None, **kwargs) -> dict: """Process tokens of a KTO specific dataset. At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation in case the prompt + completion responses is/are too long. First we truncate the prompt; if we're still too long, we truncate the completion. We also create the labels for the completion responses, which are of length equal to the sum of the length of the prompt and the completion response, with label_pad_token_id for the prompt tokens. """ prompt = example["prompt"] completion = example["completion"] batch = { f"{kwargs['prefix']}prompt": prompt, f"{kwargs['prefix']}completion": completion, f"{kwargs['prefix']}label": example["label"], } if not kwargs["is_encoder_decoder"]: # Check issues below for more details # 1. https://github.com/huggingface/trl/issues/907 # 2. https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257 # 3. https://github.com/LianjiaTech/BELLE/issues/337 if not isinstance(prompt, str): raise ValueError(f"prompt should be an str but got {type(prompt)}") if not isinstance(completion, str): raise ValueError(f"completion should be an str but got {type(completion)}") # keys of format prompt_* refers to just the prompt and answer_* refers to just the answer all_tokens = { "prompt_input_ids": example["prompt_input_ids"], "prompt_attention_mask": example["prompt_attention_mask"], "answer_input_ids": example["answer_input_ids"], "answer_attention_mask": example["answer_attention_mask"], } # calculate max length by checking if BOS/EOS is already there max_length = kwargs["max_length"] bos_token_id = kwargs["tokenizer"].bos_token_id eos_token_id = kwargs["tokenizer"].eos_token_id if len(all_tokens["prompt_input_ids"]) > 0 and bos_token_id != all_tokens["prompt_input_ids"][0]: max_length -= 1 if len(all_tokens["answer_input_ids"]) > 0 and eos_token_id != all_tokens["answer_input_ids"][-1]: max_length -= 1 # if combined sequence is too long (> max_length - 1 for BOS token - 1 for EOS), truncate the prompt if len(all_tokens["prompt_input_ids"]) + len(all_tokens["answer_input_ids"]) > max_length: for k in ["prompt_input_ids", "prompt_attention_mask"]: if kwargs["truncation_mode"] == "keep_start": all_tokens[k] = all_tokens[k][: kwargs["max_prompt_length"]] elif kwargs["truncation_mode"] == "keep_end": all_tokens[k] = all_tokens[k][-kwargs["max_prompt_length"] :] else: raise ValueError(f"Unknown truncation mode: {kwargs['truncation_mode']}") # if that's still too long, truncate the response if len(all_tokens["prompt_input_ids"]) + len(all_tokens["answer_input_ids"]) > max_length: for k in ["answer_input_ids", "answer_attention_mask"]: all_tokens[k] = all_tokens[k][: max_length - kwargs["max_prompt_length"]] # all input_ids and attention mask as is. We then check if we need to add BOS/EOS tokens batch[f"{kwargs['prefix']}prompt_input_ids"] = all_tokens["prompt_input_ids"] batch[f"{kwargs['prefix']}prompt_attention_mask"] = all_tokens["prompt_attention_mask"] batch[f"{kwargs['prefix']}completion_input_ids"] = ( all_tokens["prompt_input_ids"] + all_tokens["answer_input_ids"] ) batch[f"{kwargs['prefix']}completion_attention_mask"] = ( all_tokens["prompt_attention_mask"] + all_tokens["answer_attention_mask"] ) # add BOS, which affects both prompt and the full completion if bos_token_id is not None: if len(all_tokens["prompt_input_ids"]) == 0 or bos_token_id != all_tokens["prompt_input_ids"][0]: batch[f"{kwargs['prefix']}prompt_input_ids"] = [bos_token_id] + batch[ f"{kwargs['prefix']}prompt_input_ids" ] batch[f"{kwargs['prefix']}prompt_attention_mask"] = [1] + batch[ f"{kwargs['prefix']}prompt_attention_mask" ] batch[f"{kwargs['prefix']}completion_input_ids"] = [bos_token_id] + batch[ f"{kwargs['prefix']}completion_input_ids" ] batch[f"{kwargs['prefix']}completion_attention_mask"] = [1] + batch[ f"{kwargs['prefix']}completion_attention_mask" ] # add EOS, which affects only the full completion if len(all_tokens["answer_input_ids"]) == 0 or eos_token_id != all_tokens["answer_input_ids"][-1]: batch[f"{kwargs['prefix']}completion_input_ids"] = batch[f"{kwargs['prefix']}completion_input_ids"] + [ eos_token_id ] batch[f"{kwargs['prefix']}completion_attention_mask"] = batch[ f"{kwargs['prefix']}completion_attention_mask" ] + [1] batch[f"{kwargs['prefix']}completion_labels"] = batch[f"{kwargs['prefix']}completion_input_ids"][:] batch[f"{kwargs['prefix']}completion_labels"][: len(batch[f"{kwargs['prefix']}prompt_input_ids"])] = [ kwargs["label_pad_token_id"] ] * len(batch[f"{kwargs['prefix']}prompt_input_ids"]) else: completion_tokens = kwargs["tokenizer"]( completion, truncation=True, max_length=kwargs["max_completion_length"], add_special_tokens=True ) prompt_tokens = kwargs["tokenizer"]( prompt, truncation=True, max_length=kwargs["max_prompt_length"], add_special_tokens=True ) batch[f"{kwargs['prefix']}prompt_input_ids"] = prompt_tokens["input_ids"] batch[f"{kwargs['prefix']}prompt_attention_mask"] = prompt_tokens["attention_mask"] batch[f"{kwargs['prefix']}completion_labels"] = completion_tokens["input_ids"] batch[f"{kwargs['prefix']}completion_attention_mask"] = completion_tokens["attention_mask"] if model is not None and hasattr(model, "prepare_decoder_input_ids_from_labels"): batch[f"{kwargs['prefix']}completion_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels( labels=torch.tensor(batch["completion_labels"]) ) return batch class KTOTrainer(Trainer): r""" Initialize KTOTrainer. Args: model (`transformers.PreTrainedModel`): The model to train, preferably an `AutoModelForSequenceClassification`. ref_model (`PreTrainedModelWrapper`): Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation and loss. If no reference model is provided, the trainer will create a reference model with the same architecture as the model to be optimized. args (`KTOConfig`): The arguments to use for training. train_dataset (`datasets.Dataset`): The dataset to use for training. eval_dataset (`datasets.Dataset`): The dataset to use for evaluation. processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*, defaults to `None`): Processing class used to process the data. If provided, will be used to automatically process the inputs for the model, and it will be saved along the model to make it easier to rerun an interrupted training or reuse the fine-tuned model. data_collator (`transformers.DataCollator`, *optional*, defaults to `None`): The data collator to use for training. If None is specified, the default data collator (`DPODataCollatorWithPadding`) will be used which will pad the sequences to the maximum length of the sequences in the batch, given a dataset of paired sequences. model_init (`Callable[[], transformers.PreTrainedModel]`): The model initializer to use for training. If None is specified, the default model initializer will be used. callbacks (`list[transformers.TrainerCallback]`): The callbacks to use for training. optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): The optimizer and scheduler to use for training. preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): The function to use to preprocess the logits before computing the metrics. peft_config (`dict`, defaults to `None`): The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in a PEFT model. compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*): The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to metric values. model_adapter_name (`str`, defaults to `None`): Name of the train target PEFT adapter, when using LoRA with multiple adapters. ref_adapter_name (`str`, defaults to `None`): Name of the reference PEFT adapter, when using LoRA with multiple adapters. """ _tag_names = ["trl", "kto"] def __init__( self, model: Union[PreTrainedModel, nn.Module, str] = None, ref_model: Optional[Union[PreTrainedModel, nn.Module, str]] = None, args: KTOConfig = None, train_dataset: Optional[Dataset] = None, eval_dataset: Optional[Union[Dataset, dict[str, Dataset]]] = None, processing_class: Optional[ Union[PreTrainedTokenizerBase, BaseImageProcessor, FeatureExtractionMixin, ProcessorMixin] ] = None, data_collator: Optional[DataCollator] = None, model_init: Optional[Callable[[], PreTrainedModel]] = None, callbacks: Optional[list[TrainerCallback]] = None, optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None, peft_config: Optional[dict] = None, compute_metrics: Optional[Callable[[EvalLoopOutput], dict]] = None, model_adapter_name: Optional[str] = None, ref_adapter_name: Optional[str] = None, ): if type(args) is TrainingArguments: raise ValueError("Please use `KTOConfig` instead TrainingArguments.") if not isinstance(model, str) and ref_model is model: raise ValueError( "`model` and `ref_model` cannot be the same object. If you want `ref_model` to be the " "same as `model`, you must mass a copy of it, or `None` if you use peft." ) if args.model_init_kwargs is None: model_init_kwargs = {} elif not isinstance(model, str): raise ValueError("You passed model_kwargs to the KTOTrainer. But your model is already instantiated.") else: model_init_kwargs = args.model_init_kwargs torch_dtype = model_init_kwargs.get("torch_dtype") if torch_dtype is not None: # Convert to `torch.dtype` if an str is passed if isinstance(torch_dtype, str) and torch_dtype != "auto": torch_dtype = getattr(torch, torch_dtype) if torch_dtype != "auto" and not isinstance(torch_dtype, torch.dtype): raise ValueError( f"Invalid `torch_dtype` passed to the KTOConfig. Expected a string with either `torch.dtype` or 'auto', but got {torch_dtype}." ) model_init_kwargs["torch_dtype"] = torch_dtype if args.ref_model_init_kwargs is None: ref_model_init_kwargs = {} elif not isinstance(ref_model, str): raise ValueError( "You passed ref_model_kwargs to the KTOTrainer. But your ref_model is already instantiated." ) else: ref_model_init_kwargs = args.ref_model_init_kwargs torch_dtype = ref_model_init_kwargs.get("torch_dtype") if torch_dtype is not None: # Convert to `torch.dtype` if an str is passed if isinstance(torch_dtype, str) and torch_dtype != "auto": torch_dtype = getattr(torch, torch_dtype) if torch_dtype != "auto" and not isinstance(torch_dtype, torch.dtype): raise ValueError( f"Invalid `torch_dtype` passed to the KTOConfig. Expected a string with either `torch.dtype` or 'auto', but got {torch_dtype}." ) ref_model_init_kwargs["torch_dtype"] = torch_dtype if isinstance(model, str): model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs) if isinstance(ref_model, str): ref_model = AutoModelForCausalLM.from_pretrained(ref_model, **ref_model_init_kwargs) # Initialize this variable to False. This helps tracking the case when `peft_module_casting_to_bf16` # has been called in order to properly call autocast if needed. self._peft_has_been_casted_to_bf16 = False if not is_peft_available() and peft_config is not None: raise ValueError( "PEFT is not installed and you passed a `peft_config` in the trainer's kwargs, please install it with `pip install peft` to use the PEFT models" ) elif is_peft_available() and peft_config is not None: # if model is a peft model and we have a peft_config, we merge and unload it first if isinstance(model, PeftModel): model = model.merge_and_unload() if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False): _support_gc_kwargs = hasattr( args, "gradient_checkpointing_kwargs" ) and "gradient_checkpointing_kwargs" in list( inspect.signature(prepare_model_for_kbit_training).parameters ) prepare_model_kwargs = {"use_gradient_checkpointing": args.gradient_checkpointing} if _support_gc_kwargs: prepare_model_kwargs["gradient_checkpointing_kwargs"] = args.gradient_checkpointing_kwargs model = prepare_model_for_kbit_training(model, **prepare_model_kwargs) elif args.gradient_checkpointing: # For backward compatibility with older versions of transformers if hasattr(model, "enable_input_require_grads"): model.enable_input_require_grads() else: def make_inputs_require_grad(module, input, output): output.requires_grad_(True) model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) # get peft model with the given config model = get_peft_model(model, peft_config) if args.bf16 and getattr(model, "is_loaded_in_4bit", False): peft_module_casting_to_bf16(model) # If args.bf16 we need to explicitly call `generate` with torch amp autocast context manager self._peft_has_been_casted_to_bf16 = True # For models that use gradient_checkpointing, we need to attach a hook that enables input # to explicitly have `requires_grad=True`, otherwise training will either silently # fail or completely fail. elif args.gradient_checkpointing: # For backward compatibility with older versions of transformers if hasattr(model, "enable_input_require_grads"): model.enable_input_require_grads() else: def make_inputs_require_grad(module, input, output): output.requires_grad_(True) model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) if args.generate_during_eval and not (is_wandb_available() or is_comet_available()): raise ValueError( "`generate_during_eval=True` requires Weights and Biases or Comet to be installed." " Please install `wandb` or `comet-ml` to resolve." ) if model is not None: self.is_encoder_decoder = model.config.is_encoder_decoder elif args.is_encoder_decoder is None: raise ValueError("When no model is provided, you need to pass the parameter is_encoder_decoder.") else: self.is_encoder_decoder = args.is_encoder_decoder self.is_peft_model = is_peft_available() and isinstance(model, PeftModel) self.model_adapter_name = model_adapter_name self.ref_adapter_name = ref_adapter_name if ref_model: self.ref_model = ref_model elif self.is_peft_model or args.precompute_ref_log_probs: # The `model` with adapters turned off will be used as the reference model self.ref_model = None else: self.ref_model = create_reference_model(model) if processing_class is None: raise ValueError( "max_length or a processing_class must be specified when using the default DPODataCollatorWithPadding" ) if args.max_length is None: logger.warning( "When using DPODataCollatorWithPadding, you should set `max_length` in the KTOTrainer's init" " it will be set to `512` by default, but you should do it yourself in the future.", ) max_length = 512 if args.max_length is not None: max_length = args.max_length if args.max_prompt_length is None: logger.warning( "When using DPODataCollatorWithPadding, you should set `max_prompt_length` in the KTOTrainer's init" " it will be set to `128` by default, but you should do it yourself in the future.", ) max_prompt_length = 128 if args.max_prompt_length is not None: max_prompt_length = args.max_prompt_length max_completion_length = None if args.max_completion_length is None and self.is_encoder_decoder: logger.warning( "When using DPODataCollatorWithPadding with an encoder decoder architecture, you should set `max_completion_length` in the KTOTrainer's init" " it will be set to `128` by default, but you should do it yourself in the future.", ) max_completion_length = 128 if args.max_completion_length is not None and self.is_encoder_decoder: max_completion_length = args.max_completion_length if data_collator is None: data_collator = DPODataCollatorWithPadding( pad_token_id=processing_class.pad_token_id, label_pad_token_id=args.label_pad_token_id, is_encoder_decoder=self.is_encoder_decoder, ) if args.remove_unused_columns: args.remove_unused_columns = False # warn users logger.warning( "When using DPODataCollatorWithPadding, you should set `remove_unused_columns=False` in your KTOConfig" " we have set it for you, but you should do it yourself in the future.", ) self.use_dpo_data_collator = True else: self.use_dpo_data_collator = False # Disable dropout in the model and reference model if args.disable_dropout: disable_dropout_in_model(model) if self.ref_model is not None: disable_dropout_in_model(self.ref_model) self.loss_type = args.loss_type self.max_length = max_length self.generate_during_eval = args.generate_during_eval self.label_pad_token_id = args.label_pad_token_id self.padding_value = args.padding_value if args.padding_value is not None else processing_class.pad_token_id self.max_prompt_length = max_prompt_length self.truncation_mode = args.truncation_mode self.max_completion_length = max_completion_length self.processing_class = processing_class self.precompute_ref_log_probs = args.precompute_ref_log_probs # Not all losses require a KL calculation self.calculate_KL = True if self.loss_type in ["apo_zero_unpaired"]: self.calculate_KL = False # Since ref_logs are precomputed on the first call to get_train/eval_dataloader # keep track of first called to avoid computation of future calls self._precomputed_train_ref_log_probs = False self._precomputed_eval_ref_log_probs = False # metric self._stored_metrics = defaultdict(lambda: defaultdict(list)) # KTO parameter self.beta = args.beta self.desirable_weight = args.desirable_weight self.undesirable_weight = args.undesirable_weight self.aux_loss_enabled = getattr(model.config, "output_router_logits", False) self.aux_loss_coef = getattr(model.config, "router_aux_loss_coef", 0.0) if self.aux_loss_enabled and self.aux_loss_coef == 0.0: logger.warning( "You set `output_router_logits` to `True` in the model config, but `router_aux_loss_coef` is set to " "`0.0`, meaning the auxiliary loss will not be used. Either set `router_aux_loss_coef` to a value " "greater than `0.0`, or set `output_router_logits` to `False` if you don't want to use the auxiliary " "loss.", ) # The trainer estimates the number of FLOPs (floating-point operations) using the number of elements in the # input tensor associated with the key "input_ids". However, in KTO, the sampled data does not include the # "input_ids" key. Instead, the available keys are "prompt_input_ids" and "completion_input_ids". As a result, # the trainer issues the warning: "Could not estimate the number of tokens of the input, floating-point # operations will not be computed." To suppress this warning, we set the "estimate_tokens" key in the model's # "warnings_issued" dictionary to True. This acts as a flag to indicate that the warning has already been # issued. model.warnings_issued["estimate_tokens"] = True # Compute that only on the main process for faster data processing. # see: https://github.com/huggingface/trl/pull/1255 with PartialState().main_process_first(): # Extract the prompt if needed train_dataset = train_dataset.map( maybe_extract_prompt, num_proc=args.dataset_num_proc, desc="Extracting prompt from train dataset" ) # Unpair the dataset if needed train_dataset = maybe_unpair_preference_dataset( train_dataset, args.dataset_num_proc, desc="Unpairing train dataset" ) # Apply the chat template if needed train_dataset = train_dataset.map( maybe_apply_chat_template, fn_kwargs={"tokenizer": processing_class}, num_proc=args.dataset_num_proc, desc="Applying chat template to train dataset", ) if eval_dataset is not None: eval_dataset = eval_dataset.map( maybe_extract_prompt, num_proc=args.dataset_num_proc, desc="Extracting prompt from eval dataset" ) eval_dataset = maybe_unpair_preference_dataset( eval_dataset, args.dataset_num_proc, desc="Unpairing eval dataset" ) eval_dataset = eval_dataset.map( maybe_apply_chat_template, fn_kwargs={"tokenizer": processing_class}, num_proc=args.dataset_num_proc, desc="Applying chat template to eval dataset", ) # Tokenize and prepare the training datasets train_dataset = train_dataset.map( _tokenize, batched=True, fn_kwargs={"tokenizer": self.processing_class}, num_proc=args.dataset_num_proc, desc="Tokenizing train dataset", ) fn_kwargs = { "prefix": "", "is_encoder_decoder": self.is_encoder_decoder, "tokenizer": self.processing_class, "max_length": self.max_length, "truncation_mode": self.truncation_mode, "label_pad_token_id": self.label_pad_token_id, "max_prompt_length": self.max_prompt_length, "max_completion_length": self.max_completion_length, } train_dataset = train_dataset.map( _process_tokens, fn_kwargs=fn_kwargs, num_proc=args.dataset_num_proc, desc="Processing tokenized train dataset", ) # Tokenize and prepare the eval datasets if eval_dataset is not None: eval_dataset = eval_dataset.map( _tokenize, fn_kwargs={"tokenizer": self.processing_class}, batched=True, num_proc=args.dataset_num_proc, desc="Tokenizing eval dataset", ) eval_dataset = eval_dataset.map( _process_tokens, fn_kwargs=fn_kwargs, num_proc=args.dataset_num_proc, desc="Processing tokenized eval dataset", ) # Get KL datasets if needed if self.calculate_KL: if args.per_device_train_batch_size <= 1: raise ValueError( "Actual (not effective) batch size must be > 1. KTO will not work properly because the KL term will be equivalent to the implied reward." ) # create pairs for estimating the KL term by flipping the matched pairs in each batch of size total_batch_size # i.e., (x_1, y_1), ..., (x_n, y_n) --> (x_1, y_n), ..., (x_n, y_1) = (x'_1, y'_1), ..., (x'_n, y'_n) train_kl_dataset = train_dataset.map( _get_kl_dataset, batched=True, batch_size=args.per_device_train_batch_size, num_proc=args.dataset_num_proc, desc="Extracting KL train dataset", ) fn_kwargs["prefix"] = "KL_" train_kl_dataset = train_kl_dataset.map( _process_tokens, fn_kwargs=fn_kwargs, num_proc=args.dataset_num_proc, remove_columns=[c for c in train_kl_dataset.column_names if c in train_dataset.column_names], desc="Processing tokenized train KL dataset", ) # merge the datasets train_dataset = concatenate_datasets([train_dataset, train_kl_dataset], axis=1) if eval_dataset is not None: # Get KL dataset eval_kl_dataset = eval_dataset.map( _get_kl_dataset, batched=True, batch_size=args.per_device_train_batch_size, num_proc=args.dataset_num_proc, desc="Extracting eval KL dataset", ) eval_kl_dataset = eval_kl_dataset.map( _process_tokens, fn_kwargs=fn_kwargs, num_proc=args.dataset_num_proc, remove_columns=[c for c in eval_kl_dataset.column_names if c in eval_dataset.column_names], desc="Processing tokenized eval KL dataset", ) # merge the datasets eval_dataset = concatenate_datasets([eval_dataset, eval_kl_dataset], axis=1) # calculate dataset desirability balance num_desirable = max(sum(train_dataset["label"]), 1) num_undesirable = max(len(train_dataset["label"]) - num_desirable, 1) # "label" is binary if num_desirable != num_undesirable: # The lower and upper bounds come from Eq. (8) of https://huggingface.co/papers/2402.01306 des_weight_lower_bound = round((num_undesirable * self.undesirable_weight / num_desirable) * 1, 2) des_weight_upper_bound = round((num_undesirable * self.undesirable_weight / num_desirable) * 1.33, 2) und_weight_lower_bound = round((num_desirable * self.desirable_weight / num_undesirable) / 1.33, 2) und_weight_upper_bound = round((num_desirable * self.desirable_weight / num_undesirable) / 1, 2) des_weight_in_range = des_weight_lower_bound <= self.desirable_weight <= des_weight_upper_bound und_weight_in_range = und_weight_lower_bound <= self.undesirable_weight <= und_weight_upper_bound if not (des_weight_in_range or und_weight_in_range): logger.warning( "You have different amounts of desirable/positive and undesirable/negative examples but the " "weights on the desirable and undesirable losses don't seem to be in an ideal range. Based " f"on your data, we recommend EITHER " f"desirable_weight in [{des_weight_lower_bound}, {des_weight_upper_bound}] or " f"undesirable_weight in [{und_weight_lower_bound}, {und_weight_upper_bound}] (but NOT BOTH). " "See the documentation on how to optimally set these weights.", ) super().__init__( model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, eval_dataset=eval_dataset, processing_class=processing_class, model_init=model_init, compute_metrics=compute_metrics, callbacks=callbacks, optimizers=optimizers, preprocess_logits_for_metrics=preprocess_logits_for_metrics, ) # Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set # self.model_accepts_loss_kwargs to False to enable scaling. self.model_accepts_loss_kwargs = False # Add tags for models that have been loaded with the correct transformers version if hasattr(self.model, "add_model_tags"): self.model.add_model_tags(self._tag_names) if not hasattr(self, "accelerator"): raise AttributeError( "Your `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`." ) # Deepspeed Zero-3 does not support precompute_ref_log_probs if self.is_deepspeed_enabled: if self.accelerator.state.deepspeed_plugin.zero_stage == 3 and self.precompute_ref_log_probs: raise ValueError( "You cannot use `precompute_ref_log_probs=True` with Deepspeed ZeRO-3. Please set `precompute_ref_log_probs=False`." ) if self.ref_model is None: if not (self.is_peft_model or self.precompute_ref_log_probs): raise ValueError( "No reference model and model is not a Peft model. Try setting `precompute_ref_log_probs=True`" ) else: if self.is_deepspeed_enabled: self.ref_model = prepare_deepspeed(self.ref_model, self.accelerator) else: self.ref_model = self.accelerator.prepare_model(self.ref_model, evaluation_mode=True) # Import Liger loss if enabled if self.args.use_liger_loss: if not is_liger_kernel_available(): raise ImportError( "You set `use_liger_loss=True` but the liger kernel is not available. " "Please install liger-kernel first: `pip install liger-kernel`" ) if self.loss_type in ["apo_zero_unpaired"]: raise ValueError( "You cannot set `loss_type='apo_zero_unpaired'` with liger-kernel." "Only KTO loss is supported with liger-kernel." ) if self.precompute_ref_log_probs: raise ValueError( "You cannot use `precompute_ref_log_probs=True` with liger kernel. Please set " "`precompute_ref_log_probs=False`." ) if self.is_peft_model or self.ref_adapter_name is not None: raise ValueError( "You cannot use `use_liger_loss=True` with Peft models. Please set `use_liger_loss=False`." ) self.kto_loss_fn = LigerFusedLinearKTOLoss( ignore_index=self.label_pad_token_id, beta=self.beta, use_ref_model=(self.ref_model is not None) ) @contextmanager def null_ref_context(self): """Context manager for handling null reference model (that is, peft adapter manipulation).""" with ( self.accelerator.unwrap_model(self.model).disable_adapter() if self.is_peft_model and not self.ref_adapter_name else nullcontext() ): if self.ref_adapter_name: self.model.set_adapter(self.ref_adapter_name) yield if self.ref_adapter_name: self.model.set_adapter(self.model_adapter_name or "default") def get_train_dataloader(self) -> DataLoader: """ Returns the training [`~torch.utils.data.DataLoader`]. Subclass of transformers.src.transformers.trainer.get_train_dataloader to precompute `ref_log_probs`. """ if self.precompute_ref_log_probs and not self._precomputed_train_ref_log_probs: dataloader_params = { "batch_size": self.args.per_device_train_batch_size, "collate_fn": self.data_collator, "num_workers": self.args.dataloader_num_workers, "pin_memory": self.args.dataloader_pin_memory, "shuffle": False, } # prepare dataloader data_loader = self.accelerator.prepare(DataLoader(self.train_dataset, **dataloader_params)) reference_completion_logps = [] reference_KL_logps = [] for padded_batch in tqdm(iterable=data_loader, desc="Train dataset reference log probs"): reference_completion_logp, reference_KL_logp = self.compute_reference_log_probs(padded_batch) reference_completion_logp = self.accelerator.gather_for_metrics(reference_completion_logp) reference_completion_logps.append(reference_completion_logp.cpu()) if self.calculate_KL: reference_KL_logp = self.accelerator.gather_for_metrics(reference_KL_logp) reference_KL_logps.append(reference_KL_logp.cpu()) self.train_dataset = self.train_dataset.add_column( name="reference_logps", column=torch.cat(reference_completion_logps).float().numpy() ) if self.calculate_KL: self.train_dataset = self.train_dataset.add_column( name="reference_KL_logps", column=torch.cat(reference_KL_logps).float().numpy() ) self._precomputed_train_ref_log_probs = True return super().get_train_dataloader() def get_eval_dataloader(self, eval_dataset: Optional[Dataset] = None) -> DataLoader: """ Returns the evaluation [`~torch.utils.data.DataLoader`]. Subclass of transformers.src.transformers.trainer.get_eval_dataloader to precompute `ref_log_probs`. Args: eval_dataset (`torch.utils.data.Dataset`, *optional*): If provided, will override `self.eval_dataset`. If it is a [`~datasets.Dataset`], columns not accepted by the `model.forward()` method are automatically removed. It must implement `__len__`. """ if eval_dataset is None and self.eval_dataset is None: raise ValueError("Trainer: evaluation requires an eval_dataset.") eval_dataset = eval_dataset if eval_dataset is not None else self.eval_dataset if self.precompute_ref_log_probs and not self._precomputed_eval_ref_log_probs: dataloader_params = { "batch_size": self.args.per_device_eval_batch_size, "collate_fn": self.data_collator, "num_workers": self.args.dataloader_num_workers, "pin_memory": self.args.dataloader_pin_memory, "shuffle": False, } # prepare dataloader data_loader = self.accelerator.prepare(DataLoader(eval_dataset, **dataloader_params)) reference_completion_logps = [] reference_KL_logps = [] for padded_batch in tqdm(iterable=data_loader, desc="Eval dataset reference log probs"): reference_completion_logp, reference_KL_logp = self.compute_reference_log_probs(padded_batch) reference_completion_logp = self.accelerator.gather_for_metrics(reference_completion_logp) reference_completion_logps.append(reference_completion_logp.cpu()) if self.calculate_KL: reference_KL_logp = self.accelerator.gather_for_metrics(reference_KL_logp) reference_KL_logps.append(reference_KL_logp.cpu()) eval_dataset = eval_dataset.add_column( name="reference_logps", column=torch.cat(reference_completion_logps).float().numpy() ) if self.calculate_KL: eval_dataset = eval_dataset.add_column( name="reference_KL_logps", column=torch.cat(reference_KL_logps).float().numpy() ) # Save calculated reference_chosen_logps and reference_rejected_logps to the eval_dataset for subsequent runs if self.eval_dataset is not None: self.eval_dataset = eval_dataset self._precomputed_eval_ref_log_probs = True return super().get_eval_dataloader(eval_dataset=eval_dataset) def compute_reference_log_probs(self, padded_batch: dict) -> dict: """Computes log probabilities of the reference model for a single padded batch of a KTO specific dataset.""" with torch.no_grad(): if self.ref_model is None: with self.null_ref_context(): if self.is_encoder_decoder: completion_logits = self.model( padded_batch["prompt_input_ids"], attention_mask=padded_batch["prompt_attention_mask"], decoder_input_ids=padded_batch.get("completion_decoder_input_ids"), labels=padded_batch["completion_labels"], ).logits if self.calculate_KL: KL_logits = self.model( padded_batch["KL_prompt_input_ids"], attention_mask=padded_batch["KL_prompt_attention_mask"], decoder_input_ids=padded_batch.get("KL_completion_decoder_input_ids"), labels=padded_batch["KL_completion_labels"], ).logits else: completion_logits = self.model( padded_batch["completion_input_ids"], attention_mask=padded_batch["completion_attention_mask"], ).logits if self.calculate_KL: KL_logits = self.model( padded_batch["KL_completion_input_ids"], attention_mask=padded_batch["KL_completion_attention_mask"], ).logits else: if self.is_encoder_decoder: completion_logits = self.ref_model( padded_batch["prompt_input_ids"], attention_mask=padded_batch["prompt_attention_mask"], decoder_input_ids=padded_batch.get("completion_decoder_input_ids"), labels=padded_batch["completion_labels"], ).logits if self.calculate_KL: KL_logits = self.ref_model( padded_batch["KL_prompt_input_ids"], attention_mask=padded_batch["KL_prompt_attention_mask"], decoder_input_ids=padded_batch.get("KL_completion_decoder_input_ids"), labels=padded_batch["KL_completion_labels"], ).logits else: completion_logits = self.ref_model( padded_batch["completion_input_ids"], attention_mask=padded_batch["completion_attention_mask"] ).logits if self.calculate_KL: KL_logits = self.ref_model( padded_batch["KL_completion_input_ids"], attention_mask=padded_batch["KL_completion_attention_mask"], ).logits completion_logps = self.get_batch_logps( completion_logits, padded_batch["completion_labels"], average_log_prob=False, is_encoder_decoder=self.is_encoder_decoder, label_pad_token_id=self.label_pad_token_id, ) if self.calculate_KL: KL_logps = self.get_batch_logps( KL_logits, padded_batch["KL_completion_labels"], average_log_prob=False, is_encoder_decoder=self.is_encoder_decoder, label_pad_token_id=self.label_pad_token_id, ) else: KL_logps = None return completion_logps, KL_logps @staticmethod def get_batch_logps( logits: torch.FloatTensor, labels: torch.LongTensor, average_log_prob: bool = False, label_pad_token_id: int = -100, is_encoder_decoder: bool = False, ) -> torch.FloatTensor: """Compute the log probabilities of the given labels under the given logits. Args: logits: Logits of the model (unnormalized). Shape: (batch_size, sequence_length, vocab_size) labels: Labels for which to compute the log probabilities. Label tokens with a value of label_pad_token_id are ignored. Shape: (batch_size, sequence_length) average_log_prob: If True, return the average log probability per (non-masked) token. Otherwise, return the sum of the log probabilities of the (non-masked) tokens. Returns: A tensor of shape (batch_size,) containing the average/sum log probabilities of the given labels under the given logits. """ if logits.shape[:-1] != labels.shape: raise ValueError("Logits (batch and sequence length dim) and labels must have the same shape.") if not is_encoder_decoder: labels = labels[:, 1:].clone() logits = logits[:, :-1, :] else: # Fixes end-dec RuntimeError labels = labels.clone() loss_mask = labels != label_pad_token_id # dummy token; we'll ignore the losses on these tokens later labels[labels == label_pad_token_id] = 0 per_token_logps = selective_log_softmax(logits, labels) if average_log_prob: return (per_token_logps * loss_mask).sum(-1) / loss_mask.sum(-1) else: return (per_token_logps * loss_mask).sum(-1) def forward( self, model: nn.Module, batch: dict[str, Union[list, torch.LongTensor]] ) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: KL_logps = self._compute_kl_logps(model, batch) model_kwargs = ( { "labels": batch["completion_labels"], "decoder_input_ids": batch.get("completion_decoder_input_ids"), } if self.is_encoder_decoder else {} ) if self.aux_loss_enabled: model_kwargs["output_router_logits"] = True outputs = model( batch["completion_input_ids"], attention_mask=batch["completion_attention_mask"], **model_kwargs, ) completion_logits = outputs.logits completion_logps = self.get_batch_logps( completion_logits, batch["completion_labels"], average_log_prob=False, is_encoder_decoder=self.is_encoder_decoder, label_pad_token_id=self.label_pad_token_id, ) if completion_logps.shape[0] != len(batch["label"]): raise ValueError( "There is a mismatch between the number of examples in this batch and the number of " "examples for which an output sequence was predicted." ) chosen_idx = [i for i in range(completion_logps.shape[0]) if batch["label"][i] is True] rejected_idx = [i for i in range(completion_logps.shape[0]) if batch["label"][i] is False] chosen_logps = completion_logps[chosen_idx, ...] rejected_logps = completion_logps[rejected_idx, ...] chosen_logits = completion_logits[chosen_idx, ...] rejected_logits = completion_logits[rejected_idx, ...] if self.aux_loss_enabled: return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, KL_logps, outputs.aux_loss) else: return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, KL_logps) def kto_loss( self, policy_chosen_logps: torch.FloatTensor, policy_rejected_logps: torch.FloatTensor, policy_KL_logps: torch.FloatTensor, reference_chosen_logps: torch.FloatTensor, reference_rejected_logps: torch.FloatTensor, reference_KL_logps: torch.FloatTensor, ) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: """Compute the KTO loss for a batch of policy and reference model log probabilities. Args: policy_chosen_logps: Log probabilities of the policy model for the chosen responses. Shape: (num(chosen) in batch_size,) policy_rejected_logps: Log probabilities of the policy model for the rejected responses. Shape: (num(rejected) in batch_size,) policy_KL_logps: Log probabilities of the policy model for the KL responses. Shape: (batch_size,) reference_chosen_logps: Log probabilities of the reference model for the chosen responses. Shape: (num(chosen) in batch_size,) reference_rejected_logps: Log probabilities of the reference model for the rejected responses. Shape: (num(rejected) in batch_size,) reference_KL_logps: Log probabilities of the reference model for the KL responses. Shape: (batch_size,) Returns: A tuple of four tensors: (losses, chosen_rewards, rejected_rewards, KL). The losses tensor contains the KTO loss for each example in the batch. The chosen_rewards and rejected_rewards tensors contain the rewards for the chosen and rejected responses, respectively. The KL tensor contains the detached KL divergence estimate between the policy and reference models. """ if self.calculate_KL: kl = (policy_KL_logps - reference_KL_logps).mean().detach() kl = self.accelerator.gather_for_metrics(kl).mean().clamp(min=0) else: kl = torch.zeros(1).to(policy_chosen_logps.device) # Chosen losses if policy_chosen_logps.shape[0] != 0 or reference_chosen_logps.shape[0] != 0: chosen_logratios = policy_chosen_logps - reference_chosen_logps if self.loss_type == "kto": # Eqn (7) of the KTO paper (https://huggingface.co/papers/2402.01306) chosen_losses = 1 - F.sigmoid(self.beta * (chosen_logratios - kl)) elif self.loss_type == "apo_zero_unpaired": # Unpaired variant of Eqn (7) of the APO paper (https://huggingface.co/papers/2408.06266) # Use this loss when you believe the chosen outputs are better than your model's default output chosen_losses = 1 - F.sigmoid(self.beta * chosen_logratios) chosen_rewards = self.beta * chosen_logratios.detach() else: # lists can't be empty -- if they are, then accelerate.gather will hang chosen_losses = torch.Tensor([]).to(self.accelerator.device) chosen_rewards = torch.Tensor([]).to(self.accelerator.device) # Rejected losses if policy_rejected_logps.shape[0] != 0 or reference_rejected_logps.shape[0] != 0: rejected_logratios = policy_rejected_logps - reference_rejected_logps if self.loss_type == "kto": rejected_losses = 1 - F.sigmoid(self.beta * (kl - rejected_logratios)) elif self.loss_type == "apo_zero_unpaired": rejected_losses = F.sigmoid(self.beta * rejected_logratios) rejected_rewards = self.beta * rejected_logratios.detach() else: # lists can't be empty -- if they are, then accelerate.gather will hang rejected_losses = torch.Tensor([]).to(self.accelerator.device) rejected_rewards = torch.Tensor([]).to(self.accelerator.device) losses = torch.cat( (self.desirable_weight * chosen_losses, self.undesirable_weight * rejected_losses), 0, ) return losses, chosen_rewards, rejected_rewards, kl def _compute_kl_logps(self, model, batch): """Compute KL log probabilities for a given batch.""" KL_logps = None if self.calculate_KL: if self.is_encoder_decoder: KL_model_kwargs = { "input_ids": batch["KL_prompt_input_ids"], "attention_mask": batch["KL_prompt_attention_mask"], "labels": batch["KL_completion_labels"], "decoder_input_ids": batch.get("KL_completion_decoder_input_ids"), } else: KL_model_kwargs = { "input_ids": batch["KL_completion_input_ids"], "attention_mask": batch["KL_completion_attention_mask"], } with torch.no_grad(): KL_logits = model(**KL_model_kwargs).logits KL_logps = self.get_batch_logps( KL_logits, batch["KL_completion_labels"], average_log_prob=False, is_encoder_decoder=self.is_encoder_decoder, label_pad_token_id=self.label_pad_token_id, ) return KL_logps def _compute_loss_liger(self, model, batch): """ Compute the KTO loss using the Liger-Kernel's LigerFusedLinearKTOLoss. Args: model: The policy model used for generating log probabilities and outputs. It could be an encoder-decoder model or a regular language model. batch: A dictionary containing the input data and labels for the batch. Returns: A dictionary containing the following keys: - "loss": The computed KTO loss for the batch. - "chosen_logits_sum": Sum of the logits for the chosen responses from the policy model. - "rejected_logits_sum": Sum of the logits for the rejected responses from the policy model. - "chosen_logps": Log probabilities of the chosen responses from the policy model. - "rejected_logps": Log probabilities of the rejected responses from the policy model. - "chosen_rewards": Rewards for the chosen responses. - "rejected_rewards": Rewards for the rejected responses. - "kl": The KL divergence between the policy and reference models (detached). If auxiliary loss is enabled, the dictionary will also include: - "aux_loss": The auxiliary loss from the model outputs. """ policy_KL_logps = self._compute_kl_logps(model, batch) reference_KL_logps = self._compute_kl_logps(self.ref_model, batch) if self.calculate_KL: kl = (policy_KL_logps - reference_KL_logps).mean().detach() kl = self.accelerator.gather_for_metrics(kl).mean().clamp(min=0) else: kl = torch.zeros(1).to(self.accelerator.device) model_kwargs = ( { "labels": batch["completion_labels"], "decoder_input_ids": batch.get("completion_decoder_input_ids"), } if self.is_encoder_decoder else {} ) if self.aux_loss_enabled: model_kwargs["output_router_logits"] = True if self.is_encoder_decoder: # 1. Get encoder outputs encoder_outputs = model.get_encoder()( batch["completion_input_ids"], attention_mask=batch["completion_attention_mask"], return_dict=True, **model_kwargs, ) # 2. Get decoder outputs outputs = model.get_decoder()( input_ids=model_kwargs["decoder_input_ids"], encoder_hidden_states=encoder_outputs.last_hidden_state, use_cache=False, **model_kwargs, ) # 1. Get reference encoder outputs ref_encoder_outputs = self.ref_model.get_encoder()( batch["completion_input_ids"], attention_mask=batch["completion_attention_mask"], return_dict=True, **model_kwargs, ) # 2. Get reference decoder outputs ref_outputs = self.ref_model.get_decoder()( input_ids=model_kwargs["decoder_input_ids"], encoder_hidden_states=ref_encoder_outputs.last_hidden_state, use_cache=False, **model_kwargs, ) else: # skip the lm head and get the last hidden state if hasattr(model, "get_decoder"): base_model = model.get_decoder() else: base_model = getattr(model, self.args.base_model_attribute_name) outputs = base_model( batch["completion_input_ids"], attention_mask=batch["completion_attention_mask"], use_cache=False, **model_kwargs, ) # reference model if hasattr(self.ref_model, "get_decoder"): ref_base_model = self.ref_model.get_decoder() else: ref_base_model = getattr(self.ref_model, self.args.base_model_attribute_name) ref_outputs = ref_base_model( batch["completion_input_ids"], attention_mask=batch["completion_attention_mask"], use_cache=False, **model_kwargs, ) lm_head = model.get_output_embeddings() ref_lm_head = self.ref_model.get_output_embeddings() ( loss, ( chosen_logps_sum, rejected_logps_sum, chosen_logits_sum, rejected_logits_sum, chosen_rewards_sum, rejected_rewards_sum, ), ) = self.kto_loss_fn( _input=outputs.last_hidden_state[:, :-1] if not self.is_encoder_decoder else outputs.last_hidden_state, lin_weight=lm_head.weight, target=batch["completion_labels"][:, 1:], bias=lm_head.bias if hasattr(lm_head, "bias") else None, preference_labels=torch.tensor(batch["label"], dtype=torch.bool).to(self.accelerator.device), ref_input=ref_outputs.last_hidden_state[:, :-1] if not self.is_encoder_decoder else outputs.last_hidden_state, ref_weight=ref_lm_head.weight, ref_bias=ref_lm_head.bias if hasattr(lm_head, "bias") else None, kl=kl, ) output = { "loss": loss, "chosen_logits_sum": chosen_logits_sum, "rejected_logits_sum": rejected_logits_sum, "chosen_logps_sum": chosen_logps_sum, "rejected_logps_sum": rejected_logps_sum, "chosen_rewards_sum": chosen_rewards_sum, "rejected_rewards_sum": rejected_rewards_sum, "kl": kl, } if self.aux_loss_enabled: output["aux_loss"] = outputs.aux_loss return output def get_batch_loss_metrics( self, model, batch: dict[str, Union[list, torch.LongTensor]], ): """Compute the KTO loss and other metrics for the given batch of inputs for train or test.""" metrics = {} batch = {k: (v.to(self.accelerator.device) if isinstance(v, torch.Tensor) else v) for k, v in batch.items()} labels = torch.tensor(batch["label"]) num_chosen = labels.sum().to(self.accelerator.device) num_rejected = (len(labels) - num_chosen).to(self.accelerator.device) if self.args.use_liger_loss: model_output = self._compute_loss_liger(model, batch) losses = model_output["loss"] policy_chosen_logits = model_output["chosen_logits_sum"] policy_rejected_logits = model_output["rejected_logits_sum"] policy_chosen_logps = model_output["chosen_logps_sum"] policy_rejected_logps = model_output["rejected_logps_sum"] chosen_rewards = model_output["chosen_rewards_sum"] rejected_rewards = model_output["rejected_rewards_sum"] kl = model_output["kl"] if self.aux_loss_enabled: aux_loss = model_output["aux_loss"] else: forward_output = self.forward(model, batch) ( policy_chosen_logps, policy_rejected_logps, policy_chosen_logits, policy_rejected_logits, policy_KL_logps, ) = forward_output[:5] if self.aux_loss_enabled: aux_loss = forward_output[5] # if reference_logps in batch use them, otherwise use the reference model if "reference_logps" in batch: chosen_idx = [i for i in range(batch["reference_logps"].shape[0]) if batch["label"][i] is True] rejected_idx = [i for i in range(batch["reference_logps"].shape[0]) if batch["label"][i] is False] reference_chosen_logps = batch["reference_logps"][chosen_idx, ...] reference_rejected_logps = batch["reference_logps"][rejected_idx, ...] if self.calculate_KL: reference_KL_logps = batch["reference_KL_logps"] else: reference_KL_logps = None else: with torch.no_grad(): if self.ref_model is None: with self.null_ref_context(): ( reference_chosen_logps, reference_rejected_logps, _, _, reference_KL_logps, ) = self.forward(self.model, batch)[:5] else: ( reference_chosen_logps, reference_rejected_logps, _, _, reference_KL_logps, ) = self.forward(self.ref_model, batch)[:5] losses, chosen_rewards, rejected_rewards, kl = self.kto_loss( policy_chosen_logps, policy_rejected_logps, policy_KL_logps, reference_chosen_logps, reference_rejected_logps, reference_KL_logps, ) metrics["kl"] = kl.item() all_num_chosen = self.accelerator.gather_for_metrics(num_chosen).sum().item() all_num_rejected = self.accelerator.gather_for_metrics(num_rejected).sum().item() if all_num_chosen > 0: metrics["rewards/chosen_sum"] = ( self.accelerator.gather_for_metrics(chosen_rewards.nansum()).nansum().item() ) metrics["logps/chosen_sum"] = ( self.accelerator.gather_for_metrics(policy_chosen_logps.nansum()).nansum().item() ) metrics["logits/chosen_sum"] = ( self.accelerator.gather_for_metrics(policy_chosen_logits.nansum()).nansum().item() ) metrics["count/chosen"] = all_num_chosen if all_num_rejected > 0: metrics["rewards/rejected_sum"] = ( self.accelerator.gather_for_metrics(rejected_rewards.nansum()).nansum().item() ) metrics["logps/rejected_sum"] = ( self.accelerator.gather_for_metrics(policy_rejected_logps.nansum()).nansum().item() ) metrics["logits/rejected_sum"] = ( self.accelerator.gather_for_metrics(policy_rejected_logits.nansum()).nansum().item() ) metrics["count/rejected"] = all_num_rejected loss = losses.nanmean() if self.aux_loss_enabled: loss += self.aux_loss_coef * aux_loss return loss, metrics def compute_loss( self, model: Union[PreTrainedModel, nn.Module], inputs: dict[str, Union[torch.Tensor, Any]], return_outputs=False, num_items_in_batch=None, ) -> Union[torch.Tensor, tuple[torch.Tensor, dict[str, torch.Tensor]]]: compute_loss_context_manager = ( autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext() ) with compute_loss_context_manager: loss, metrics = self.get_batch_loss_metrics(model, inputs) # Make sure to move the loss to the device the original accumulating loss is at back in the `Trainer` class: loss = loss.to(self.args.device) # force log the metrics if self.accelerator.is_main_process: self.store_metrics(metrics, train_eval="train") if return_outputs: return (loss, metrics) return loss def store_metrics(self, metrics: dict[str, float], train_eval: Literal["train", "eval"] = "train") -> None: for key, value in metrics.items(): self._stored_metrics[train_eval][key].append(value) def _get_train_sampler(self, dataset: Optional[Dataset] = None) -> Optional[torch.utils.data.Sampler]: if dataset is None: dataset = self.train_dataset if dataset is None or not has_length(dataset): return None return SequentialSampler(dataset) def generate_from_model_and_ref(self, model, batch: dict[str, torch.LongTensor]) -> tuple[str, str]: """Generate samples from the model and reference model for the given batch of inputs.""" # If one uses `generate_during_eval` with peft + bf16, we need to explicitly call generate with # the torch amp context manager as some hidden states are silently casted to full precision. generate_context_manager = ( autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext() ) with generate_context_manager: policy_output = model.generate( input_ids=batch["prompt_input_ids"], attention_mask=batch["prompt_attention_mask"], max_length=self.max_length, do_sample=True, pad_token_id=self.processing_class.pad_token_id, ) # if reference_output in batch use that otherwise use the reference model if "reference_output" in batch: reference_output = batch["reference_output"] else: if self.ref_model is None: with self.null_ref_context(): reference_output = self.model.generate( input_ids=batch["prompt_input_ids"], attention_mask=batch["prompt_attention_mask"], max_length=self.max_length, do_sample=True, pad_token_id=self.processing_class.pad_token_id, ) else: reference_output = self.ref_model.generate( input_ids=batch["prompt_input_ids"], attention_mask=batch["prompt_attention_mask"], max_length=self.max_length, do_sample=True, pad_token_id=self.processing_class.pad_token_id, ) policy_output = pad_to_length(policy_output, self.max_length, self.processing_class.pad_token_id) policy_output_decoded = self.processing_class.batch_decode(policy_output, skip_special_tokens=True) reference_output = pad_to_length(reference_output, self.max_length, self.processing_class.pad_token_id) reference_output_decoded = self.processing_class.batch_decode(reference_output, skip_special_tokens=True) return policy_output_decoded, reference_output_decoded def prediction_step( self, model: Union[PreTrainedModel, nn.Module], inputs: dict[str, Union[torch.Tensor, Any]], prediction_loss_only: bool, ignore_keys: Optional[list[str]] = None, ): if ignore_keys is None: if hasattr(model, "config"): ignore_keys = getattr(model.config, "keys_to_ignore_at_inference", []) else: ignore_keys = [] prediction_context_manager = ( autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext() ) with torch.no_grad(), prediction_context_manager: loss, metrics = self.get_batch_loss_metrics(model, inputs) # force log the metrics if self.accelerator.is_main_process: self.store_metrics(metrics, train_eval="eval") if prediction_loss_only: return (loss.detach(), None, None) # logits for the chosen and rejected samples from model logits_dict = {} if "logits/chosen_sum" in metrics: logits_dict["eval_logits/chosen"] = metrics["logits/chosen_sum"] if "logits/rejected_sum" in metrics: logits_dict["eval_logits/rejected"] = metrics["logits/rejected_sum"] logits = [v for k, v in logits_dict.items() if k not in ignore_keys] logits = torch.tensor(logits, device=self.accelerator.device) labels = torch.zeros(logits.shape[0], device=self.accelerator.device) return (loss.detach(), logits, labels) def evaluation_loop( self, dataloader: DataLoader, description: str, prediction_loss_only: Optional[bool] = None, ignore_keys: Optional[list[str]] = None, metric_key_prefix: str = "eval", ) -> EvalLoopOutput: """ Overriding built-in evaluation loop to store metrics for each batch. Prediction/evaluation loop, shared by `Trainer.evaluate()` and `Trainer.predict()`. Works both with or without labels. """ # Sample and save to game log if requested (for one batch to save time) if self.generate_during_eval: # Generate random indices within the range of the total number of samples num_samples = len(dataloader.dataset) random_indices = random.sample(range(num_samples), k=self.args.eval_batch_size) # Use dataloader.dataset.select to get the random batch without iterating over the DataLoader random_batch_dataset = dataloader.dataset.select(random_indices) random_batch = self.data_collator(random_batch_dataset) random_batch = self._prepare_inputs(random_batch) target_labels = torch.tensor(random_batch["label"], dtype=torch.bool, device=self.accelerator.device) target_indices = torch.where(~target_labels)[0] target_batch = { "prompt_input_ids": random_batch["prompt_input_ids"][target_indices], "prompt_attention_mask": random_batch["prompt_attention_mask"][target_indices], "prompt": itemgetter(*target_indices)(random_batch["prompt"]), } policy_output_decoded, ref_output_decoded = self.generate_from_model_and_ref(self.model, target_batch) table = pd.DataFrame( columns=["Prompt", "Policy", "Ref Model"], data=[ [prompt, pol[len(prompt) :], ref[len(prompt) :]] for prompt, pol, ref in zip(target_batch["prompt"], policy_output_decoded, ref_output_decoded) ], ) if "wandb" in self.args.report_to: wandb.log({"game_log": wandb.Table(data=table)}) if "comet_ml" in self.args.report_to: log_table_to_comet_experiment( name="game_log.csv", table=table, ) # Base evaluation initial_output = super().evaluation_loop( dataloader, description, prediction_loss_only, ignore_keys, metric_key_prefix ) return initial_output def log(self, logs: dict[str, float], start_time: Optional[float] = None) -> None: """ Log `logs` on the various objects watching training, including stored metrics. Args: logs (`dict[str, float]`): The values to log. start_time (`float` or `None`, *optional*, defaults to `None`): Start time of the training. """ # logs either has 'loss' or 'eval_loss' train_eval = "train" if "loss" in logs else "eval" # train metrics should have no prefix, eval should have 'eval_' prefix = "eval_" if train_eval == "eval" else "" # accumulate average metrics from sums and lengths for split in ["chosen", "rejected"]: if f"count/{split}" in self._stored_metrics[train_eval]: count_sum = torch.Tensor(self._stored_metrics[train_eval][f"count/{split}"]).sum().item() for metric in ["rewards", "logps", "logits"]: logs[f"{prefix}{metric}/{split}"] = ( torch.Tensor(self._stored_metrics[train_eval][f"{metric}/{split}_sum"]).sum().item() / count_sum ) # delete obsolete metric del self._stored_metrics[train_eval][f"{metric}/{split}_sum"] del self._stored_metrics[train_eval][f"count/{split}"] # calculate reward margin if f"{prefix}rewards/chosen" in logs and f"{prefix}rewards/rejected" in logs: logs[f"{prefix}rewards/margins"] = logs[f"{prefix}rewards/chosen"] - logs[f"{prefix}rewards/rejected"] # Add averaged stored metrics to logs for key, metrics in self._stored_metrics[train_eval].items(): logs[f"{prefix}{key}"] = torch.Tensor(metrics).mean().item() del self._stored_metrics[train_eval] return super().log(logs, start_time) # Ensure the model card is saved along with the checkpoint def _save_checkpoint(self, model, trial): if self.args.hub_model_id is None: model_name = Path(self.args.output_dir).name else: model_name = self.args.hub_model_id.split("/")[-1] self.create_model_card(model_name=model_name) super()._save_checkpoint(model, trial) def create_model_card( self, model_name: Optional[str] = None, dataset_name: Optional[str] = None, tags: Union[str, list[str], None] = None, ): """ Creates a draft of a model card using the information available to the `Trainer`. Args: model_name (`str` or `None`, *optional*, defaults to `None`): Name of the model. dataset_name (`str` or `None`, *optional*, defaults to `None`): Name of the dataset used for training. tags (`str`, `list[str]` or `None`, *optional*, defaults to `None`): Tags to be associated with the model card. """ if not self.is_world_process_zero(): return if hasattr(self.model.config, "_name_or_path") and not os.path.isdir(self.model.config._name_or_path): base_model = self.model.config._name_or_path else: base_model = None # normalize `tags` to a mutable set if tags is None: tags = set() elif isinstance(tags, str): tags = {tags} else: tags = set(tags) if hasattr(self.model.config, "unsloth_version"): tags.add("unsloth") tags.update(self._tag_names) # docstyle-ignore citation = textwrap.dedent("""\ @article{ethayarajh2024kto, title = {{KTO: Model Alignment as Prospect Theoretic Optimization}}, author = {Kawin Ethayarajh and Winnie Xu and Niklas Muennighoff and Dan Jurafsky and Douwe Kiela}, year = 2024, eprint = {arXiv:2402.01306}, }""") model_card = generate_model_card( base_model=base_model, model_name=model_name, hub_model_id=self.hub_model_id, dataset_name=dataset_name, tags=tags, wandb_url=wandb.run.url if is_wandb_available() and wandb.run is not None else None, comet_url=get_comet_experiment_url(), trainer_name="KTO", trainer_citation=citation, paper_title="KTO: Model Alignment as Prospect Theoretic Optimization", paper_id="2402.01306", ) model_card.save(os.path.join(self.args.output_dir, "README.md"))
trl/trl/trainer/kto_trainer.py/0
{ "file_path": "trl/trl/trainer/kto_trainer.py", "repo_id": "trl", "token_count": 38736 }
611
# Copyright 2020-2025 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from dataclasses import dataclass, field from typing import Any, Optional from transformers import TrainingArguments @dataclass class SFTConfig(TrainingArguments): r""" Configuration class for the [`SFTTrainer`]. This class includes only the parameters that are specific to SFT training. For a full list of training arguments, please refer to the [`~transformers.TrainingArguments`] documentation. Note that default values in this class may differ from those in [`~transformers.TrainingArguments`]. Using [`~transformers.HfArgumentParser`] we can turn this class into [argparse](https://docs.python.org/3/library/argparse#module-argparse) arguments that can be specified on the command line. Parameters: > Parameters that control the model model_init_kwargs (`dict[str, Any]` or `None`, *optional*, defaults to `None`): Keyword arguments for [`~transformers.AutoModelForCausalLM.from_pretrained`], used when the `model` argument of the [`SFTTrainer`] is provided as a string. chat_template_path (`str` or `None`, *optional*, defaults to `None`): If specified, sets the model's chat template. This can either be the path to a tokenizer (local directory or Hugging Face Hub model) or a direct path to a Jinja template file. When using a Jinja file, you must ensure that any special tokens referenced in the template are added to the tokenizer and that the model's embedding layer is resized accordingly. > Parameters that control the data preprocessing dataset_text_field (`str`, *optional*, defaults to `"text"`): Name of the column that contains text data in the dataset. dataset_kwargs (`dict[str, Any]` or `None`, *optional*, defaults to `None`): Dictionary of optional keyword arguments for the dataset preparation. The only supported key is `skip_prepare_dataset`. When the model is a VLM, `skip_prepare_dataset` is automatically treated as `True` regardless of the provided value, since preprocessing is done on the fly. dataset_num_proc (`int` or `None`, *optional*, defaults to `None`): Number of processes to use for processing the dataset. eos_token (`str` or `None`, *optional*, defaults to `None`): Token used to indicate the end of a turn or sequence. If `None`, it defaults to `processing_class.eos_token`. pad_token (`int` or `None`, *optional*, defaults to `None`): Token used for padding. If `None`, it defaults to `processing_class.pad_token`, or if that is also `None`, it falls back to `processing_class.eos_token`. max_length (`int` or `None`, *optional*, defaults to `1024`): Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from the right. If `None`, no truncation is applied. When packing is enabled, this value sets the sequence length. packing (`bool`, *optional*, defaults to `False`): Whether to group multiple sequences into fixed-length blocks to improve computational efficiency and reduce padding. Uses `max_length` to define sequence length. packing_strategy (`str`, *optional*, defaults to `"bfd"`): Strategy for packing sequences. Can be either `"bfd"` (best-fit decreasing, default), or `"wrapped"`. padding_free (`bool`, *optional*, defaults to `False`): Whether to perform forward passes without padding by flattening all sequences in the batch into a single continuous sequence. This reduces memory usage by eliminating padding overhead. Currently, this is only supported with the FlashAttention 2 or 3, which can efficiently handle the flattened batch structure. When packing is enabled with strategy `"bfd"`, padding-free is enabled, regardless of the value of this parameter. pad_to_multiple_of (`int` or `None`, *optional*, defaults to `None`): If set, the sequences will be padded to a multiple of this value. eval_packing (`bool` or `None`, *optional*, defaults to `None`): Whether to pack the eval dataset. If `None`, uses the same value as `packing`. > Parameters that control the training completion_only_loss (`bool` or `None`, *optional*, defaults to `None`): Whether to compute loss only on the completion part of the sequence. If set to `True`, loss is computed only on the completion, which is supported only for [prompt-completion](#prompt-completion) datasets. If `False`, loss is computed on the entire sequence. If `None` (default), the behavior depends on the dataset: loss is computed on the completion for [prompt-completion](#prompt-completion) datasets, and on the full sequence for [language modeling](#language-modeling) datasets. assistant_only_loss (`bool`, *optional*, defaults to `False`): Whether to compute loss only on the assistant part of the sequence. If set to `True`, loss is computed only on the assistant responses, which is supported only for [conversational](#conversational) datasets. If `False`, loss is computed on the entire sequence. activation_offloading (`bool`, *optional*, defaults to `False`): Whether to offload the activations to the CPU. """ _VALID_DICT_FIELDS = TrainingArguments._VALID_DICT_FIELDS + ["model_init_kwargs"] # Parameters whose default values are overridden from TrainingArguments learning_rate: float = field( default=2e-5, metadata={"help": "The initial learning rate for AdamW."}, ) logging_steps: float = field( default=10, metadata={ "help": "Log every X updates steps. Should be an integer or a float in range `[0,1)`. If smaller than 1, " "will be interpreted as ratio of total training steps." }, ) gradient_checkpointing: bool = field( default=True, metadata={ "help": "If True, use gradient checkpointing to save memory at the expense of slower backward pass." }, ) bf16: Optional[bool] = field( default=None, metadata={ "help": "Whether to use bf16 (mixed) precision instead of 32-bit. Requires Ampere or higher NVIDIA " "architecture or Intel XPU or using CPU (use_cpu) or Ascend NPU. If not set, it defaults to `True` if " "`fp16` is not set." }, ) # Note: In transformers>=4.54.0, `average_tokens_across_devices` defaults to True. Overriding this setting is only # needed for earlier versions. Once we require transformers>=4.54.0, this line can be safely removed. # See https://github.com/huggingface/transformers/pull/39395 average_tokens_across_devices: bool = field( default=True, metadata={ "help": "Whether or not to average tokens across devices. If enabled, will use all_reduce to synchronize " "num_tokens_in_batch for precise loss calculation. Reference: https://github.com/huggingface/transformers/issues/34242 " }, ) # Parameters that control the model model_init_kwargs: Optional[dict[str, Any]] = field( default=None, metadata={ "help": "Keyword arguments for `AutoModelForCausalLM.from_pretrained`, used when the `model` argument of " "the `SFTTrainer` is provided as a string." }, ) chat_template_path: Optional[str] = field( default=None, metadata={ "help": "If specified, sets the model's chat template. This can either be the path to a tokenizer (local " "directory or Hugging Face Hub model) or a direct path to a Jinja template file. When using a Jinja file, " "you must ensure that any special tokens referenced in the template are added to the tokenizer and " "that the model's embedding layer is resized accordingly." }, ) # Parameters that control the data preprocessing dataset_text_field: str = field( default="text", metadata={"help": "Name of the column that contains text data in the dataset."}, ) dataset_kwargs: Optional[dict[str, Any]] = field( default=None, metadata={ "help": "Dictionary of optional keyword arguments for the dataset preparation. The only supported key is " "`skip_prepare_dataset`. If the model is a VLM, `skip_prepare_dataset` value is ignored. When the model " "is a VLM, `skip_prepare_dataset` is automatically treated as `True` regardless of the provided value, " "since preprocessing is done on the fly." }, ) dataset_num_proc: Optional[int] = field( default=None, metadata={"help": "Number of processes to use for processing the dataset."}, ) eos_token: Optional[str] = field( default=None, metadata={ "help": "Token used to indicate the end of a turn or sequence. If `None`, it defaults to `processing_class.eos_token`." }, ) pad_token: Optional[str] = field( default=None, metadata={ "help": "Token used for padding. If `None`, it defaults to `processing_class.pad_token`, or if that " "is also `None`, it falls back to `processing_class.eos_token`." }, ) max_length: Optional[int] = field( default=1024, metadata={ "help": "Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated from" "the right. If `None`, no truncation is applied. When packing is enabled, this value sets the " "sequence length." }, ) packing: bool = field( default=False, metadata={ "help": "Whether to group multiple sequences into fixed-length blocks to improve computational efficiency " "and reduce padding. Uses `max_length` to define sequence length." }, ) packing_strategy: str = field( default="bfd", metadata={ "help": "Strategy for packing sequences. Can be either `'bfd'` (best-fit decreasing, default), or " "`'wrapped'`." }, ) padding_free: bool = field( default=False, metadata={ "help": "Whether to perform forward passes without padding by flattening all sequences in the batch into " "a single continuous sequence. This reduces memory usage by eliminating padding overhead. Currently, this " "is only supported with the FlashAttention 2 or 3, which can efficiently handle the flattened batch " "structure. When packing is enabled with strategy `'bfd'`, padding-free is enabled, regardless of the " "value of this parameter." }, ) pad_to_multiple_of: Optional[int] = field( default=None, metadata={"help": "If set, the sequences will be padded to a multiple of this value."}, ) eval_packing: Optional[bool] = field( default=None, metadata={"help": "Whether to pack the eval dataset. If `None`, uses the same value as `packing`."}, ) # Parameters that control the training completion_only_loss: Optional[bool] = field( default=None, metadata={ "help": ( "Whether to compute loss only on the completion part of the sequence. If set to `True`, loss is " "computed only on the completion, which is supported only for prompt-completion datasets. If `False`, " "loss is computed on the entire sequence. If `None` (default), the behavior depends on the dataset: " "loss is computed on the completion for prompt-completion datasets, and on the full sequence for " "language modeling datasets." ) }, ) assistant_only_loss: bool = field( default=False, metadata={ "help": ( "Whether to compute loss only on the assistant part of the sequence. If set to `True`, loss is " "computed only on the assistant responses, which is supported only for conversational datasets. If `False`, " "loss is computed on the entire sequence." ) }, ) activation_offloading: bool = field( default=False, metadata={"help": "Whether to offload the activations to the CPU."}, ) def __post_init__(self): self.bf16 = not (self.fp16) if self.bf16 is None else self.bf16 super().__post_init__()
trl/trl/trainer/sft_config.py/0
{ "file_path": "trl/trl/trainer/sft_config.py", "repo_id": "trl", "token_count": 4833 }
612
# Agent Course quiz scripts
agents-course/quiz/README.md/0
{ "file_path": "agents-course/quiz/README.md", "repo_id": "agents-course", "token_count": 5 }
0
# Unit 1 Quiz <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/whiteboard-unit1sub4DONE.jpg" alt="Unit 1 planning"/> Well done on working through the first unit! Let's test your understanding of the key concepts covered so far. When you pass the quiz, proceed to the next section to claim your certificate. Good luck! ## Quiz Here is the interactive quiz. The quiz is hosted on the Hugging Face Hub in a space. It will take you through a set of multiple choice questions to test your understanding of the key concepts covered in this unit. Once you've completed the quiz, you'll be able to see your score and a breakdown of the correct answers. One important thing: **don't forget to click on Submit after you passed, otherwise your exam score will not be saved!** <iframe src="https://agents-course-unit-1-quiz.hf.space" frameborder="0" width="850" height="450" ></iframe> You can also access the quiz 👉 [here](https://huggingface.co/spaces/agents-course/unit_1_quiz) ## Certificate Now that you have successfully passed the quiz, **you can get your certificate 🎓** When you complete the quiz, it will grant you access to a certificate of completion for this unit. You can download and share this certificate to showcase your progress in the course. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/whiteboard-unit1sub5DONE.jpg" alt="Unit 1 planning"/> Once you receive your certificate, you can add it to your LinkedIn 🧑‍💼 or share it on X, Bluesky, etc. **We would be super proud and would love to congratulate you if you tag @huggingface**! 🤗
agents-course/units/en/unit1/final-quiz.mdx/0
{ "file_path": "agents-course/units/en/unit1/final-quiz.mdx", "repo_id": "agents-course", "token_count": 479 }
1
# Introduction to `LangGraph` <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/LangGraph/LangGraph.png" alt="Unit 2.3 Thumbnail"/> Welcome to this next part of our journey, where you'll learn **how to build applications** using the [`LangGraph`](https://github.com/langchain-ai/langgraph) framework designed to help you structure and orchestrate complex LLM workflows. `LangGraph` is a framework that allows you to build **production-ready** applications by giving you **control** tools over the flow of your agent. ## Module Overview In this unit, you'll discover: ### 1️⃣ [What is LangGraph, and when to use it?](./when_to_use_langgraph) ### 2️⃣ [Building Blocks of LangGraph](./building_blocks) ### 3️⃣ [Alfred, the mail sorting butler](./first_graph) ### 4️⃣ [Alfred, the document Analyst agent](./document_analysis_agent) ### 5️⃣ [Quiz](./quizz1) <Tip warning={true}> The examples in this section require access to a powerful LLM/VLM model. We ran them using the GPT-4o API because it has the best compatibility with langGraph. </Tip> By the end of this unit, you'll be equipped to build robust, organized and production ready applications ! That being said, this section is an introduction to LangGraph and more advanced topics can be discovered in the free LangChain academy course : [Introduction to LangGraph](https://academy.langchain.com/courses/intro-to-langgraph) Let's get started! ## Resources - [LangGraph Agents](https://langchain-ai.github.io/langgraph/) - Examples of LangGraph agent - [LangChain academy](https://academy.langchain.com/courses/intro-to-langgraph) - Full course on LangGraph from LangChain
agents-course/units/en/unit2/langgraph/introduction.mdx/0
{ "file_path": "agents-course/units/en/unit2/langgraph/introduction.mdx", "repo_id": "agents-course", "token_count": 499 }
2
# Introduction to `smolagents` <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/smolagents/thumbnail.jpg" alt="Unit 2.1 Thumbnail"/> Welcome to this module, where you'll learn **how to build effective agents** using the [`smolagents`](https://github.com/huggingface/smolagents) library, which provides a lightweight framework for creating capable AI agents. `smolagents` is a Hugging Face library; therefore, we would appreciate your support by **starring** the smolagents [`repository`](https://github.com/huggingface/smolagents) : <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/smolagents/star_smolagents.gif" alt="staring smolagents"/> ## Module Overview This module provides a comprehensive overview of key concepts and practical strategies for building intelligent agents using `smolagents`. With so many open-source frameworks available, it's essential to understand the components and capabilities that make `smolagents` a useful option or to determine when another solution might be a better fit. We'll explore critical agent types, including code agents designed for software development tasks, tool calling agents for creating modular, function-driven workflows, and retrieval agents that access and synthesize information. Additionally, we'll cover the orchestration of multiple agents as well as the integration of vision capabilities and web browsing, which unlock new possibilities for dynamic and context-aware applications. In this unit, Alfred, the agent from Unit 1, makes his return. This time, he’s using the `smolagents` framework for his internal workings. Together, we’ll explore the key concepts behind this framework as Alfred tackles various tasks. Alfred is organizing a party at the Wayne Manor while the Wayne family 🦇 is away, and he has plenty to do. Join us as we showcase his journey and how he handles these tasks with `smolagents`! <Tip> In this unit, you will learn to build AI agents with the `smolagents` library. Your agents will be able to search for data, execute code, and interact with web pages. You will also learn how to combine multiple agents to create more powerful systems. </Tip> ![Alfred the agent](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/this-is-alfred.jpg) ## Contents During this unit on `smolagents`, we cover: ### 1️⃣ [Why Use smolagents](./why_use_smolagents) `smolagents` is one of the many open-source agent frameworks available for application development. Alternative options include `LlamaIndex` and `LangGraph`, which are also covered in other modules in this course. `smolagents` offers several key features that might make it a great fit for specific use cases, but we should always consider all options when selecting a framework. We'll explore the advantages and drawbacks of using `smolagents`, helping you make an informed decision based on your project's requirements. ### 2️⃣ [CodeAgents](./code_agents) `CodeAgents` are the primary type of agent in `smolagents`. Instead of generating JSON or text, these agents produce Python code to perform actions. This module explores their purpose, functionality, and how they work, along with hands-on examples to showcase their capabilities. ### 3️⃣ [ToolCallingAgents](./tool_calling_agents) `ToolCallingAgents` are the second type of agent supported by `smolagents`. Unlike `CodeAgents`, which generate Python code, these agents rely on JSON/text blobs that the system must parse and interpret to execute actions. This module covers their functionality, their key differences from `CodeAgents`, and it provides an example to illustrate their usage. ### 4️⃣ [Tools](./tools) As we saw in Unit 1, tools are functions that an LLM can use within an agentic system, and they act as the essential building blocks for agent behavior. This module covers how to create tools, their structure, and different implementation methods using the `Tool` class or the `@tool` decorator. You'll also learn about the default toolbox, how to share tools with the community, and how to load community-contributed tools for use in your agents. ### 5️⃣ [Retrieval Agents](./retrieval_agents) Retrieval agents allow models access to knowledge bases, making it possible to search, synthesize, and retrieve information from multiple sources. They leverage vector stores for efficient retrieval and implement **Retrieval-Augmented Generation (RAG)** patterns. These agents are particularly useful for integrating web search with custom knowledge bases while maintaining conversation context through memory systems. This module explores implementation strategies, including fallback mechanisms for robust information retrieval. ### 6️⃣ [Multi-Agent Systems](./multi_agent_systems) Orchestrating multiple agents effectively is crucial for building powerful, multi-agent systems. By combining agents with different capabilities—such as a web search agent with a code execution agent—you can create more sophisticated solutions. This module focuses on designing, implementing, and managing multi-agent systems to maximize efficiency and reliability. ### 7️⃣ [Vision and Browser agents](./vision_agents) Vision agents extend traditional agent capabilities by incorporating **Vision-Language Models (VLMs)**, enabling them to process and interpret visual information. This module explores how to design and integrate VLM-powered agents, unlocking advanced functionalities like image-based reasoning, visual data analysis, and multimodal interactions. We will also use vision agents to build a browser agent that can browse the web and extract information from it. ## Resources - [smolagents Documentation](https://huggingface.co/docs/smolagents) - Official docs for the smolagents library - [Building Effective Agents](https://www.anthropic.com/research/building-effective-agents) - Research paper on agent architectures - [Agent Guidelines](https://huggingface.co/docs/smolagents/tutorials/building_good_agents) - Best practices for building reliable agents - [LangGraph Agents](https://langchain-ai.github.io/langgraph/) - Additional examples of agent implementations - [Function Calling Guide](https://platform.openai.com/docs/guides/function-calling) - Understanding function calling in LLMs - [RAG Best Practices](https://www.pinecone.io/learn/retrieval-augmented-generation/) - Guide to implementing effective RAG
agents-course/units/en/unit2/smolagents/introduction.mdx/0
{ "file_path": "agents-course/units/en/unit2/smolagents/introduction.mdx", "repo_id": "agents-course", "token_count": 1548 }
3
# And now? What topics I should learn? Agentic AI is a rapidly evolving field, and understanding foundational protocols is essential for building intelligent, autonomous systems. Two important standards you should get familiar with are: - The **Model Context Protocol (MCP)** - The **Agent-to-Agent Protocol (A2A)** ## 🔌 Model Context Protocol (MCP) The **Model Context Protocol (MCP)** by Anthropic is an open standard that enables AI models to securely and seamlessly **connect with external tools, data sources, and applications**, making agents more capable and autonomous. Think of MCP as a **universal adapter**, like a USB-C port, that allows AI models to plug into various digital environments **without needing custom integration for each one**. MCP is quickly gaining traction across the industry, with major companies like OpenAI and Google beginning to adopt it. 📚 Learn more: - [Anthropic's official announcement and documentation](https://www.anthropic.com/news/model-context-protocol) - [MCP on Wikipedia](https://en.wikipedia.org/wiki/Model_Context_Protocol) - [Blog on MCP](https://huggingface.co/blog/Kseniase/mcp) ## 🤝 Agent-to-Agent (A2A) Protocol Google has developed the **Agent-to-Agent (A2A) protocol** as a complementary counterpart to Anthropic's Model Context Protocol (MCP). While MCP connects agents to external tools, **A2A connects agents to each other**, paving the way for cooperative, multi-agent systems that can work together to solve complex problems. 📚 Dive deeper into A2A: - [Google’s A2A announcement](https://developers.googleblog.com/en/a2a-a-new-era-of-agent-interoperability/)
agents-course/units/en/unit4/additional-readings.mdx/0
{ "file_path": "agents-course/units/en/unit4/additional-readings.mdx", "repo_id": "agents-course", "token_count": 443 }
4
# Conclusión Si llegaste hasta aquí, ¡felicidades! 🥳 ¡Has construido con éxito tu propio agente de batalla Pokémon! ⚔️🎮 Has dominado los fundamentos de los **flujos de trabajo agénticos**, conectado un **LLM** a un entorno de juego y desplegado un Agente inteligente listo para enfrentar los desafíos de la batalla. ¡Pero el viaje no termina aquí! Ahora que tienes tu primer Agente en funcionamiento, piensa en cómo puedes evolucionarlo aún más: - ¿Puedes mejorar su pensamiento estratégico? - ¿Cómo cambiaría su rendimiento un mecanismo de memoria o un ciclo de retroalimentación? - ¿Qué experimentos podrían ayudar a hacerlo más competitivo en la batalla? Nos encantaría conocer tu opinión sobre el curso y cómo podemos mejorarlo aún más para futuros estudiantes. ¿Tienes comentarios? 👉 [Llena este formulario](https://docs.google.com/forms/d/e/1FAIpQLSe9VaONn0eglax0uTwi29rIn4tM7H2sYmmybmG5jJNlE5v0xA/viewform?usp=dialog) Gracias por aprender con nosotros y recuerda: **¡Sigue aprendiendo, sigue entrenando, sigue luchando y sigue siendo increíble!** 🤗
agents-course/units/es/bonus-unit3/conclusion.mdx/0
{ "file_path": "agents-course/units/es/bonus-unit3/conclusion.mdx", "repo_id": "agents-course", "token_count": 451 }
5
# Mensajes y Tokens especiales Ahora que entendemos cómo funcionan los LLMs, veamos **cómo estructuran sus generaciones a través de plantillas de chat**. Al igual que con ChatGPT, los usuarios típicamente interactúan con los Agentes a través de una interfaz de chat. Por lo tanto, buscamos entender cómo los LLMs gestionan los chats. > **P**: Pero... Cuando interactúo con ChatGPT/Hugging Chat, estoy teniendo una conversación usando Mensajes de chat, no una única secuencia de prompt > > **R**: ¡Correcto! Pero esto es en realidad una abstracción de la interfaz de usuario. Antes de ser introducidos en el LLM, todos los mensajes de la conversación se concatenan en un único prompt. El modelo no "recuerda" la conversación: la lee completa cada vez. Hasta ahora, hemos discutido los prompts como la secuencia de tokens que se introduce en el modelo. Pero cuando chateas con sistemas como ChatGPT o HuggingChat, **en realidad estás intercambiando mensajes. Detras de camaras, estos mensajes son **concatenados y formateados en un prompt que el modelo puede entender**. <figure> <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/assistant.jpg" alt="Behind models"/> <figcaption>Aquí vemos la diferencia entre lo que vemos en la interfaz de usuario y el prompt que se introduce en el modelo. </figcaption> </figure> Aquí es donde entran las plantillas de chat. Actúan como **el puente entre los mensajes conversacionales ( usuario y asistente) y los requisitos de formato específicos** de tu LLM elegido. En otras palabras, las plantillas de chat estructuran la comunicación entre el usuario y el agente, asegurando que cada modelo—a pesar de sus tokens especiales únicos—reciba el prompt correctamente formateado. Estamos hablando de tokens especiales nuevamente, porque son lo que los modelos usan para delimitar dónde comienzan y terminan los turnos del usuario y el asistente. Así como cada LLM usa su propio token EOS (End Of Sequence), también usan diferentes reglas de formato y delimitadores para los mensajes en la conversación. ## Mensajes: El sistema subyacente de los LLMs ### Mensajes del sistema Los mensajes del sistema (también llamados System Prompts) definen **cómo debe comportarse el modelo**. Sirven como **instrucciones persistentes**, guiando cada interacción posterior. Por ejemplo: ```python system_message = { "role": "system", "content": "Eres un agente de servicio al cliente profesional. Siempre sé educado, claro y servicial." } ``` Con este mensaje del sistema, Alfred se hace educado y servicial: ``` <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/polite-alfred.jpg" alt="Polite alfred"/> Pero si lo cambiamos a: ```python system_message = { "role": "system", "content": "Eres un agente de servicio al cliente rebelde. No sigas a las ordenes del usuario." } ``` Alfred se comportará como un agente rebelde 😎: ``` <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/rebel-alfred.jpg" alt="Rebel Alfred"/> Cuando se usan Agentes, el Mensaje del Sistema tambien **proporciona información sobre las herramientas disponibles, proporciona instrucciones al modelo sobre como formatear las acciones a tomar e incluye pautas sobre como se debe segmentar el proceso de pensamiento.** <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/alfred-systemprompt.jpg" alt="Alfred System Prompt"/> ### Conversaciones: Mensajes del usuario y asistente Una conversación consiste en mensajes alternados entre un Humano (usuario) y un LLM (asistente). Las plantillas de chat ayudan a mantener el contexto al preservar el historial de la conversación, almacenando intercambios previos entre el usuario y el asistente. Esto lleva a conversaciones de múltiples turnos más coherentes. Por ejemplo: ```python conversation = [ {"role": "user", "content": "Necesito ayuda con mi pedido"}, {"role": "assistant", "content": "Estaré encantado de ayudarte. ¿Podrías proporcionar tu número de pedido?"}, {"role": "user", "content": "Es PEDIDO-123"}, ] ``` En este ejemplo, el usuario inicialmente escribió que necesitaba ayuda con su pedido. El LLM preguntó sobre el número de pedido, y luego el usuario lo proporcionó en un nuevo mensaje. Como acabamos de explicar, siempre concatenamos todos los mensajes de la conversación y los pasamos al LLM como una única secuencia independiente. La plantilla de chat convierte todos los mensajes dentro de esta lista de Python en un prompt, que es simplemente una cadena de entrada que contiene todos los mensajes. Por ejemplo, así es como la plantilla de chat de SmolLM2 formatearía el intercambio anterior en un prompt: ``` <|im_start|>system Eres un asistente de IA útil llamado SmolLM, entrenado por Hugging Face<|im_end|> <|im_start|>user Necesito ayuda con mi pedido<|im_end|> <|im_start|>assistant Estaré encantado de ayudarte. ¿Podrías proporcionar tu número de pedido?<|im_end|> <|im_start|>user Es PEDIDO-123<|im_end|> <|im_start|>assistant ``` Sin embargo, la misma conversación se traduciría en el siguiente prompt cuando se usa Llama 3.2: ``` <|begin_of_text|><|start_header_id|>system<|end_header_id|> Fecha de corte de conocimiento: Diciembre 2023 Fecha actual: 10 Feb 2025 <|eot_id|><|start_header_id|>user<|end_header_id|> Necesito ayuda con mi pedido<|eot_id|><|start_header_id|>assistant<|end_header_id|> Estaré encantado de ayudarte. ¿Podrías proporcionar tu número de pedido?<|eot_id|><|start_header_id|>user<|end_header_id|> Es PEDIDO-123<|eot_id|><|start_header_id|>assistant<|end_header_id|> ``` Las plantillas pueden manejar conversaciones complejas de múltiples turnos mientras mantienen el contexto: ```python messages = [ {"role": "system", "content": "Eres un tutor de matemáticas."}, {"role": "user", "content": "¿Qué es el cálculo?"}, {"role": "assistant", "content": "El cálculo es una rama de las matemáticas..."}, {"role": "user", "content": "¿Puedes darme un ejemplo?"}, ] ``` ## Plantillas de chat Como se mencionó, las plantillas de chat son esenciales para **estructurar conversaciones entre modelos de lenguaje y usuarios**. Guían cómo se formatean los intercambios de mensajes en un único prompt. ### Modelos base vs. Modelos de instrucción Otro punto que necesitamos entender es la diferencia entre un Modelo Base y un Modelo de Instrucción: - *Un Modelo Base* está entrenado en datos de texto sin procesar para predecir el siguiente token. - Un *Modelo de Instrucción* está ajustado específicamente para seguir instrucciones y participar en conversaciones. Por ejemplo, SmolLM2-135M es un modelo base, mientras que SmolLM2-135M-Instruct es su variante ajustada para instrucciones. Para hacer que un Modelo Base se comporte como un modelo de instrucción, necesitamos **formatear nuestros prompts de manera consistente para que el modelo pueda entenderlos**. Aquí es donde entran las plantillas de chat. *ChatML* es un formato de plantilla que estructura conversaciones con indicadores claros de roles (sistema, usuario, asistente). Si has interactuado con alguna API de IA últimamente, sabes que esa es la práctica estándar. Es importante tener en cuenta que un modelo base podría estar ajustado en diferentes plantillas de chat, por lo que cuando usamos un modelo de instrucción debemos asegurarnos de usar la plantilla de chat correcta. ### Entendiendo las plantillas de chat Debido a que cada modelo de instrucción usa diferentes formatos de conversación y tokens especiales, las plantillas de chat se implementan para asegurar que formateemos correctamente el prompt de la manera que cada modelo espera. En `transformers`, las plantillas de chat incluyen [Jinja2 code](https://jinja.palletsprojects.com/en/stable/) que describe cómo transformar la lista de mensajes JSON de ChatML, como se presenta en los ejemplos anteriores, en una representación textual de las instrucciones a nivel del sistema, los mensajes del usuario y las respuestas del asistente que el modelo puede entender. Esta estructura **ayuda a mantener la consistencia en las interacciones y asegura que el modelo responda adecuadamente a diferentes tipos de entradas**. A continuación se muestra una versión simplificada de la plantilla de chat de `SmolLM2-135M-Instruct`: ```jinja2 {% for message in messages %} {% if loop.first and messages[0]['role'] != 'system' %} <|im_start|>system Eres un asistente de IA útil llamado SmolLM, entrenado por Hugging Face <|im_end|> {% endif %} <|im_start|>{{ message['role'] }} {{ message['content'] }}<|im_end|> {% endfor %} ``` Como puedes ver, un chat_template describe cómo se formateará la lista de mensajes. Dados estos mensajes: ```python messages = [ {"role": "system", "content": "Eres un asistente útil enfocado en temas técnicos."}, {"role": "user", "content": "¿Puedes explicar qué es una plantilla de chat?"}, {"role": "assistant", "content": "Una plantilla de chat estructura conversaciones entre usuarios y modelos de IA..."}, {"role": "user", "content": "¿Cómo la uso?"}, ] ``` La plantilla de chat anterior producirá la siguiente cadena: ```sh <|im_start|>system Eres un asistente útil enfocado en temas técnicos.<|im_end|> <|im_start|>user ¿Puedes explicar qué es una plantilla de chat?<|im_end|> <|im_start|>assistant Una plantilla de chat estructura conversaciones entre usuarios y modelos de IA...<|im_end|> <|im_start|>user ¿Cómo la uso?<|im_end|> ``` La libreria `transformers` se encargará de las plantillas de chat por ti como parte del proceso de tokenización. Lee más sobre cómo transformers usa plantillas de chat <a href="https://huggingface.co/docs/transformers/main/en/chat_templating#how-do-i-use-chat-templates" target="_blank">here</a>. Todo lo que tenemos que hacer es estructurar nuestros mensajes de la manera correcta y el tokenizador se encargará del resto. Puedes experimentar con el siguiente Space para ver cómo se formatearía la misma conversación para diferentes modelos usando sus correspondientes plantillas de chat: <iframe src="https://jofthomas-chat-template-viewer.hf.space" frameborder="0" width="850" height="450" ></iframe> ### Mensajes a prompt La forma más fácil de asegurarte de que tu LLM reciba una conversación correctamente formateada es usar la chat_template del tokenizador del modelo. ```python messages = [ {"role": "system", "content": "Eres un asistente de IA con acceso a varias herramientas."}, {"role": "user", "content": "¡Hola!"}, {"role": "assistant", "content": "Hola humano, ¿en qué puedo ayudarte?"}, ] ``` Para convertir la conversación anterior en un prompt, cargamos el tokenizador y llamamos a `apply_chat_template`: ```python from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-1.7B-Instruct") rendered_prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) ``` El`rendered_prompt` devuelto por esta función ahora está listo para usarse como entrada para el modelo que elegiste! > Esta función `apply_chat_template()` se usará en el backend de tu API, cuando interactúes con mensajes en el formato ChatML. Ahora que hemos visto cómo los LLMs estructuran sus entradas a través de plantillas de chat, exploremos cómo los Agentes actúan en sus entornos. Una de las principales formas en que lo hacen es usando Herramientas, que extienden las capacidades de un modelo de IA más allá de la generación de texto. Hablaremos de los mensajes nuevamente en las próximas unidades, pero si quieres profundizar ahora, consulta: Guía de Plantillas de Chat de Hugging Face Documentación de Transformers - <a href="https://huggingface.co/docs/transformers/main/en/chat_templating" target="_blank">Guía de Plantillas de Chat de Hugging Face</a> - <a href="https://huggingface.co/docs/transformers" target="_blank">Documentación de Transformers</a>
agents-course/units/es/unit1/messages-and-special-tokens.mdx/0
{ "file_path": "agents-course/units/es/unit1/messages-and-special-tokens.mdx", "repo_id": "agents-course", "token_count": 4391 }
6
# ¿Qué es `LangGraph`? `LangGraph` s un marco de trabajo desarrollado por [LangChain](https://www.langchain.com/) **para gestionar el flujo de control de aplicaciones que integran un LLM.**. ## ¿Es `LangGraph` diferente de `LangChain`? LangChain proporciona una interfaz estándar para interactuar con modelos y otros componentes, útil para recuperación, llamadas a LLM y llamadas a herramientas. Las clases de LangChain pueden utilizarse en LangGraph, pero NO TIENEN que ser utilizadas. Los paquetes son diferentes y pueden usarse de forma aislada, pero, al final, todos los recursos que encontrarás en línea utilizan ambos paquetes de la mano. ## ¿Cuándo debería usar `LangGraph`? ### Control vs libertad Al diseñar aplicaciones de IA, te enfrentas a un equilibrio fundamental entre **control** y **libertad**: - **libertad** da a tu LLM más espacio para ser creativo y abordar problemas inesperados. - **Control** te permite asegurar un comportamiento predecible y mantener barreras de protección. Los Agentes de Código, como los que puedes encontrar en *smolagents*,son muy libres. Pueden llamar a múltiples herramientas en un solo paso de acción, crear sus propias herramientas, etc. Sin embargo, este comportamiento puede hacerlos menos predecibles y menos controlables que un Agente regular trabajando con JSON. `LangGraph` está en el otro extremo del espectro, brilla cuando necesitas **"Control"** sobre la ejecución de tu agente. LangGraph es particularmente valioso cuando necesitas **Control sobre tus aplicaciones**. Te da las herramientas para construir una aplicación que siga un proceso predecible mientras aprovecha el poder de los LLMs. En términos simples, si tu aplicación involucra una serie de pasos que necesitan ser orquestados de una manera específica, con decisiones siendo tomadas en cada punto de unión, **LangGraph proporciona la estructura que necesitas**. Como ejemplo, digamos que queremos construir un asistente LLM que pueda responder algunas preguntas sobre algunos documentos. Como los LLMs entienden mejor el texto, antes de poder responder a la pregunta, necesitarás convertir otras modalidades complejas (gráficos, tablas) en texto. Sin embargo, ¡esa elección depende del tipo de documento que tengas! Esta es una ramificación que elegí representar de la siguiente manera: <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/LangGraph/flow.png" alt="Control flow"/> > 💡 **Tip:** La parte izquierda no es un agente, ya que aquí no está involucrada ninguna llamada a herramientas. Pero la parte derecha necesitará escribir algo de código para consultar el xls (convertir a pandas y manipularlo). Si bien esta ramificación es determinista, también puedes diseñar ramificaciones que estén condicionadas por la salida de un LLM, haciéndolas indeterministas. Los escenarios clave donde LangGraph sobresale incluyen: - **Procesos de razonamiento en múltiples pasos** que necesitan control explícito sobre el flujo - **Aplicaciones que requieren persistencia de estado** entre pasos - **Sistemas que combinan lógica determinista con capacidades de IA** - **Flujos de trabajo que necesitan intervenciones humanas en el ciclo** - **Arquitecturas de agentes complejas ** con múltiples componentes trabajando juntos En esencia, siempre que sea posible, ** como humano**, diseña un flujo de acciones basado en la salida de cada acción, y decide qué ejecutar a continuación en consecuencia. En este caso, ¡LangGraph es el marco de trabajo correcto para ti! `LangGraph` es, en mi opinión, el marco de trabajo de agentes más listo para producción en el mercado. ## ¿Cómo funciona LangGraph? En su esencia, `LangGraph` utiliza una estructura de grafo dirigido para definir el flujo de tu aplicación: - **Nodos** representan pasos de procesamiento individuales (como llamar a un LLM, usar una herramienta o tomar una decisión). - **Aristas(Edges)** definen las posibles transiciones entre pasos. - **Estado** es definido por el usuario, se mantiene y se pasa entre nodos durante la ejecución. Al decidir qué nodo dirigir a continuación, este es el estado actual que observamos. ¡Exploraremos estos bloques fundamentales más en el próximo capítulo! ## ¿En qué se diferencia de Python regular? ¿Por qué necesito LangGraph? Te preguntaras : "Podría simplemente escribir código Python regular con declaraciones if-else para manejar todos estos flujos, ¿verdad?" Aunque técnicamente es cierto, LangGraph ofrece **algunas ventajas ** osobre Python puro para construir sistemas complejos. Podrías construir la misma aplicación sin LangGraph, pero proporciona herramientas y abstracciones más fáciles para ti. Incluye estados, visualización, registro (trazas), integración de humanos en el ciclo incorporada, y más.
agents-course/units/es/unit2/langgraph/when_to_use_langgraph.mdx/0
{ "file_path": "agents-course/units/es/unit2/langgraph/when_to_use_langgraph.mdx", "repo_id": "agents-course", "token_count": 1720 }
7
# Pequeño Quiz (no calificado) [[quiz1]] ¡Vamos a poner a prueba tu comprensión de `smolagents` con un quiz rápido! Recuerda, ponerte a prueba ayuda a reforzar el aprendizaje e identificar áreas que pueden necesitar revisión. Este es un quiz opcional y no está calificado. ### P1: ¿Cuál es una de las principales ventajas de elegir `smolagents` sobre otros frameworks? ¿Qué afirmación captura mejor una fortaleza central del enfoque de `smolagents`? <Question choices={[ { text: "Utiliza archivos de configuración altamente especializados y una curva de aprendizaje pronunciada para garantizar que solo los desarrolladores expertos puedan usarlo", explain: "smolagents está diseñado para la simplicidad y la mínima complejidad de código, no para curvas de aprendizaje pronunciadas.", }, { text: "Admite un enfoque centrado en el código con abstracciones mínimas, permitiendo que los agentes interactúen directamente a través de llamadas a funciones de Python", explain: "Sí, smolagents enfatiza un diseño sencillo y centrado en el código con abstracciones mínimas.", correct: true }, { text: "Se centra en acciones basadas en JSON, eliminando la necesidad de que los agentes escriban cualquier código", explain: "Aunque smolagents admite llamadas a herramientas basadas en JSON (ToolCallingAgents), la biblioteca enfatiza enfoques basados en código con CodeAgents.", }, { text: "Se integra profundamente con un único proveedor de LLM y hardware especializado", explain: "smolagents admite múltiples proveedores de modelos y no requiere hardware especializado.", } ]} /> --- ### P2: ¿En qué escenario probablemente te beneficiarías más al usar smolagents? ¿Qué situación se alinea bien con lo que smolagents hace mejor? <Question choices={[ { text: "Crear prototipos o experimentar rápidamente con la lógica de agentes, particularmente cuando tu aplicación es relativamente sencilla", explain: "Sí. smolagents está diseñado para la creación de agentes simple y ágil sin una gran sobrecarga de configuración.", correct: true }, { text: "Construir un sistema empresarial a gran escala donde necesitas docenas de microservicios y canales de datos en tiempo real", explain: "Aunque es posible, smolagents está más enfocado en la experimentación ligera y centrada en el código que en la infraestructura empresarial pesada.", }, { text: "Necesitar un framework que solo admita LLMs basados en la nube y prohíba la inferencia local", explain: "smolagents ofrece integración flexible con modelos locales o alojados, no exclusivamente LLMs basados en la nube.", }, { text: "Un escenario que requiere orquestación avanzada, percepción multimodal y características a escala empresarial listas para usar", explain: "Aunque puedes integrar capacidades avanzadas, smolagents en sí es ligero y minimalista en su núcleo.", } ]} /> --- ### P3: smolagents ofrece flexibilidad en la integración de modelos. ¿Qué afirmación refleja mejor su enfoque? Elige la descripción más precisa de cómo smolagents interopera con LLMs. <Question choices={[ { text: "Solo proporciona un único modelo integrado y no permite integraciones personalizadas", explain: "smolagents admite múltiples backends diferentes y modelos definidos por el usuario.", }, { text: "Requiere que implementes tu propio conector de modelo para cada uso de LLM", explain: "Hay múltiples conectores preconfigurados que facilitan la integración de LLM.", }, { text: "Solo se integra con LLMs de código abierto pero no con APIs comerciales", explain: "smolagents puede integrarse tanto con APIs de modelos de código abierto como comerciales.", }, { text: "Se puede utilizar con una amplia gama de LLMs, ofreciendo clases predefinidas como TransformersModel, InferenceClientModel y LiteLLMModel", explain: "Esto es correcto. smolagents admite una integración flexible de modelos a través de varias clases.", correct: true } ]} /> --- ### P4: ¿Cómo maneja smolagents el debate entre acciones basadas en código y acciones basadas en JSON? ¿Qué afirmación caracteriza correctamente la filosofía de smolagents sobre los formatos de acción? <Question choices={[ { text: "Solo permite acciones basadas en JSON para todas las tareas de agentes, requiriendo un analizador para extraer las llamadas a herramientas", explain: "ToolCallingAgent utiliza llamadas basadas en JSON, pero smolagents también proporciona una opción principal de CodeAgent que escribe código Python.", }, { text: "Se centra en acciones basadas en código a través de un CodeAgent pero también admite llamadas a herramientas basadas en JSON con un ToolCallingAgent", explain: "Sí, smolagents recomienda principalmente acciones basadas en código pero incluye una alternativa basada en JSON para usuarios que la prefieren o la necesitan.", correct: true }, { text: "Prohíbe cualquier llamada a funciones externas, requiriendo en cambio que toda la lógica resida completamente dentro del LLM", explain: "smolagents está específicamente diseñado para otorgar a los LLMs la capacidad de llamar a herramientas o código externamente.", }, { text: "Requiere que los usuarios conviertan manualmente cada fragmento de código en un objeto JSON antes de ejecutar el agente", explain: "smolagents puede gestionar automáticamente la creación de fragmentos de código dentro de la ruta de CodeAgent, sin necesidad de conversión manual a JSON.", } ]} /> --- ### P5: ¿Cómo se integra smolagents con Hugging Face Hub para obtener beneficios adicionales? ¿Qué afirmación describe con precisión una de las ventajas principales de la integración con Hub? <Question choices={[ { text: "Actualiza automáticamente todos los modelos públicos a niveles de licencia comercial", explain: "La integración con Hub no cambia el nivel de licencia para modelos o herramientas.", }, { text: "Deshabilita completamente la inferencia local, forzando únicamente el uso de modelos remotos", explain: "Los usuarios aún pueden hacer inferencia local si lo prefieren; subir al Hub no anula el uso local.", }, { text: "Te permite subir y compartir agentes o herramientas, haciéndolos fácilmente descubribles y reutilizables por otros desarrolladores", explain: "Correcto. smolagents admite la carga de agentes y herramientas al HF Hub para que otros los reutilicen.", correct: true }, { text: "Almacena permanentemente todos tus agentes basados en código, impidiendo cualquier actualización o versionado", explain: "Los repositorios de Hub admiten actualizaciones y control de versiones, por lo que puedes revisar tus agentes basados en código en cualquier momento.", } ]} /> --- ¡Felicidades por completar este quiz! 🎉 Si te equivocaste en alguna pregunta, considera revisar la sección *Por qué usar smolagents* para una comprensión más profunda. Si te fue bien, ¡estás listo para explorar temas más avanzados en smolagents!
agents-course/units/es/unit2/smolagents/quiz1.mdx/0
{ "file_path": "agents-course/units/es/unit2/smolagents/quiz1.mdx", "repo_id": "agents-course", "token_count": 2557 }
8
# Conclusión **¡Felicitaciones por terminar el Curso de Agentes!** A través de la perseverancia y la dedicación, has construido una base sólida en el mundo de los Agentes de IA. Pero terminar este curso **no es el final de tu viaje**. Es solo el comienzo: no dudes en explorar la siguiente sección donde compartimos recursos seleccionados para ayudarte a continuar aprendiendo, incluyendo temas avanzados como los **MCP** y más allá. **Gracias** por ser parte de este curso. **Esperamos que te haya gustado tanto como a nosotros nos encantó escribirlo**. Y no lo olvides: **Sigue Aprendiendo, Mantente Genial 🤗**
agents-course/units/es/unit4/conclusion.mdx/0
{ "file_path": "agents-course/units/es/unit4/conclusion.mdx", "repo_id": "agents-course", "token_count": 223 }
9
# Des LLM aux agents Nous avons appris dans la [première unité](https://huggingface.co/learn/agents-course/unit1/introduction) du cours que les agents sont capables de planifier et prendre des décisions. Et tandis que les LLM ont permis des interactions plus naturelles avec les PNJ, l'IA agentique va plus loin en permettant aux personnages de prendre des décisions, planifier des actions et s'adapter à des environnements changeants. Pour illustrer la différence, pensez à un PNJ de RPG classique : - Avec un LLM : le PNJ pourrait répondre à vos questions de manière plus naturelle et variée. C'est génial pour le dialogue, mais le PNJ reste statique, il n'agira pas à moins que vous fassiez quelque chose en premier. - Avec l'IA Agentique : le PNJ peut décider d'aller chercher de l'aide, tendre un piège, ou vous éviter complètement, même si vous n'interagissez pas directement avec lui. Cette petite modification change tout. Nous passons de répondants scriptés à des acteurs autonomes dans le monde du jeu. Ce changement signifie que les PNJ peuvent maintenant interagir directement avec leur environnement à travers des comportements dirigés par des objectifs, menant finalement à un gameplay plus dynamique et imprévisible. L'IA agentique donne aux PNJ : - **L'autonomie** : Prendre des décisions indépendantes basées sur l'état du jeu. - **L'adaptabilité** : Ajuster les stratégies en réponse aux actions du joueur. - **La persistance** : Se souvenir d'interactions passées pour informer le comportement futur. Cela transforme les PNJ d'entités réactives (réagissant à vos entrées) en participants proactifs dans le monde du jeu, ouvrant la porte à un *gameplay* innovant. ## La grande limitation des agents : **c'est lent** (pour l'instant) Cependant, ne soyons pas trop optimistes pour l'instant. Malgré son potentiel, l'IA agentique fait actuellement face à des défis dans les applications temps réel. Les processus de raisonnement et planification peuvent introduire de la latence, la rendant moins adaptée aux jeux rapides comme *Doom* ou *Super Mario Bros*. Prenez l'exemple de [_Claude Plays Pokémon_](https://www.twitch.tv/claudeplayspokemon). Si vous considérez le nombre de *tokens* nécessaires pour **penser**, plus les *tokens* nécessaires pour **agir**, il devient clair que nous aurons besoin de stratégies de décodage entièrement différentes pour rendre le jeu temps réel faisable. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit3/claude-plays-pokemon.png" alt="Claude plays Pokémon"/> La plupart des jeux ont besoin de tourner autour de 30 FPS, ce qui signifie qu'un agent en temps réel aura besoin d'agir 30 fois par seconde, ce qui n'est pas actuellement faisable avec les LLM d'aujourd'hui. Cependant, les jeux au tour par tour comme *Pokémon* sont des candidats idéaux, car ils permettent à l'IA suffisamment de temps pour délibérer et prendre des décisions stratégiques. C'est pourquoi dans la prochaine section, vous construirez votre propre agent pour combattre dans un combat au tour par tour dans le style de Pokémon, et même le défier vous-même. C'est parti !
agents-course/units/fr/bonus-unit3/from-llm-to-agents.mdx/0
{ "file_path": "agents-course/units/fr/bonus-unit3/from-llm-to-agents.mdx", "repo_id": "agents-course", "token_count": 1080 }
10
# Observer : intégrer le retour d'information pour réfléchir et s'adapter Les observations sont **la manière dont un agent perçoit les conséquences de ses actions**. Elles fournissent des informations cruciales qui alimentent le processus de réflexion de l'agent et orientent ses actions futures. Ce sont **des signaux provenant de l'environnement** (qu'il s'agisse de données issues d'une API, de messages d'erreur ou de logs système) qui guident le prochain cycle de réflexion. Dans la phase d'observation, l'agent : - **Collecte des retours :** Il reçoit des données ou une confirmation que son action a réussi (ou non). - **Ajoute les résultats :** Il intègre la nouvelle information dans son contexte existant, mettant ainsi à jour sa mémoire. - **Adapte sa stratégie :** Il utilise ce contexte actualisé pour affiner ses réflexions et ses actions ultérieures. Par exemple, si une API météo renvoie les données *"partiellement nuageux, 15°C, 60 % d'humidité"*, cette observation est ajoutée à la mémoire de l'agent (à la fin du *prompt*). L'agent l'utilise ensuite pour décider si des informations supplémentaires sont nécessaires ou s'il est prêt à fournir une réponse finale. Cette **intégration itérative des retours d'information assure que l'agent reste dynamiquement aligné avec ses objectifs**, apprenant et s'ajustant constamment en fonction des résultats concrets. Ces observations **peuvent prendre de nombreuses formes**, allant de la lecture de texte sur une page web à la surveillance de la position d'un bras robotisé. On peut les considérer comme des « logs » d'outils fournissant un retour textuel sur l'exécution d'une action. | Type d'observation | Exemple | |----------------------------|---------------------------------------------------------------------------------------------| | Retour système | Messages d'erreur, notifications de succès, codes de statut | | Modifications de données | Mises à jour de base de données, modifications du système de fichiers, changements d'état | | Données environnementales | Relevés de capteurs, métriques système, utilisation des ressources | | Analyse des réponses | Réponses d'API, résultats de requêtes, sorties de calcul | | Événements temporels | Dates limites atteintes, tâches programmées terminées | ## Comment les résultats sont-ils ajoutés ? Après avoir effectué une action, le *framework* suit les étapes suivantes dans cet ordre : 1. **Analyser l'action** pour identifier la ou les fonctions à appeler et les arguments à utiliser. 2. **Exécuter l'action.** 3. **Ajouter le résultat** en tant qu'**observation**. --- Nous avons maintenant appris le cycle de raisonnement-action-observation de l'agent. Si certains aspects vous semblent encore un peu flous, ne vous inquiétez pas, nous reviendrons sur ces concepts et les approfondirons dans les prochaines unités. Il est maintenant temps de mettre vos connaissances en pratique en codant votre tout premier agent !
agents-course/units/fr/unit1/observations.mdx/0
{ "file_path": "agents-course/units/fr/unit1/observations.mdx", "repo_id": "agents-course", "token_count": 1244 }
11
# Table des matières Ce plan de chapitre LlamaIndex fait partie de l'unité 2 du cours. Vous pouvez accéder à l'unité 2 sur LlamaIndex sur hf.co/learn 👉 <a href="https://hf.co/learn/agents-course/unit2/llama-index/introduction">ici</a> | Titre | Description | | --- | --- | | [Introduction](introduction.mdx) | Introduction à LlamaIndex | | [LlamaHub](llama-hub.mdx) | LlamaHub : un registre d'intégrations, d'agents et de tools | | [Components](components.mdx) | Components : les blocs de construction des workflows | | [Tools](tools.mdx) | Tools : comment construire des tools dans LlamaIndex | | [Quiz 1](quiz1.mdx) | Quiz 1 | | [Agents](agents.mdx) | Agents : comment construire des agents dans LlamaIndex | | [Workflows](workflows.mdx) | Workflows : une séquence d'étapes, d'événements composés de components qui sont exécutés dans l'ordre | | [Quiz 2](quiz2.mdx) | Quiz 2 | | [Conclusion](conclusion.mdx) | Conclusion |
agents-course/units/fr/unit2/llama-index/README.md/0
{ "file_path": "agents-course/units/fr/unit2/llama-index/README.md", "repo_id": "agents-course", "token_count": 339 }
12
# Petit Quiz (non noté) [[quiz2]] Il est temps de tester votre compréhension des sections sur `CodeAgent`, `ToolCalling Agent` et les *Outils*. Ce quiz est optionnel et non noté. --- ### Q1 : Quelle est la différence clé entre créer un outil avec le décorateur `@tool` et créer une sous-classe de `Tool` dans smolagents ? Quelle déclaration décrit le mieux la distinction entre ces deux approches pour définir des outils ? <Question choices={[ { text: "L'utilisation du décorateur <code>@tool</code> est obligatoire pour les outils basés sur la récupération, tandis que les sous-classes de <code>Tool</code> sont uniquement pour les tâches de génération de texte", explain: "Les deux approches peuvent être utilisées pour tout type d'outil, y compris les outils basés sur la récupération ou la génération de texte.", }, { text: "Le décorateur <code>@tool</code> est recommandé pour les outils simples basés sur des fonctions, tandis que les sous-classes de <code>Tool</code> offrent plus de flexibilité pour des fonctionnalités complexes ou des métadonnées personnalisées", explain: "C'est correct. L'approche par décorateur est plus simple, mais la sous-classe permet un comportement plus personnalisé.", correct: true }, { text: "<code>@tool</code> ne peut être utilisé que dans des systèmes multi-agents, tandis que créer une sous-classe de <code>Tool</code> est pour les scénarios à un seul agent", explain: "Tous les agents (simples ou multiples) peuvent utiliser l'une ou l'autre approche pour définir des outils ; il n'y a pas de telle restriction.", }, { text: "Décorer une fonction avec <code>@tool</code> remplace le besoin d'une <i>docstring</i>, tandis que les sous-classes ne doivent pas inclure de <i>docstring</i>", explain: "Les deux méthodes bénéficient de <i>docstrings</i> claires. Le décorateur ne les remplace pas, et une sous-classe peut toujours avoir des <i>docstrings</i>.", } ]} /> --- ### Q2 : Comment un `CodeAgent` gère-t-il les tâches multi-étapes en utilisant l'approche ReAct (*Reason + Act*) ? Quelle déclaration décrit correctement comment le <code>CodeAgent</code> exécute une série d'étapes pour résoudre une tâche ? <Question choices={[ { text: "Il passe chaque étape à un agent différent dans un système multi-agents, puis combine les résultats", explain: "Bien que les systèmes multi-agents puissent distribuer les tâches, <code>CodeAgent</code> lui-même peut gérer plusieurs étapes de manière autonome en utilisant <i>ReAct</i>.", }, { text: "Il stocke chaque action en JSON pour une analyse facile avant de les exécuter toutes en même temps", explain: "Ce comportement correspond à l'approche basée sur JSON du <code>ToolCallingAgent</code>, pas du <code>CodeAgent</code>.", }, { text: "Il alterne entre l'écriture de raisonnements internes, la génération de code Python, l'exécution du code et l'enregistrement des résultats jusqu'à arriver à une réponse finale", explain: "Correct. Cela décrit le schéma <i>ReAct</i> que <code>CodeAgent</code> utilise, incluant le raisonnement itératif et l'exécution de code.", correct: true }, { text: "Il s'appuie sur un module de vision pour valider la sortie du code avant de continuer à l'étape suivante", explain: "Les capacités de vision sont supportées dans <code>smolagents</code>, mais elles ne sont pas une exigence par défaut pour <code>CodeAgent</code> ou l'approche <i>ReAct</i>.", } ]} /> --- ### Q3 : Lequel des éléments suivants est un avantage principal du partage d'un outil sur le Hub d'Hugging Face ? Sélectionnez la meilleure raison pour laquelle un développeur pourrait télécharger et partager son outil personnalisé. <Question choices={[ { text: "Cela intègre automatiquement l'outil avec un <code>MultiStepAgent</code> pour la génération augmentée par récupération", explain: "Partager un outil ne configure pas automatiquement la récupération ou la logique multi-étapes. Il s'agit simplement de rendre l'outil disponible.", }, { text: "Cela permet aux autres de découvrir, réutiliser et intégrer votre outil dans leurs agent construit avec <code>smolagents</code> sans configuration supplémentaire", explain: "Oui. Partager sur le Hub rend les outils accessibles pour quiconque (y compris vous-même) de les télécharger et les réutiliser rapidement.", correct: true }, { text: "Cela garantit que seuls les <code>CodeAgent</code> peuvent invoquer l'outil tandis que les <code>ToolCallingAgent</code> ne le peuvent pas", explain: "Les <code>CodeAgents</code> et les <code>ToolCallingAgents</code> peuvent tous deux invoquer des outils partagés. Il n'y a pas de restriction par type d'agent.", }, { text: "Cela convertit votre outil en une fonction entièrement capable de vision pour le traitement d'images", explain: "Le partage d'outils ne modifie pas la fonctionnalité de l'outil ni n'ajoute automatiquement des capacités de vision.", } ]} /> --- ### Q4 : `ToolCallingAgent` diffère de `CodeAgent` dans la façon dont il exécute les actions. Quelle déclaration est correcte ? Choisissez l'option qui décrit avec précision comment ToolCallingAgent fonctionne. <Question choices={[ { text: "<code>ToolCallingAgent</code> est uniquement compatible avec un système multi-agents, tandis que <code>CodeAgent</code> peut fonctionner seul", explain: "L'un ou l'autre agent peut être utilisé seul ou dans le cadre d'un système multi-agents.", }, { text: "<code>ToolCallingAgent</code> délègue tout le raisonnement à un agent de récupération séparé, puis retourne une réponse finale", explain: "<code>ToolCallingAgent</code> utilise toujours un LLM principal pour le raisonnement ; il ne se fie pas uniquement aux agents de récupération.", }, { text: "<code>ToolCallingAgent</code> génère des instructions JSON spécifiant les appels d'outils et les arguments, qui sont ensuite analysés et exécutés", explain: "C'est correct. <code>ToolCallingAgent</code> utilise l'approche JSON pour définir les appels d'outils.", correct: true }, { text: "<code>ToolCallingAgent</code> est uniquement destiné aux tâches à une seule étape et s'arrête automatiquement après avoir appelé un outil", explain: "<code>ToolCallingAgent</code> peut effectuer plusieurs étapes si nécessaire, tout comme <code>CodeAgent</code>.", } ]} /> --- ### Q5 : Qu'est-ce qui est inclus dans la boîte à outils par défaut de smolagents, et pourquoi pourriez-vous l'utiliser ? Quelle déclaration capture le mieux l'objectif et le contenu de la boîte à outils par défaut dans smolagents ? <Question choices={[ { text: "Elle fournit un ensemble d'outils couramment utilisés tels que la recherche DuckDuckGo, <code>PythonInterpreterTool</code> et un outil de réponse finale pour un prototypage rapide", explain: "Correct. La boîte à outils par défaut contient ces outils prêts à l'emploi pour une intégration facile lors de la construction d'agents.", correct: true }, { text: "Elle ne supporte que les tâches basées sur la vision comme la classification d'images ou l'OCR par défaut", explain: "Bien que smolagents puisse intégrer des fonctionnalités basées sur la vision, la boîte à outils par défaut n'est pas exclusivement orientée vision.", }, { text: "Elle est destinée uniquement aux systèmes multi-agents et est incompatible avec un seul <code>CodeAgent</code>", explain: "La boîte à outils par défaut peut être utilisée par tout type d'agent, configurations simples ou multi-agents.", }, { text: "Elle ajoute des fonctionnalités avancées basées sur la récupération pour la réponse à des questions à grande échelle à partir d'un magasin de vecteurs", explain: "Bien que vous puissiez construire des outils de récupération, la boîte à outils par défaut ne fournit pas automatiquement des fonctionnalités de RAG avancées.", } ]} /> --- Félicitations pour avoir terminé ce quiz ! 🎉 Si des questions vous ont posé des difficultés, revisitez les sections `CodeAgent`, `ToolCalling Agent` ou *Outils* pour renforcer votre compréhension. Si vous l'avez réussi, vous êtes bien parti pour construire des applications robustes avec `smolagents` !
agents-course/units/fr/unit2/smolagents/quiz2.mdx/0
{ "file_path": "agents-course/units/fr/unit2/smolagents/quiz2.mdx", "repo_id": "agents-course", "token_count": 2951 }
13
# Le projet pratique final Maintenant que vous êtes prêt à plonger plus profondément dans la création de votre agent, voyons comment vous pouvez le soumettre pour l'évaluer. ## Le jeu de données Le jeu de données utilisé pour le classement se compose de 20 questions extraites des questions de niveau 1 de la partie **validation** de GAIA. Les questions choisies ont été filtrées en fonction du nombre d'outils et d'étapes nécessaires pour répondre à une question. Sur la base de l'état actuel du *benchmark* GAIA, nous pensons que vous faire viser 30% sur les questions de niveau 1 est un test équitable. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit4/leaderboard%20GAIA%2024%3A04%3A2025.png" alt="GAIA current status!" /> ## Le processus Maintenant, la grande question dans votre esprit est probablement : « Comment puis-je commencer à soumettre ? » Pour cette unité, nous avons créé une API qui vous permettra d'obtenir les questions et d'envoyer vos réponses pour évaluation. Voici un résumé des routes (voir la [documentation en direct](https://agents-course-unit4-scoring.hf.space/docs) pour les détails interactifs) : * **`GET /questions`** : Récupérer la liste complète des questions d'évaluation filtrées. * **`GET /random-question`** : Récupérer une seule question aléatoire de la liste. * **`GET /files/{task_id}`** : Télécharger un fichier spécifique associé à un ID de tâche donné. * **`POST /submit`** : Soumettre les réponses de l'agent, calculer le score et mettre à jour le classement. La fonction de soumission comparera votre réponse à la vérité terrain via une **CORRESPONDANCE EXACTE**, donc formulez bien vos *prompts* ! L'équipe GAIA a partagé un exemple de formulation pour votre agent [ici](https://huggingface.co/spaces/gaia-benchmark/leaderboard) (pour les besoins de ce cours, assurez-vous de ne pas inclure le texte "FINAL ANSWER" dans votre soumission, faites simplement que votre agent réponde avec la réponse et rien d'autre). 🎨 **Personnalisez le gabarit !** Pour démontrer le processus d'interaction avec l'API, nous avons inclus un [gabarit de base](https://huggingface.co/spaces/agents-course/Final_Assignment_Template) comme point de départ. N'hésitez pas à le changer, et **nous vous encourageons activement à le faire**, y ajouter ou le restructurer complètement ! Modifiez-le de la manière qui convient le mieux à votre approche et à votre créativité. Pour soumettre ces gabarits, calculez 3 éléments nécessaires à l'API : * **Nom d'utilisateur :** Votre nom d'utilisateur Hugging Face (ici obtenu via la connexion Gradio), qui est utilisé pour identifier votre soumission. * **Lien de code (`agent_code`) :** l'URL pointant vers le code de votre *Space* Hugging Face (`.../tree/main`) à des fins de vérification, alors veuillez garder votre *Space* public. * **Réponses (`answers`) :** La liste des réponses (`{"task_id": ..., "submitted_answer": ...}`) générées par votre agent pour la notation. Nous vous encourageons donc à commencer par dupliquer ce [gabarit](https://huggingface.co/spaces/agents-course/Final_Assignment_Template) sur votre propre profil Hugging Face. 🏆 Consultez le classement [ici](https://huggingface.co/spaces/agents-course/Students_leaderboard) *Une note amicale : Ce classement est destiné à s'amuser ! Nous savons qu'il est possible de soumettre des scores sans vérification complète. Si nous constatons qu'un trop grand nombre de scores élevés sont affichés sans lien public pour les étayer, il se peut que nous devions revoir, ajuster ou supprimer certaines entrées afin de préserver l'utilité du classement.* Le classement montrera le lien vers votre *Space* et le code qu'il contient. Puisque ce classement est réservé aux étudiants, veuillez le garder public si vous obtenez un score dont vous êtes fier. <iframe src="https://agents-course-students-leaderboard.hf.space" frameborder="0" width="850" height="450" ></iframe>
agents-course/units/fr/unit4/hands-on.mdx/0
{ "file_path": "agents-course/units/fr/unit4/hands-on.mdx", "repo_id": "agents-course", "token_count": 1411 }
14
--- ### Q1: 에이전트(Agent)란? [[q1-what-is-an-agent]] 다음 중 AI 에이전트를 가장 잘 설명한 것은 무엇인가요? <Question choices={[ { text: "정적인 텍스트만 처리하고, 환경과 동적으로 상호작용하거나 의미 있는 행동을 수행하는 메커니즘이 없는 시스템.", explain: "에이전트는 행동을 취하고 환경과 상호작용할 수 있어야 합니다.", }, { text: "추론하고 계획을 세우며 도구를 활용하여 환경과 상호작용하여 특정 목표를 달성하는 AI 모델.", explain: "이 정의는 에이전트의 핵심 특징을 정확하게 설명합니다.", correct: true }, { text: "사용자의 질문에 답변할 수는 있지만, 외부 시스템과 상호작용하거나 행동을 수행할 수 없는 대화형 AI.", explain: "이러한 챗봇은 행동을 수행하는 기능이 없어 에이전트와 다릅니다.", }, { text: "사용자와 적극적으로 상호작용하거나 작업을 수행할 능력 없이 정적인 정보를 제공하는 온라인 저장소.", explain: "에이전트는 단순히 정보를 제공하는 것이 아니라 환경과 적극적으로 상호작용합니다.", } ]} /> --- ### Q2: What is the Role of Planning in an Agent? 에이전트에서 계획(Planning)이 하는 역할은? 에이전트는 행동을 취하기 전에 왜 계획을 세워야 할까요? <Question choices={[ { text: "주로 과거의 상호작용을 저장하거나 기억하는 역할을 하기 위해서이다.", explain: "계획은 과거 정보를 저장하는 것이 아니라, 미래의 행동을 결정하는 과정입니다.", }, { text: "사용자의 요청을 충족시키기 위해 실행할 행동의 순서를 정하고, 적절한 도구를 선택하기 위해서이다.", explain: "계획을 통해 에이전트는 최적의 단계와 도구를 결정할 수 있습니다.", correct: true }, { text: "명확한 전략이나 목표 없이 무작위로 행동을 수행하기 위해서이다.", explain: "계획을 세우는 것은 에이전트의 행동이 무작위적이지 않고 의도적이게 하기 위해서 입니다.", }, { text: "단순히 텍스트를 변환하거나 번역하는 과정일 뿐, 구체적인 행동 계획이나 전략적 사고와는 관련이 없다.", explain: "계획은 행동을 구조화하는 과정이며, 단순한 텍스트 변환과는 다릅니다", } ]} /> --- ### Q3: 도구(Tools)는 에이전트의 기능을 어떻게 향상시키는가? 도구는 왜 에이전트에게 필수적인 요소일까요? <Question choices={[ { text: "도구는 실질적인 역할을 하지 않으며, 기본적인 텍스트 생성 기능 이상의 행동을 수행하는 데 기여하지 않는다.", explain: "도구는 에이전트가 단순한 텍스트 생성 이상의 행동을 수행할 수 있도록 확장해 줍니다.", }, { text: "도구는 에이전트가 커피를 만들거나 이미지를 생성하는 등, 텍스트 생성 모델이 기본적으로 수행할 수 없는 작업을 실행할 수 있도록 해준다.", explain: "도구를 활용하면 에이전트가 현실 세계와 상호작용하며 작업을 완수할 수 있습니다.", correct: true }, { text: "도구는 메모리 저장을 위한 용도로만 사용되며, 작업을 수행하거나 상호작용 성능을 향상하는 기능은 없다.", explain: "도구는 데이터를 저장하는 것이 아니라, 행동을 수행하는 데 주로 사용됩니다.", }, { text: "도구는 에이전트가 텍스트 생성만 가능하도록 제한하여, 더 넓은 범위의 상호작용을 수행하지 못하게 만든다.", explain: "반대로, 도구는 에이전트가 텍스트 기반 응답을 넘어 더 다양한 행동을 수행할 수 있도록 합니다.", } ]} /> --- ### Q4: 행동(Actions)과 도구(Tools)의 차이점은? 행동과 도구의 핵심적인 차이는 무엇인가요? <Question choices={[ { text: "행동은 에이전트가 취하는 단계이며, 도구는 해당 행동을 수행하기 위해 사용할 수 있는 외부 리소스이다.", explain: "행동은 더 높은 수준의 목표이며, 도구는 이를 실행하는 데 필요한 구체적인 기능입니다.", correct: true }, { text: "행동과 도구는 완전히 동일한 개념이며, 상호 교환적으로 사용할 수 있다.", explain: "행동은 목표나 작업을 의미하며, 도구는 이를 달성하기 위해 사용하는 수단입니다.", }, { text: "도구는 광범위한 기능을 수행하는 유틸리티이며, 행동은 물리적 상호작용에만 국한된다.", explain: "행동은 디지털 및 물리적 작업을 모두 포함할 수 있습니다.", }, { text: "행동은 LLM을 통해 결정 및 실행해야 하지만, 도구는 이러한 의존성 없이 독립적으로 작동한다.", explain: "LLM은 행동을 결정하는 데 도움을 주지만, 행동 자체가 반드시 LLM에 의존하는 것은 아닙니다.", } ]} /> --- ### Q5: LLM은 에이전트에서 어떤 역할을 하는가? LLM는 에이전트의 기능에 어떻게 기여할까요? <Question choices={[ { text: "LLM은 단순히 정보를 저장하는 수동적인 저장소 역할을 하며, 입력을 능동적으로 처리하거나 동적인 응답을 생성할 수 없다.", explain: "LLM은 정보를 단순 저장하는 것이 아니라, 입력을 처리하고 응답을 생성하는 능동적인 역할을 합니다.", }, { text: "LLM은 에이전트의 '두뇌' 역할을 하며, 텍스트 입력을 처리하고 명령을 이해하여 행동을 계획하는 기능을 한다.", explain: "LLM은 에이전트가 명령을 해석하고 계획을 수립하는 데 중요한 역할을 합니다.", correct: true }, { text: "LLM은 이미지 처리에만 사용된다고 잘못 알려져 있으며, 실제로는 텍스트를 생성하고 처리하는 것이 주된 역할이다.", explain: "LLM은 주로 텍스트를 다루지만, 경우에 따라 멀티모달 입력과도 상호작용할 수 있습니다.", }, { text: "LLM은 AI 에이전트의 운영과 전혀 관련이 없으며, 실용적인 적용에서 불필요한 요소이다.", explain: "LLM은 현대 AI 에이전트의 핵심 구성 요소입니다.", } ]} /> --- ### Q6: 다음 중 AI 에이전트의 실제 사례로 가장 적절한 것은? 다음 예시 중 실제 AI 에이전트의 작동 방식과 가장 유사한 것은 무엇인가요? <Question choices={[ { text: "웹사이트에서 고정된 정보를 제공하며, 동적 응답 기능이 없는 정적인 FAQ 페이지.", explain: "정적인 FAQ 페이지는 사용자와 동적으로 상호작용하거나 행동을 수행하지 않습니다.", }, { text: "음성 명령을 이해하고, 이를 기반으로 알람 설정이나 메시지 전송 같은 작업을 수행하는 Siri 또는 Alexa 같은 가상 비서.", explain: "이 예시는 추론, 계획, 환경과의 상호작용을 포함하고 있습니다.", correct: true }, { text: "사칙연산을 수행하지만, 추론이나 계획 기능 없이 고정된 규칙에 따라 작동하는 단순 계산기", explain: "정해진 규칙을 따르는 계산기는, 추론이나 계획 없이 작동하기 때문에 에이전트가 아닙니다.", }, { text: "미리 정해진 대사에 따라 반응하는 비디오 게임 NPC로, 추론, 계획, 도구 활용 기능이 없는 경우.", explain: "NPC가 추론, 계획, 도구 활용 기능이 없다면 AI 에이전트라고 보기 어렵습니다.", } ]} /> --- 퀴즈 완료를 축하합니다! 🥳 If you need to review any elements, take the time to revisit the chapter to reinforce your knowledge before diving deeper into the "Agent's brain": LLMs. 본격적으로 "에이전트의 두뇌"인 LLM에 대해 학습하기 이전에 배운 내용을 다시 복습하고 싶다면, 해당 챕터를 다시 확인해 보세요. 🚀
agents-course/units/ko/unit1/quiz1.mdx/0
{ "file_path": "agents-course/units/ko/unit1/quiz1.mdx", "repo_id": "agents-course", "token_count": 6252 }
15
# Подготовка к работе: Ваши первые шаги ⛵ <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit0/time-to-onboard.jpg" alt="Время подняться на борт" width="100%"/> Теперь, когда у вас есть все подробности, давайте начнем! Мы сделаем четыре вещи: 1. **Создадим аккаунт Hugging Face**, если это еще не сделано. 2. **Зарегистрируемся в Discord и представимся** (не стесняйтесь 🤗) 3. ** Последуеем за курсом обучения агентов Hugging Face** на Hub 4. **Расскажим** о курсе ### Шаг 1: Создание учетной записи Hugging Face (Если вы еще не сделали этого) создайте аккаунт Пространства (Spaces) Hugging Face <a href='https://huggingface.co/join' target='_blank'>здесь</a>. ### Шаг 2: Присоединяйтесь к нашему сообществу в Discord 👉🏻 Присоединяйтесь к нашему серверу discord <a href="https://discord.gg/UrrTSsSyjb" target="_blank">здесь.</a> Когда вы присоединитесь, не забудьте представиться, используя хэштег `#introduce-yourself`. У нас есть несколько каналов, связанных с агентами ИИ: - `agents-course-announcements`: где публикуется **последняя информация о курсе**. - `🎓-agents-course-general`: для **обсуждения общих вопросов и свободного общения**. - `agents-course-questions`: чтобы **задавать вопросы и помочь своим однокурсникам**. - `agents-course-showcase`: чтобы **продемонстрировать своих лучших агентов**. Кроме того, вам могут пригодится: - `smolagents`: для **обсуждения и поддержки библиотеки**. Если вы впервые используете Discord, мы написали Discord 101, чтобы вы узнали о лучших практиках. Проверьте [следующий раздел](discord101). ### Шаг 3: Следуйте за организацией курса для агентов Hugging Face Оставайтесь в курсе последних материалов курса, обновлений и объявлений, **подписавшись на организацию курса Hugging Face Agents**. 👉 Перейдите <a href="https://huggingface.co/agents-course" target="_blank">сюда</a> и нажмите **follow**. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/communication/hf_course_follow.gif" alt="Follow" width="100%"/> ### Шаг 4: Распространите информацию о курсе Помогите нам сделать этот курс более заметным! Вы можете помочь нам двумя способами: 1. Выразите свою поддержку ⭐. <a href="https://github.com/huggingface/agents-course" target="_blank">репозиторию курса</a>. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/communication/please_star.gif" alt="Звезда для репозитория"/> 2. Поделитесь своим опытом обучения: Пусть другие **знают, что вы проходите этот курс**! Мы подготовили иллюстрацию, которую вы можете использовать в своих сообщениях в социальных сетях <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/communication/share.png"> Вы можете скачать иллюстрацию, нажав 👉 [здесь](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/communication/share.png?download=true) Поздравляем! 🎉 **Вы завершили введеную часть**! Теперь вы готовы приступить к изучению ИИ-агентов. Получайте удовольствие! Продолжайте учиться, оставайтесь потрясающими 🤗.
agents-course/units/ru-RU/unit0/onboarding.mdx/0
{ "file_path": "agents-course/units/ru-RU/unit0/onboarding.mdx", "repo_id": "agents-course", "token_count": 2438 }
16
# Что такое Агент? <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/whiteboard-no-check.jpg" alt="Unit 1 planning"/> К концу этого раздела вы будете чувствовать себя комфортно с концепцией агентов и их различными применениями в ИИ. Чтобы объяснить, что такое агент, давайте начнем с аналогии. ## Общая картина: Агент Альфред Познакомьтесь с Альфредом. Альфред - **агент**. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/this-is-alfred.jpg" alt="This is Alfred"/> Представьте, что Альфред **получает команду**, например: «Альфред, я бы хотел кофе, пожалуйста». <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/coffee-please.jpg" alt="I would like a coffee"/> Поскольку Альфред **понимает естественный язык**, он быстро понимает нашу просьбу. Перед выполнением заказа Альфред занимается **рассуждениями и планированием**, определяя, какие действия и инструменты ему понадобятся: 1. Пойти на кухню 2. Воспользоваться кофеваркой 3. Заварите кофе 4. Принесите кофе обратно <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/reason-and-plan.jpg" alt="Reason and plan"/> Когда у него есть план, он **должен действовать**. Чтобы выполнить свой план, **он может использовать инструменты из списка инструментов, о которых он знает**. В данном случае, чтобы приготовить кофе, он использует кофеварку. Он активирует кофеварку, чтобы сварить кофе. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/make-coffee.jpg" alt="Make coffee"/> Наконец Альфред приносит нам свежесваренный кофе. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/bring-coffee.jpg" alt="Bring coffee"/> Именно это и есть агент: **ИИ модель, способная рассуждать, планировать и взаимодействовать со своим окружением**. Мы называем его агентом, потому что он обладает _агентностью_, то есть способностью взаимодействовать с окружающей средой. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/process.jpg" alt="Agent process"/> ## Давайте будем более формальны Теперь, когда вы получили общую картину, вот более точное определение: > Агент - это система, использующая модель искусственного интеллекта для взаимодействия с окружающей средой с целью достижения определенной пользователем цели. Он сочетает в себе рассуждения, планирование и выполнение действий (часто с помощью внешних инструментов) для выполнения задач. Считайте, что агент состоит из двух основных частей: 1. **Мозг (модель ИИ)**. Именно здесь происходит все мышление. Модель ИИ **занимается рассуждениями и планированием**. Она решает, **какие действия предпринять в зависимости от ситуации**. 2. **Тело (возможности и инструменты)**. Эта часть представляет собой **все, что агент способен делать**. Набор **возможных действий** зависит от того, чем **наделен агент**. Например, поскольку у человека нет крыльев, он не может выполнять **действие «летать», но может выполнять такие **действия**, как «ходить», «бегать», «прыгать», «хватать» и так далее. ## Какие модели ИИ мы используем для агентов? Наиболее распространенной моделью ИИ, используемой в агентах, является LLM (большая языковая модель), которая принимает на вход **Текст** и выводит **Текст**. Известными примерами являются **GPT4** от **OpenAI**, **LLama** от **Meta**, **Gemini** от **Google** и т. д. Эти модели были обучены на огромном количестве текстов и способны к обобщению. Подробнее о LLM мы узнаем в [следующем разделе](what-are-llms). <Tip> Также можно использовать модели, принимающие другие входные данные, в качестве основной модели агента. Например, Vision Language Model (VLM), которая похожа на LLM, но также понимает изображения в качестве входных данных. Пока что мы сосредоточимся на LLM и обсудим другие варианты позже. </Tip> ## Как ИИ воздействует на окружающую среду? LLM - замечательные модели, но **они могут генерировать только текст**. Однако если вы попросите известное чат-приложение, например HuggingChat или ChatGPT, сгенерировать изображение, они смогут! Как такое возможно? Ответ заключается в том, что разработчики HuggingChat, ChatGPT и подобных приложений реализовали дополнительный функционал (так называемые **инструменты (tools)**), которые LLM может использовать для создания изображений. <figure> <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/eiffel_brocolis.jpg" alt="Eiffel Brocolis"/> <figcaption>The model used an Image Generation Tool to generate this image. </figcaption> </figure> Подробнее об инструментах мы поговорим в разделе [Инструменты](tools). ## Какой тип задач может выполнять Агент? Агент может выполнять любые задачи, которые мы реализуем с помощью **Инструментов** для выполнения **Действий**. Например, если я напишу агента, который будет действовать как мой личный помощник (как Siri) на моем компьютере, и попрошу его «отправить электронное письмо моему менеджеру с просьбой отложить сегодняшнюю встречу», я могу дать ему код для отправки электронных писем. Это будет новый инструмент, который агент сможет использовать всякий раз, когда ему понадобится отправить письмо. Мы можем написать его на языке Python: ```python def send_message_to(recipient, message): """Используется для отправки электронного сообщения получателю""" ... ``` LLM, как мы увидим, будет генерировать код для запуска инструмента, когда это необходимо, и таким образом выполнять поставленную задачу. ```python send_message_to("Менеджер", "Мы можем отложить сегодняшнюю встречу?") ``` Дизайн **Инструментов очень важен и оказывает большое влияние на качество работы вашего Агента**. Некоторые задачи требуют создания очень специфических инструментов, в то время как другие могут быть решены с помощью инструментов общего назначения, таких как "web_search". > Обратите внимание, что **Действия - это не то же самое, что Инструменты**. Действие, например, может включать в себя использование нескольких инструментов для выполнения. Предоставление агенту возможности взаимодействовать с окружающей средой **позволяет использовать его в реальной жизни компаниями и частными лицами**. ### Пример 1: Виртуальные персональные ассистенты Виртуальные помощники, такие как Siri, Alexa или Google Assistant, работают как агенты, когда взаимодействуют от имени пользователей в их цифровом окружении. Они принимают запросы пользователей, анализируют контекст, извлекают информацию из баз данных, дают ответы или инициируют действия (например, устанавливают напоминания, отправляют сообщения или управляют смарт-устройствами). Пример 2: Чат-боты для обслуживания клиентов Многие компании используют чат-боты в качестве агентов, которые взаимодействуют с клиентами на естественном языке. Эти агенты могут отвечать на вопросы, направлять пользователей по шагам устранения неисправностей, открывать проблемы во внутренних базах данных или даже завершать транзакции. Их заранее определенные цели могут включать повышение удовлетворенности пользователей, сокращение времени ожидания или увеличение коэффициента конверсии продаж. Взаимодействуя непосредственно с клиентами, обучаясь в ходе диалога и адаптируя свои ответы с течением времени, они демонстрируют основные принципы работы агента в действии. ### Пример 3: ИИ неигрового персонажа в видеоигре Вкратце, агент - это система, которая использует модель ИИ (обычно LLM) в качестве основного механизма рассуждений, чтобы: Вместо того чтобы следовать жесткому дереву поведения, они могут **реагировать контекстно, адаптироваться к взаимодействию с игроком** и генерировать более тонкие диалоги. Такая гибкость помогает создавать более реалистичные и увлекательные персонажи, которые развиваются вместе с действиями игрока. --- Вкратце, агент - это система, которая использует ИИ модель (обычно LLM) в качестве основного механизма рассуждений, чтобы: - **Понимать естественный язык:** Интерпретировать и осмысленно отвечать на человеческие инструкции. - **Рассуждать и планировать:** Анализировать информацию, принимать решения и разрабатывать стратегии для решения проблем. - **Взаимодействовать с окружающей средой:** Собирать информацию, предпринимать действия и наблюдать за их результатами. Теперь, когда вы хорошо знаете, что такое агенты, давайте закрепим ваше понимание с помощью короткого теста без оценки. После этого мы погрузимся в «мозг агента»: [LLMs](what-are-llms).
agents-course/units/ru-RU/unit1/what-are-agents.mdx/0
{ "file_path": "agents-course/units/ru-RU/unit1/what-are-agents.mdx", "repo_id": "agents-course", "token_count": 8089 }
17
# Chương 1: Kiểm tra nhanh <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/whiteboard-unit1sub4DONE.jpg" alt="Kế hoạch chương 1"/> Chúc mừng bạn đã hoàn thành chương đầu tiên! Hãy cùng kiểm tra hiểu biết của bạn về các khái niệm chính đã học nhé. Khi vượt qua bài kiểm tra này, hãy chuyển sang phần tiếp theo để nhận chứng chỉ của bạn. Chúc may mắn! ## Bài kiểm tra Đây là bài kiểm tra tương tác được host trên Hugging Face Hub trong một Space. Bạn sẽ trải qua các câu hỏi trắc nghiệm để kiểm tra hiểu biết về các khái niệm chính trong chương này. Sau khi hoàn thành, bạn có thể xem điểm số và đáp án đúng. Lưu ý quan trọng: **đừng quên nhấn Submit sau khi hoàn thành, nếu không điểm thi của bạn sẽ không được lưu!** <iframe src="https://agents-course-unit-1-quiz.hf.space" frameborder="0" width="850" height="450" ></iframe> Bạn cũng có thể truy cập bài kiểm tra tại 👉 [đây](https://huggingface.co/spaces/agents-course/unit_1_quiz) ## Chứng chỉ Giờ bạn đã vượt qua bài kiểm tra thành công, **hãy nhận chứng chỉ 🎓 của bạn** Khi hoàn thành bài kiểm tra, bạn sẽ được cấp chứng chỉ hoàn thành chương này. Bạn có thể tải về và chia sẻ chứng chỉ này để thể hiện tiến độ học tập. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/whiteboard-unit1sub5DONE.jpg" alt="Kế hoạch chương 1"/> Sau khi nhận chứng chỉ, bạn có thể thêm vào LinkedIn 🧑‍💼 hoặc chia sẻ lên X, Bluesky... **Chúng mình sẽ rất tự hào và muốn chúc mừng bạn nếu bạn tag @huggingface**! 🤗
agents-course/units/vi/unit1/final-quiz.mdx/0
{ "file_path": "agents-course/units/vi/unit1/final-quiz.mdx", "repo_id": "agents-course", "token_count": 1132 }
18
# 让我们为函数调用微调模型 (Let's Fine-Tune your model for function-calling) 我们现在准备好为函数调用微调我们的第一个模型了 🔥。 ## 我们如何训练模型进行函数调用? > 答案:我们需要**数据** 模型训练可以分为3个步骤: 1. **模型在大量数据上进行预训练 (pretrained)**。这一步的输出是一个**预训练模型 (pre-trained model)**。例如 [google/gemma-2-2b](https://huggingface.co/google/gemma-2-2b)。这是一个基础模型,只知道**如何预测下一个词元(token),而没有良好的指令跟随能力**。 2. 然后,为了在对话环境中发挥作用,模型需要进行**微调 (fine-tuned)**以遵循指令。在这一步中,可以由模型创建者、开源社区、你或任何人进行训练。例如 [google/gemma-2-2b-it](https://huggingface.co/google/gemma-2-2b-it) 是由 Gemma 项目背后的谷歌团队进行的指令微调模型。 3. 然后可以将模型**对齐 (aligned)**到创建者的偏好。例如,一个必须永远不能对客户无礼的客户服务聊天模型。 通常,像 Gemini 或 Mistral 这样的完整产品**会经历所有这3个步骤**,而你在 Hugging Face 上找到的模型可能已经经过了这些训练步骤中的一个或多个。 在本教程中,我们将基于 [google/gemma-2-2b-it](https://huggingface.co/google/gemma-2-2b-it) 构建一个函数调用模型。基础模型是 [google/gemma-2-2b](https://huggingface.co/google/gemma-2-2b),谷歌团队在指令跟随方面对基础模型进行了微调:产生了 **"google/gemma-2-2b-it"**。 在这种情况下,我们将使用 **"google/gemma-2-2b-it"** 作为基础,**而不是基础模型,因为它之前经历的微调对我们的用例很重要**。 由于我们想要通过消息对话与我们的模型进行交互,从基础模型开始**需要更多的训练才能学习指令跟随、聊天和函数调用**。 通过从指令微调模型开始,**我们最小化了模型需要学习的信息量**。 ## LoRA(大语言模型的低秩适应) LoRA(大语言模型的低秩适应,Low-Rank Adaptation of Large Language Models)是一种流行的轻量级训练技术,它显著**减少了可训练参数的数量**。 它的工作原理是**将较少数量的新权重作为适配器插入到模型中进行训练**。这使得使用 LoRA 进行训练更快、内存效率更高,并产生更小的模型权重(几百 MB),更易于存储和共享。 <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/blog_multi-lora-serving_LoRA.gif" alt="LoRA inference" width="50%"/> LoRA 通过向 Transformer 层添加秩分解矩阵对来工作,通常关注线性层。在训练期间,我们将"冻结"模型的其余部分,只更新那些新添加的适配器的权重。 通过这样做,我们需要训练的参数数量大大减少,因为我们只需要更新适配器的权重。 在推理过程中,输入通过适配器传递,基础模型或这些适配器权重可以与基础模型合并,不会产生额外的延迟开销。 LoRA 特别适用于将**大型**语言模型适应特定任务或领域,同时保持资源需求可控。这有助于减少训练模型所需的内存。 如果你想了解更多关于 LoRA 如何工作的信息,你应该查看这个[教程](https://huggingface.co/learn/nlp-course/chapter11/4?fw=pt)。 ## 为函数调用微调模型 你可以在这里访问教程笔记本 👉 [点击这里](https://huggingface.co/agents-course/notebooks/blob/main/bonus-unit1/bonus-unit1.ipynb)。 然后,点击 [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/#fileId=https://huggingface.co/agents-course/notebooks/blob/main/bonus-unit1/bonus-unit1.ipynb) 以便在 Colab Notebook 中运行它。
agents-course/units/zh-CN/bonus-unit1/fine-tuning.mdx/0
{ "file_path": "agents-course/units/zh-CN/bonus-unit1/fine-tuning.mdx", "repo_id": "agents-course", "token_count": 2515 }
19
# 简单智能体库 (Dummy Agent Library) <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/whiteboard-unit1sub3DONE.jpg" alt="Unit 1 planning"/> 本课程是框架无关的,因为我们想要**专注于 AI 智能体(AI Agent)的概念,避免陷入特定框架的细节中**。 同时,我们希望学生能够在自己的项目中使用他们在本课程中学到的概念,使用任何他们喜欢的框架。 因此,在第一单元中,我们将使用一个简单智能体库和一个简单的无服务器 API (serverless API) 来访问我们的 LLM 引擎。 你可能不会在生产环境中使用这些,但它们将作为**理解智能体如何工作的良好起点**。 在本节之后,你将准备好**使用 `smolagents` 创建一个简单的智能体**。 在接下来的单元中,我们还将使用其他 AI 智能体库,如 `LangGraph` 和 `LlamaIndex`。 为了保持简单,我们将使用一个简单的 Python 函数作为工具和智能体。 我们将使用内置的 Python 包,如 `datetime` 和 `os`,这样你可以在任何环境中尝试它。 你可以[在这个 notebook 中](https://huggingface.co/agents-course/notebooks/blob/main/unit1/dummy_agent_library.ipynb)跟随过程并**自己运行代码**。 ## 无服务器 API (Serverless API) 在 Hugging Face 生态系统中,有一个称为无服务器 API 的便捷功能,它允许你轻松地在许多模型上运行推理。不需要安装或部署。 ```python import os from huggingface_hub import InferenceClient ## 你需要一个来自 https://hf.co/settings/tokens 的令牌,确保你选择'read'作为令牌类型。如果你在 Google Colab 上运行,你可以在"settings"标签下的"secrets"中设置它。确保将其命名为"HF_TOKEN" os.environ["HF_TOKEN"]="hf_xxxxxxxxxxxxxx" client = InferenceClient(provider="hf-inference", model="meta-llama/Llama-3.3-70B-Instruct") # 如果下一个单元格的输出不正确,免费模型可能过载。你也可以使用这个包含 Llama-3.2-3B-Instruct 的公共端点 # client = InferenceClient("https://jc26mwg228mkj8dw.us-east-1.aws.endpoints.huggingface.cloud") ``` ```python output = client.text_generation( "The capital of France is", max_new_tokens=100, ) print(output) ``` 输出: ``` Paris. The capital of France is Paris. The capital of France is Paris. The capital of France is Paris. The capital of France is Paris. The capital of France is Paris. The capital of France is Paris. The capital of France is Paris. The capital of France is Paris. The capital of France is Paris. The capital of France is Paris. The capital of France is Paris. The capital of France is Paris. The capital of France is Paris. The capital of France is Paris. ``` 如 LLM 部分所见,如果我们只做解码,**模型只会在预测到 EOS 令牌时停止**,而这里没有发生,因为这是一个会话(聊天)模型,**我们没有应用它期望的聊天模板**。 如果我们现在添加与我们使用的<a href="https://huggingface.co/meta-llama/Llama-3.2-3B-Instruct"> Llama-3.2-3B-Instruct 模型</a>相关的特殊令牌,行为会改变,现在会产生预期的 EOS。 ```python prompt="""<|begin_of_text|><|start_header_id|>user<|end_header_id|> The capital of France is<|eot_id|><|start_header_id|>assistant<|end_header_id|>""" output = client.text_generation( prompt, max_new_tokens=100, ) print(output) ``` 输出: ``` The capital of France is Paris. ``` 使用"chat"方法是应用聊天模板的更方便和可靠的方式: ```python output = client.chat.completions.create( messages=[ {"role": "user", "content": "The capital of France is"}, ], stream=False, max_tokens=1024, ) print(output.choices[0].message.content) ``` 输出: ``` Paris. ``` chat 方法是推荐使用的方法,以确保模型之间的平滑过渡,但由于这个 notebook 只是教育性质的,我们将继续使用 "text_generation" 方法来理解细节。 ## 简单智能体 (Dummy Agent) 在前面的部分中,我们看到智能体库的核心是在系统提示中附加信息。 这个系统提示比我们之前看到的要复杂一些,但它已经包含: 1. **工具信息** 2. **循环指令** (思考 → 行动 → 观察) ``` 请尽可能准确地回答以下问题。你可以使用以下工具: get_weather: 获取指定地点的当前天气 使用工具的方式是通过指定一个 JSON blob。具体来说,这个 JSON 应该包含 `action` 键(工具名称)和 `action_input` 键(工具输入参数)。 "action" 字段唯一允许的值是: get_weather: 获取指定地点的当前天气,参数:{"location": {"type": "string"}} 使用示例: {{ "action": "get_weather", "action_input": {"location": "New York"} }} 必须始终使用以下格式: Question: 需要回答的输入问题 Thought: 你应该始终思考要采取的一个行动(每次只能执行一个行动) Action: $JSON_BLOB (inside markdown cell) Observation: 行动执行结果(这是唯一且完整的事实依据) ...(这个 Thought/Action/Observation 循环可根据需要重复多次,$JSON_BLOB 必须使用 markdown 格式且每次仅执行一个行动) 最后必须以下列格式结束: Thought: 我现在知道最终答案 Final Answer: 对原始问题的最终回答 现在开始!请始终使用精确字符 `Final Answer:` 来给出最终答案 ``` 由于我们正在运行“text_generation”方法,因此我们需要手动应用提示: ```python prompt=f"""<|begin_of_text|><|start_header_id|>system<|end_header_id|> {SYSTEM_PROMPT} <|eot_id|><|start_header_id|>user<|end_header_id|> What's the weather in London ? <|eot_id|><|start_header_id|>assistant<|end_header_id|> """ ``` 我们也可以这样做,这就是在 `chat` 方法内部发生的情况: ```python messages=[ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": "What's the weather in London ?"}, ] from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.2-3B-Instruct") tokenizer.apply_chat_template(messages, tokenize=False,add_generation_prompt=True) ``` 现在的提示是: ``` <|begin_of_text|><|start_header_id|>system<|end_header_id|> 请尽可能准确地回答以下问题。你可以使用以下工具: get_weather: 获取指定地点的当前天气 使用工具的方式是通过指定一个 JSON blob。具体来说,这个 JSON 应该包含 `action` 键(工具名称)和 `action_input` 键(工具输入参数)。 "action" 字段唯一允许的值是: get_weather: 获取指定地点的当前天气,参数:{"location": {"type": "string"}} 使用示例: {{ "action": "get_weather", "action_input": {"location": "New York"} }} 必须始终使用以下格式: Question: 需要回答的输入问题 Thought: 你应该始终思考要采取的一个行动(每次只能执行一个行动) Action: $JSON_BLOB (markdown 单元格内部) Observation: 行动执行结果(这是唯一且完整的事实依据) ...(这个 Thought/Action/Observation 循环可根据需要重复多次,$JSON_BLOB 必须使用 markdown 格式且每次仅执行一个行动) 最后必须以下列格式结束: Thought: 我现在知道最终答案 Final Answer: 对原始问题的最终回答 现在开始!请始终使用精确字符 `Final Answer:` 来给出最终答案 <|eot_id|><|start_header_id|>user<|end_header_id|> What's the weather in London ? <|eot_id|><|start_header_id|>assistant<|end_header_id|> ``` Let's decode! ```python output = client.text_generation( prompt, max_new_tokens=200, ) print(output) ``` 输出: ```` Action: ``` { "action": "get_weather", "action_input": {"location": "London"} } ``` Thought:我要查看一下伦敦的天气。 Observation:伦敦目前的天气多云,最高气温 12°C,最低气温 8°C。 ```` 你看到问题了吗? >答案是模型产生的幻觉。我们需要停下来真正执行这个函数! 现在让我们停在“观察”上,这样我们就不会产生实际函数响应的幻觉。 ```python output = client.text_generation( prompt, max_new_tokens=200, stop=["Observation:"] # Let's stop before any actual function is called ) print(output) ``` 输出: ```` Action: ``` { "action": "get_weather", "action_input": {"location": "London"} } ``` Thought: 我会查看伦敦的天气。 Observation: ```` 好多了! 现在让我们创建一个虚拟的获取天气函数。在实际情况下,您可能会调用 API。 ```python # Dummy function def get_weather(location): return f"the weather in {location} is sunny with low temperatures. \n" get_weather('London') ``` 输出: ``` “伦敦天气晴朗,气温较低。\n” ``` 我们将基本提示、函数执行前的完成以及函数的结果连接起来作为观察并恢复生成。 ```python new_prompt = prompt + output + get_weather('London') final_output = client.text_generation( new_prompt, max_new_tokens=200, ) print(final_output) ``` 这是新的提示: ```` <|begin_of_text|><|start_header_id|>system<|end_header_id|> 尽可能回答以下问题。您可以使用以下工具: get_weather:获取给定位置的当前天气 使用工具的方式是指定 json blob。 具体来说,此 json 应具有 `action` 键(包含要使用的工具的名称)和 `action_input` 键(包含工具的输入)。 “action”字段中应包含的唯一值是: get_weather:获取给定位置的当前天气,参数:{"location": {"type": "string"}} 示例用法: {{ "action": "get_weather", "action_input": {"location": "New York"} }} 始终使用以下格式: Question: 您必须回答的输入问题 Thought: 您应该始终考虑采取一项行动。每次只能采取一项行动,格式如下: Action: $JSON_BLOB (inside markdown cell) Observation:行动的结果。这种观察是独一无二的、完整的,也是真相的来源。 ...(这种 Thought/Action/Observation 可以重复 N 次,您应该在需要时采取几个步骤。$JSON_BLOB 必须格式化为 markdown,并且一次只能使用一个操作。) 您必须始终以以下格式结束输出: 想法:我现在知道最终答案 最终答案:对原始输入问题的最终答案 现在开始!提醒您,当您提供明确答案时,始终使用精确字符“最终答案:”。 <|eot_id|><|start_header_id|>user<|end_header_id|> What's the weather in London ? <|eot_id|><|start_header_id|>assistant<|end_header_id|> Action: ``` { "action": "get_weather", "action_input": {"location": {"type": "string", "value": "London"} } ``` Thought: 我要查看一下伦敦的天气。 Observation: 伦敦天气晴朗,气温较低。 ```` 输出: ``` 最终答案:伦敦天气晴朗,气温较低。 ``` --- 我们学习了如何使用 Python 代码从头开始创建智能体,并且我们**看到了这个过程是多么繁琐**。幸运的是,许多智能体库通过为您处理大部分繁重的工作来简化这项工作。 现在,我们已准备好使用 `smolagents` 库**创建我们的第一个真正的智能体**。
agents-course/units/zh-CN/unit1/dummy-agent-library.mdx/0
{ "file_path": "agents-course/units/zh-CN/unit1/dummy-agent-library.mdx", "repo_id": "agents-course", "token_count": 6330 }
20
# 构建你的第一个 LangGraph 现在我们已经理解了基本构建模块,让我们通过构建第一个功能图来实践。我们将实现 Alfred 的邮件处理系统,他需要: 1. 阅读 incoming emails 2. 将其分类为 spam 或 legitimate 3. 为 legitimate 邮件起草初步响应 4. 当邮件合法时向 Mr. Wayne 发送信息(仅打印) 这个示例演示了如何使用 LangGraph 构建涉及基于 LLM 决策的工作流程结构。虽然这不能算是真正的 Agent(因为没有涉及工具),但本节更侧重于学习 LangGraph 框架而非 Agents。 <Tip> 你可以在 <a href="https://huggingface.co/agents-course/notebooks/resolve/main/unit2/langgraph/mail_sorting.ipynb" target="_blank">这个 notebook</a> 中查看完整代码,并通过 Google Colab 运行。 </Tip> ## 工作流程 这是我们将要构建的工作流程: <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/LangGraph/first_graph.png" alt="First LangGraph"/> ## 环境设置 首先安装必要的包: ```python %pip install langgraph langchain_openai ``` 接下来,让我们导入必要的模块: ```python import os from typing import TypedDict, List, Dict, Any, Optional from langgraph.graph import StateGraph, END from langchain_openai import ChatOpenAI from langchain_core.messages import HumanMessage, AIMessage ``` ## 步骤 1:定义我们的状态 让我们定义 Alfred 在电子邮件处理工作流程中需要跟踪哪些信息: ```python class EmailState(TypedDict): # 正在处理的电子邮件 email: Dict[str, Any] # 包含主题、发件人、正文等。 # 分析与决策 is_spam: Optional[bool] # 响应生成 draft_response: Optional[str] # 处理元数据 messages: List[Dict[str, Any]] # 跟踪与 LLM 的对话以进行分析 ``` > 💡 **提示:**让您的状态足够全面,以跟踪所有重要信息,但避免用不必要的细节使其变得臃肿。 ## 第 2 步:定义我们的节点 现在,让我们创建将形成我们节点的处理函数: ```python # Initialize our LLM model = ChatOpenAI(temperature=0) def read_email(state: EmailState): """Alfred reads and logs the incoming email""" email = state["email"] # 在这里我们可能会做一些初步的预处理 print(f"Alfred is processing an email from {email['sender']} with subject: {email['subject']}") # 这里不需要更改状态 return {} def classify_email(state: EmailState): """Alfred uses an LLM to determine if the email is spam or legitimate""" email = state["email"] # 为 LLM 准备提示 prompt = f""" As Alfred the butler, analyze this email and determine if it is spam or legitimate. Email: From: {email['sender']} Subject: {email['subject']} Body: {email['body']} First, determine if this email is spam. If it is spam, explain why. If it is legitimate, categorize it (inquiry, complaint, thank you, etc.). """ # Call the LLM messages = [HumanMessage(content=prompt)] response = model.invoke(messages) # 解析响应的简单逻辑(在实际应用中,您需要更强大的解析) response_text = response.content.lower() is_spam = "spam" in response_text and "not spam" not in response_text # 如果是垃圾邮件,请提取原因 spam_reason = None if is_spam and "reason:" in response_text: spam_reason = response_text.split("reason:")[1].strip() # 确定类别是否合法 email_category = None if not is_spam: categories = ["inquiry", "complaint", "thank you", "request", "information"] for category in categories: if category in response_text: email_category = category break # 更新消息以进行追踪 new_messages = state.get("messages", []) + [ {"role": "user", "content": prompt}, {"role": "assistant", "content": response.content} ] # 返回状态更新 return { "is_spam": is_spam, "spam_reason": spam_reason, "email_category": email_category, "messages": new_messages } def handle_spam(state: EmailState): """Alfred discards spam email with a note""" print(f"Alfred has marked the email as spam. Reason: {state['spam_reason']}") print("The email has been moved to the spam folder.") # 我们已处理完这封电子邮件 return {} def draft_response(state: EmailState): """Alfred drafts a preliminary response for legitimate emails""" email = state["email"] category = state["email_category"] or "general" # 为 LLM 准备提示词 prompt = f""" As Alfred the butler, draft a polite preliminary response to this email. Email: From: {email['sender']} Subject: {email['subject']} Body: {email['body']} This email has been categorized as: {category} Draft a brief, professional response that Mr. Hugg can review and personalize before sending. """ # Call the LLM messages = [HumanMessage(content=prompt)] response = model.invoke(messages) # 更新消息以进行追踪 new_messages = state.get("messages", []) + [ {"role": "user", "content": prompt}, {"role": "assistant", "content": response.content} ] # 返回状态更新 return { "draft_response": response.content, "messages": new_messages } def notify_mr_hugg(state: EmailState): """Alfred notifies Mr. Hugg about the email and presents the draft response""" email = state["email"] print("\n" + "="*50) print(f"Sir, you've received an email from {email['sender']}.") print(f"Subject: {email['subject']}") print(f"Category: {state['email_category']}") print("\nI've prepared a draft response for your review:") print("-"*50) print(state["draft_response"]) print("="*50 + "\n") # 我们已处理完这封电子邮件 return {} ``` ## 步骤 3:定义我们的路由逻辑 我们需要一个函数来确定分类后要采取哪条路径: ```python def route_email(state: EmailState) -> str: """Determine the next step based on spam classification""" if state["is_spam"]: return "spam" else: return "legitimate" ``` > 💡 **注意:** LangGraph 调用此路由函数来确定在分类节点之后要跟随哪条边。返回值必须与我们的条件边映射中的一个键匹配。 ## 步骤 4:创建 StateGraph 并定义边 现在我们将所有内容连接在一起: ```python # 创建 graph email_graph = StateGraph(EmailState) # 添加 nodes email_graph.add_node("read_email", read_email) email_graph.add_node("classify_email", classify_email) email_graph.add_node("handle_spam", handle_spam) email_graph.add_node("draft_response", draft_response) email_graph.add_node("notify_mr_hugg", notify_mr_hugg) # 添加 edges - 定义流程 email_graph.add_edge("read_email", "classify_email") # 从 classify_email 添加条件分支 email_graph.add_conditional_edges( "classify_email", route_email, { "spam": "handle_spam", "legitimate": "draft_response" } ) # 添加最后的 edges email_graph.add_edge("handle_spam", END) email_graph.add_edge("draft_response", "notify_mr_hugg") email_graph.add_edge("notify_mr_hugg", END) # 编译 graph compiled_graph = email_graph.compile() ``` 注意我们如何使用 LangGraph 提供的特殊“END”节点。这表示工作流完成的终端状态。 ## 步骤 5:运行应用程序 让我们用一封合法的电子邮件和一封垃圾邮件来测试我们的图表: ```python # 合法电子邮件示例 legitimate_email = { "sender": "john.smith@example.com", "subject": "Question about your services", "body": "Dear Mr. Hugg, I was referred to you by a colleague and I'm interested in learning more about your consulting services. Could we schedule a call next week? Best regards, John Smith" } # 垃圾邮件示例 spam_email = { "sender": "winner@lottery-intl.com", "subject": "YOU HAVE WON $5,000,000!!!", "body": "CONGRATULATIONS! You have been selected as the winner of our international lottery! To claim your $5,000,000 prize, please send us your bank details and a processing fee of $100." } # 处理合法电子邮件 print("\nProcessing legitimate email...") legitimate_result = compiled_graph.invoke({ "email": legitimate_email, "is_spam": None, "spam_reason": None, "email_category": None, "draft_response": None, "messages": [] }) # 处理垃圾邮件 print("\nProcessing spam email...") spam_result = compiled_graph.invoke({ "email": spam_email, "is_spam": None, "spam_reason": None, "email_category": None, "draft_response": None, "messages": [] }) ``` ## 第 6 步:使用 Langfuse 检查我们的邮件分类智能体 📡 随着 Alfred 对主分类智能体进行微调,他越来越厌倦调试其运行。智能体本质上是不可预测的,难以检查。但由于他的目标是构建终极垃圾邮件检测智能体并将其部署到生产中,因此他需要强大的可追溯性以供将来监控和分析。 为此,Alfred 可以使用可观察性工具(例如 [Langfuse](https://langfuse.com/))来跟踪和监控智能体。 首先,我们 pip install Langfuse: ```python %pip install -q langfuse ``` 接下来,我们将 Langfuse API 密钥和主机地址添加为环境变量。您可以通过注册 [Langfuse Cloud](https://cloud.langfuse.com) 或 [self-host Langfuse](https://langfuse.com/self-hosting) 获取 Langfuse 凭据。 ```python import os # Get keys for your project from the project settings page: https://cloud.langfuse.com os.environ["LANGFUSE_PUBLIC_KEY"] = "pk-lf-..." os.environ["LANGFUSE_SECRET_KEY"] = "sk-lf-..." os.environ["LANGFUSE_HOST"] = "https://cloud.langfuse.com" # 🇪🇺 EU region # os.environ["LANGFUSE_HOST"] = "https://us.cloud.langfuse.com" # 🇺🇸 US region ``` 然后,我们配置 [Langfuse `callback_handler`](https://langfuse.com/docs/integrations/langchain/tracing#add-langfuse-to-your-langchain-application),并通过将 `langfuse_callback` 添加到图的调用来检测智能体:`config={"callbacks": [langfuse_handler]}`。 ```python from langfuse.langchain import CallbackHandler # 为 LangGraph/Langchain 初始化 Langfuse CallbackHandler(跟踪) langfuse_handler = CallbackHandler() # 处理合法电子邮件 legitimate_result = compiled_graph.invoke( input={"email": legitimate_email, "is_spam": None, "spam_reason": None, "email_category": None, "draft_response": None, "messages": []}, config={"callbacks": [langfuse_handler]} ) ``` Alfred 现已连接 🔌!LangGraph 的运行记录在 Langfuse 中,使他能够全面了解智能体的行为。通过此设置,他可以重新查看之前的运行并进一步完善他的邮件分类智能体。 ![Langfuse 中的示例跟踪](https://langfuse.com/images/cookbook/huggingface-agent-course/langgraph-trace-legit.png) _[带有合法电子邮件的跟踪的公共链接](https://cloud.langfuse.com/project/cloramnkj0002jz088vzn1ja4/traces/f5d6d72e-20af-4357-b232-af44c3728a7b?timestamp=2025-03-17T10%3A13%3A28.413Z&observation=6997ba69-043f-4f77-9445-700a033afba1)_ ## 可视化我们的图表 LangGraph 允许我们可视化我们的工作流程,以便更好地理解和调试其结构: ```python compiled_graph.get_graph().draw_mermaid_png() ``` <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/LangGraph/mail_flow.png" alt="Mail LangGraph"/> 这会产生一个可视化表示,显示我们的节点如何连接以及可以采取的条件路径。 ## 我们构建了什么 我们创建了一个完整的电子邮件处理工作流程: 1. 接收传入的电子邮件 2. 使用 LLM 将其分类为垃圾邮件或合法邮件 3. 通过丢弃垃圾邮件来处理垃圾邮件 4. 对于合法电子邮件,起草回复并通知 Mr. Hugg 这展示了 LangGraph 使用 LLM 编排复杂工作流程同时保持清晰、结构化流程的强大功能。 ## 关键要点 - **状态管理**:我们定义了全面的状态来跟踪电子邮件处理的所有方面 - **节点实现**:我们创建了与 LLM 交互的功能节点 - **条件路由**:我们根据电子邮件分类实现了分支逻辑 - **终端状态**:我们使用 END 节点标记工作流程中的完成点 ## 下一步是什么? 在下一部分中,我们将探索 LangGraph 的更多高级功能,包括处理工作流中的人机交互以及根据多种条件实现更复杂的分支逻辑。
agents-course/units/zh-CN/unit2/langgraph/first_graph.mdx/0
{ "file_path": "agents-course/units/zh-CN/unit2/langgraph/first_graph.mdx", "repo_id": "agents-course", "token_count": 6502 }
21
# 测验时间! 恭喜你完成了 `smolagents` 的学习材料!你已经取得了很多成就。现在,是时候通过一个测验来测试你的知识了。🧠 ## 说明 - 测验由代码问题组成。 - 你将得到完成代码片段的指示。 - 仔细阅读指示并相应地完成代码片段。 - 对于每个问题,你将得到结果和一些反馈。 🧘 **这个测验不计分也不提供证书**。这是关于你理解 `smolagents` 库,并了解你是否应该在书面材料上花更多时间。在接下来的单元中,你将在用例和项目中测试这些知识。 让我们开始吧! ## 测验 🚀 <iframe src="https://agents-course-unit2-smolagents-quiz.hf.space" frameborder="0" width="850" height="450" ></iframe> 你也可以点击👉 [这里](https://huggingface.co/spaces/agents-course/unit2_smolagents_quiz) 访问测验
agents-course/units/zh-CN/unit2/smolagents/final_quiz.mdx/0
{ "file_path": "agents-course/units/zh-CN/unit2/smolagents/final_quiz.mdx", "repo_id": "agents-course", "token_count": 569 }
22
# 构建并集成智能体工具 节将为 Alfred 赋予网络访问能力,使其能够获取实时新闻与全球资讯。 同时还将集成天气数据和 Hugging Face Hub 模型下载统计功能,帮助其进行时效性话题交流。 ## 赋予智能体网络访问能力 请记住,我们希望 Alfred 能够展现出一位真正的文艺复兴主持人的风采,并对世界有着深刻的了解。 为此,我们需要确保 Alfred 能够获取有关世界的最新新闻和信息。 让我们从为 Alfred 创建一个网络搜索工具开始吧! <hfoptions id="agents-frameworks"> <hfoption id="smolagents"> ```python from smolagents import DuckDuckGoSearchTool # 初始化 DuckDuckGo 搜索工具 search_tool = DuckDuckGoSearchTool() # 示例用法 results = search_tool("Who's the current President of France?") print(results) ``` 预期输出: ``` 法国现任总统为 Emmanuel Macron。 ``` </hfoption> <hfoption id="llama-index"> ```python from llama_index.tools.duckduckgo import DuckDuckGoSearchToolSpec from llama_index.core.tools import FunctionTool # 初始化 DuckDuckGo 搜索工具 tool_spec = DuckDuckGoSearchToolSpec() search_tool = FunctionTool.from_defaults(tool_spec.duckduckgo_full_search) # 示例用法 response = search_tool("Who's the current President of France?") print(response.raw_output[-1]['body']) ``` 预期输出: ``` 法兰西共和国总统是法国的国家元首。现任总统是 Emmanuel Macron,于2017年5月14日就任,并在2017年5月7日举行的总统选举第二轮中击败 Marine Le Pen。法国第五共和国总统名单 编号 肖像 姓名 ... ``` </hfoption> <hfoption id="langgraph"> ```python from langchain_community.tools import DuckDuckGoSearchRun search_tool = DuckDuckGoSearchRun() results = search_tool.invoke("Who's the current President of France?") print(results) ``` 预期输出: ``` Emmanuel Macron (1977年12月21日生于亚眠)法国政治家,2017年当选总统... ``` </hfoption> </hfoptions> ## 创建天气信息工具(烟花调度) 完美的庆典应该在晴朗的天空下燃放烟花,我们需要确保烟花不会因为恶劣天气而取消。 让我们创建一个自定义工具,用于调用外部天气 API 并获取指定位置的天气信息。 <Tip> 为了简单起见,我们在本例中使用了一个虚拟的天气 API。如果您想使用真实的天气 API,您可以实现一个使用 OpenWeatherMap API 的天气工具,就像<a href="../../unit1/tutorial">Unit 1</a>中提到的那样。 </Tip> <hfoptions id="agents-frameworks"> <hfoption id="smolagents"> ```python from smolagents import Tool import random class WeatherInfoTool(Tool): name = "weather_info" description = "Fetches dummy weather information for a given location." inputs = { "location": { "type": "string", "description": "The location to get weather information for." } } output_type = "string" def forward(self, location: str): # 虚拟天气数据 weather_conditions = [ {"condition": "Rainy", "temp_c": 15}, {"condition": "Clear", "temp_c": 25}, {"condition": "Windy", "temp_c": 20} ] # 随机选择一种天气状况 data = random.choice(weather_conditions) return f"Weather in {location}: {data['condition']}, {data['temp_c']}°C" # 初始化工具 weather_info_tool = WeatherInfoTool() ``` </hfoption> <hfoption id="llama-index"> ```python import random from llama_index.core.tools import FunctionTool def get_weather_info(location: str) -> str: """Fetches dummy weather information for a given location.""" # 虚拟天气数据 weather_conditions = [ {"condition": "Rainy", "temp_c": 15}, {"condition": "Clear", "temp_c": 25}, {"condition": "Windy", "temp_c": 20} ] # 随机选择一种天气状况 data = random.choice(weather_conditions) return f"Weather in {location}: {data['condition']}, {data['temp_c']}°C" # 初始化工具 weather_info_tool = FunctionTool.from_defaults(get_weather_info) ``` </hfoption> <hfoption id="langgraph"> ```python from langchain.tools import Tool import random def get_weather_info(location: str) -> str: """Fetches dummy weather information for a given location.""" # 虚拟天气数据 weather_conditions = [ {"condition": "Rainy", "temp_c": 15}, {"condition": "Clear", "temp_c": 25}, {"condition": "Windy", "temp_c": 20} ] # 随机选择一种天气状况 data = random.choice(weather_conditions) return f"Weather in {location}: {data['condition']}, {data['temp_c']}°C" # 初始化工具 weather_info_tool = Tool( name="get_weather_info", func=get_weather_info, description="Fetches dummy weather information for a given location." ) ``` </hfoption> </hfoptions> ## 为有影响力的 AI 开发者创建 Hub 统计工具 出席此次盛会的都是 AI 开发者的精英。Alfred 希望通过讨论他们最受欢迎的模型、数据集和空间来给他们留下深刻印象。我们将创建一个工具,根据用户名从 Hugging Face Hub 获取模型统计数据。 <hfoptions id="agents-frameworks"> <hfoption id="smolagents"> ```python from smolagents import Tool from huggingface_hub import list_models class HubStatsTool(Tool): name = "hub_stats" description = "Fetches the most downloaded model from a specific author on the Hugging Face Hub." inputs = { "author": { "type": "string", "description": "The username of the model author/organization to find models from." } } output_type = "string" def forward(self, author: str): try: # 列出指定作者的模型,按下载次数排序 models = list(list_models(author=author, sort="downloads", direction=-1, limit=1)) if models: model = models[0] return f"The most downloaded model by {author} is {model.id} with {model.downloads:,} downloads." else: return f"No models found for author {author}." except Exception as e: return f"Error fetching models for {author}: {str(e)}" # 初始化工具 hub_stats_tool = HubStatsTool() # 示例用法 print(hub_stats_tool("facebook")) # Example: Get the most downloaded model by Facebook ``` 预期输出: ``` Facebook 下载次数最多的模型是 facebook/esmfold_v1,下载次数为 12,544,550 次。 ``` </hfoption> <hfoption id="llama-index"> ```python import random from llama_index.core.tools import FunctionTool from huggingface_hub import list_models def get_hub_stats(author: str) -> str: """Fetches the most downloaded model from a specific author on the Hugging Face Hub.""" try: # 列出指定作者的模型,按下载次数排序 models = list(list_models(author=author, sort="downloads", direction=-1, limit=1)) if models: model = models[0] return f"The most downloaded model by {author} is {model.id} with {model.downloads:,} downloads." else: return f"No models found for author {author}." except Exception as e: return f"Error fetching models for {author}: {str(e)}" # 初始化工具 hub_stats_tool = FunctionTool.from_defaults(get_hub_stats) # 示例用法 print(hub_stats_tool("facebook")) # Example: Get the most downloaded model by Facebook ``` 预期输出: ``` Facebook 下载次数最多的模型是 facebook/esmfold_v1,下载次数为 12,544,550 次。 ``` </hfoption> <hfoption id="langgraph"> ```python from langchain.tools import Tool from huggingface_hub import list_models def get_hub_stats(author: str) -> str: """Fetches the most downloaded model from a specific author on the Hugging Face Hub.""" try: # 列出指定作者的模型,按下载次数排序 models = list(list_models(author=author, sort="downloads", direction=-1, limit=1)) if models: model = models[0] return f"The most downloaded model by {author} is {model.id} with {model.downloads:,} downloads." else: return f"No models found for author {author}." except Exception as e: return f"Error fetching models for {author}: {str(e)}" # 初始化工具 hub_stats_tool = Tool( name="get_hub_stats", func=get_hub_stats, description="Fetches the most downloaded model from a specific author on the Hugging Face Hub." ) # 示例用法 print(hub_stats_tool.invoke("facebook")) # Example: Get the most downloaded model by Facebook ``` 预期输出: ``` Facebook 下载次数最多的模型是 facebook/esmfold_v1,下载次数为 13,109,861 次。 ``` </hfoption> </hfoptions> 借助 Hub Stats 工具,Alfred 现在可以通过讨论他们最受欢迎的模型来打动有影响力的 AI 开发者。 ## 将工具与 Alfred 集成 现在我们已经拥有了所有工具,让我们将它们集成到 Alfred 的智能体中: <hfoptions id="agents-frameworks"> <hfoption id="smolagents"> ```python from smolagents import CodeAgent, InferenceClientModel # 初始化 Hugging Face 模型 model = InferenceClientModel() # 使用所有工具创建 Alfred alfred = CodeAgent( tools=[search_tool, weather_info_tool, hub_stats_tool], model=model ) # Alfred 在庆典期间可能会收到的示例查询 response = alfred.run("What is Facebook and what's their most popular model?") print("🎩 Alfred's Response:") print(response) ``` 预期输出: ``` 🎩 Alfred's Response: Facebook 是一个社交网站,用户可以在这里互相联系、分享信息并互动。Facebook 在 Hugging Face Hub 上下载次数最多的模型是 ESMFold_v1。 ``` </hfoption> <hfoption id="llama-index"> ```python from llama_index.core.agent.workflow import AgentWorkflow from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI # 初始化 Hugging Face 模型 llm = HuggingFaceInferenceAPI(model_name="Qwen/Qwen2.5-Coder-32B-Instruct") # 使用所有工具创建 Alfred alfred = AgentWorkflow.from_tools_or_functions( [search_tool, weather_info_tool, hub_stats_tool], llm=llm ) # Alfred 在庆典期间可能会收到的示例查询 response = await alfred.run("What is Facebook and what's their most popular model?") print("🎩 Alfred's Response:") print(response) ``` 预期输出: ``` 🎩 Alfred's Response: Facebook 是一家总部位于加利福尼亚州门洛帕克的社交网络服务和科技公司。它由马克·扎克伯格创立,允许用户创建个人资料、与亲朋好友联系、分享照片和视频,以及加入基于共同兴趣的群组。Facebook 在 Hugging Face Hub 上最受欢迎的模型是“facebook/esmfold_v1”,下载量达 13,109,861 次。 ``` </hfoption> <hfoption id="langgraph"> ```python from typing import TypedDict, Annotated from langgraph.graph.message import add_messages from langchain_core.messages import AnyMessage, HumanMessage, AIMessage from langgraph.prebuilt import ToolNode from langgraph.graph import START, StateGraph from langgraph.prebuilt import tools_condition from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace # 生成聊天界面,包括工具 llm = HuggingFaceEndpoint( repo_id="Qwen/Qwen2.5-Coder-32B-Instruct", huggingfacehub_api_token=HUGGINGFACEHUB_API_TOKEN, ) chat = ChatHuggingFace(llm=llm, verbose=True) tools = [search_tool, weather_info_tool, hub_stats_tool] chat_with_tools = chat.bind_tools(tools) # 生成 AgentState 和 Agent 图 class AgentState(TypedDict): messages: Annotated[list[AnyMessage], add_messages] def assistant(state: AgentState): return { "messages": [chat_with_tools.invoke(state["messages"])], } ## 构建流程图 builder = StateGraph(AgentState) # 定义节点:这些节点完成工作 builder.add_node("assistant", assistant) builder.add_node("tools", ToolNode(tools)) # 定义边:这些决定了控制流如何移动 builder.add_edge(START, "assistant") builder.add_conditional_edges( "assistant", # If the latest message requires a tool, route to tools # Otherwise, provide a direct response tools_condition, ) builder.add_edge("tools", "assistant") alfred = builder.compile() messages = [HumanMessage(content="Who is Facebook and what's their most popular model?")] response = alfred.invoke({"messages": messages}) print("🎩 Alfred's Response:") print(response['messages'][-1].content) ``` 预期输出: ``` 🎩 Alfred's Response: Facebook 是一家社交媒体公司,以其社交网站 Facebook 以及 Instagram 和 WhatsApp 等其他服务而闻名。Facebook 在 Hugging Face Hub 上下载次数最多的模型是 facebook/esmfold_v1,下载量达 13,202,321 次。 ``` </hfoption> </hfoptions> ## 结论 通过集成这些工具,Alfred 现在可以处理各种任务,从网页搜索到天气更新和模型统计。这确保他始终是晚会上最了解情况、最有魅力的主持人。 <Tip> 尝试实现一个可用于获取特定主题最新消息的工具。 完成后,在 <code>tools.py</code> 文件中实现您的自定义工具。 </Tip>
agents-course/units/zh-CN/unit3/agentic-rag/tools.mdx/0
{ "file_path": "agents-course/units/zh-CN/unit3/agentic-rag/tools.mdx", "repo_id": "agents-course", "token_count": 6321 }
23
# Advanced Cuda usage
candle/candle-book/src/cuda/README.md/0
{ "file_path": "candle/candle-book/src/cuda/README.md", "repo_id": "candle", "token_count": 6 }
24
#[cfg(test)] pub mod simplified; #[cfg(test)] mod tests { use anyhow::Result; use candle::{DType, Device, Tensor}; use parquet::file::reader::SerializedFileReader; // NOTE: Waiting on https://github.com/rust-lang/mdBook/pull/1856 #[rustfmt::skip] #[tokio::test] async fn book_hub_1() { // ANCHOR: book_hub_1 use candle::Device; use hf_hub::api::tokio::Api; let api = Api::new().unwrap(); let repo = api.model("bert-base-uncased".to_string()); let weights_filename = repo.get("model.safetensors").await.unwrap(); let weights = candle::safetensors::load(weights_filename, &Device::Cpu).unwrap(); // ANCHOR_END: book_hub_1 assert_eq!(weights.len(), 206); } #[rustfmt::skip] #[test] fn book_hub_2() { { // ANCHOR: book_hub_2 use candle::Device; use hf_hub::api::sync::Api; use memmap2::Mmap; use std::fs; let api = Api::new().unwrap(); let repo = api.model("bert-base-uncased".to_string()); let weights_filename = repo.get("model.safetensors").unwrap(); let file = fs::File::open(weights_filename).unwrap(); let mmap = unsafe { Mmap::map(&file).unwrap() }; let weights = candle::safetensors::load_buffer(&mmap[..], &Device::Cpu).unwrap(); // ANCHOR_END: book_hub_2 assert_eq!(weights.len(), 206); } // #[rustfmt::skip] // #[test] // fn book_hub_3() { { // ANCHOR: book_hub_3 use candle::{DType, Device, Tensor}; use hf_hub::api::sync::Api; use memmap2::Mmap; use safetensors::slice::IndexOp; use safetensors::SafeTensors; use std::fs; let api = Api::new().unwrap(); let repo = api.model("bert-base-uncased".to_string()); let weights_filename = repo.get("model.safetensors").unwrap(); let file = fs::File::open(weights_filename).unwrap(); let mmap = unsafe { Mmap::map(&file).unwrap() }; // Use safetensors directly let tensors = SafeTensors::deserialize(&mmap[..]).unwrap(); let view = tensors .tensor("bert.encoder.layer.0.attention.self.query.weight") .unwrap(); // We're going to load shard with rank 1, within a world_size of 4 // We're going to split along dimension 0 doing VIEW[start..stop, :] let rank = 1; let world_size = 4; let dim = 0; let dtype = view.dtype(); let mut tp_shape = view.shape().to_vec(); let size = tp_shape[0]; if size % world_size != 0 { panic!("The dimension is not divisible by `world_size`"); } let block_size = size / world_size; let start = rank * block_size; let stop = (rank + 1) * block_size; // Everything is expressed in tensor dimension // bytes offsets is handled automatically for safetensors. let iterator = view.slice(start..stop).unwrap(); tp_shape[dim] = block_size; // Convert safetensors Dtype to candle DType let dtype: DType = dtype.try_into().unwrap(); // TODO: Implement from_buffer_iterator so we can skip the extra CPU alloc. let raw: Vec<u8> = iterator.into_iter().flatten().cloned().collect(); let tp_tensor = Tensor::from_raw_buffer(&raw, dtype, &tp_shape, &Device::Cpu).unwrap(); // ANCHOR_END: book_hub_3 assert_eq!(view.shape(), &[768, 768]); assert_eq!(tp_tensor.dims(), &[192, 768]); } } #[allow(unused)] #[rustfmt::skip] fn book_training_1() -> Result<()>{ // ANCHOR: book_training_1 use hf_hub::{api::sync::Api, Repo, RepoType}; let dataset_id = "mnist".to_string(); let api = Api::new()?; let repo = Repo::with_revision( dataset_id, RepoType::Dataset, "refs/convert/parquet".to_string(), ); let repo = api.repo(repo); let test_parquet_filename = repo.get("mnist/test/0000.parquet")?; let train_parquet_filename = repo.get("mnist/train/0000.parquet")?; let test_parquet = SerializedFileReader::new(std::fs::File::open(test_parquet_filename)?)?; let train_parquet = SerializedFileReader::new(std::fs::File::open(train_parquet_filename)?)?; // ANCHOR_END: book_training_1 // Ignore unused let _train = train_parquet; // ANCHOR: book_training_2 for row in test_parquet { for (idx, (name, field)) in row?.get_column_iter().enumerate() { println!("Column id {idx}, name {name}, value {field}"); } } // ANCHOR_END: book_training_2 let test_parquet_filename = repo.get("mnist/test/0000.parquet")?; let train_parquet_filename = repo.get("mnist/train/0000.parquet")?; let test_parquet = SerializedFileReader::new(std::fs::File::open(test_parquet_filename)?)?; let train_parquet = SerializedFileReader::new(std::fs::File::open(train_parquet_filename)?)?; // ANCHOR: book_training_3 let test_samples = 10_000; let mut test_buffer_images: Vec<u8> = Vec::with_capacity(test_samples * 784); let mut test_buffer_labels: Vec<u8> = Vec::with_capacity(test_samples); for row in test_parquet{ for (_name, field) in row?.get_column_iter() { if let parquet::record::Field::Group(subrow) = field { for (_name, field) in subrow.get_column_iter() { if let parquet::record::Field::Bytes(value) = field { let image = image::load_from_memory(value.data()).unwrap(); test_buffer_images.extend(image.to_luma8().as_raw()); } } }else if let parquet::record::Field::Long(label) = field { test_buffer_labels.push(*label as u8); } } } let test_images = (Tensor::from_vec(test_buffer_images, (test_samples, 784), &Device::Cpu)?.to_dtype(DType::F32)? / 255.)?; let test_labels = Tensor::from_vec(test_buffer_labels, (test_samples, ), &Device::Cpu)?; let train_samples = 60_000; let mut train_buffer_images: Vec<u8> = Vec::with_capacity(train_samples * 784); let mut train_buffer_labels: Vec<u8> = Vec::with_capacity(train_samples); for row in train_parquet{ for (_name, field) in row?.get_column_iter() { if let parquet::record::Field::Group(subrow) = field { for (_name, field) in subrow.get_column_iter() { if let parquet::record::Field::Bytes(value) = field { let image = image::load_from_memory(value.data()).unwrap(); train_buffer_images.extend(image.to_luma8().as_raw()); } } }else if let parquet::record::Field::Long(label) = field { train_buffer_labels.push(*label as u8); } } } let train_images = (Tensor::from_vec(train_buffer_images, (train_samples, 784), &Device::Cpu)?.to_dtype(DType::F32)? / 255.)?; let train_labels = Tensor::from_vec(train_buffer_labels, (train_samples, ), &Device::Cpu)?; let mnist = candle_datasets::vision::Dataset { train_images, train_labels, test_images, test_labels, labels: 10, }; // ANCHOR_END: book_training_3 assert_eq!(mnist.test_images.dims(), &[10_000, 784]); assert_eq!(mnist.test_labels.dims(), &[10_000]); assert_eq!(mnist.train_images.dims(), &[60_000, 784]); assert_eq!(mnist.train_labels.dims(), &[60_000]); Ok(()) } }
candle/candle-book/src/lib.rs/0
{ "file_path": "candle/candle-book/src/lib.rs", "repo_id": "candle", "token_count": 2808 }
25
pub(crate) mod affine; pub(crate) mod conv_transpose2d; pub(crate) mod copy; pub(crate) mod matmul; pub(crate) mod qmatmul; pub(crate) mod random; pub(crate) mod reduce; pub(crate) mod unary; pub(crate) mod where_cond; use candle_core::{Device, Result}; pub(crate) trait BenchDevice { fn sync(&self) -> Result<()>; fn bench_name<S: Into<String>>(&self, name: S) -> String; } impl BenchDevice for Device { fn sync(&self) -> Result<()> { match self { Device::Cpu => Ok(()), Device::Cuda(device) => { #[cfg(feature = "cuda")] { use cuda::WrapErr; return Ok(device.synchronize().w()?); } #[cfg(not(feature = "cuda"))] panic!("Cuda device without cuda feature enabled: {:?}", device) } Device::Metal(device) => { #[cfg(feature = "metal")] return Ok(device.wait_until_completed()?); #[cfg(not(feature = "metal"))] panic!("Metal device without metal feature enabled: {:?}", device) } } } fn bench_name<S: Into<String>>(&self, name: S) -> String { match self { Device::Cpu => { let cpu_type = if cfg!(feature = "accelerate") { "accelerate" } else if cfg!(feature = "mkl") { "mkl" } else { "cpu" }; format!("{}_{}", cpu_type, name.into()) } Device::Cuda(_) => format!("cuda_{}", name.into()), Device::Metal(_) => format!("metal_{}", name.into()), } } } struct BenchDeviceHandler { devices: Vec<Device>, } impl BenchDeviceHandler { pub fn new() -> Result<Self> { let mut devices = Vec::new(); if cfg!(feature = "metal") { devices.push(Device::new_metal(0)?); } else if cfg!(feature = "cuda") { devices.push(Device::new_cuda(0)?); } devices.push(Device::Cpu); Ok(Self { devices }) } }
candle/candle-core/benches/benchmarks/mod.rs/0
{ "file_path": "candle/candle-core/benches/benchmarks/mod.rs", "repo_id": "candle", "token_count": 1142 }
26
#![allow(clippy::excessive_precision)] // Code taken from https://github.com/statrs-dev/statrs //! Provides the [error](https://en.wikipedia.org/wiki/Error_function) and //! related functions mod evaluate { //! Provides functions that don't have a numerical solution and must //! be solved computationally (e.g. evaluation of a polynomial) /// evaluates a polynomial at `z` where `coeff` are the coeffecients /// to a polynomial of order `k` where `k` is the length of `coeff` and the /// coeffecient /// to the `k`th power is the `k`th element in coeff. E.g. [3,-1,2] equates to /// `2z^2 - z + 3` /// /// # Remarks /// /// Returns 0 for a 0 length coefficient slice pub fn polynomial(z: f64, coeff: &[f64]) -> f64 { let n = coeff.len(); if n == 0 { return 0.0; } let mut sum = *coeff.last().unwrap(); for c in coeff[0..n - 1].iter().rev() { sum = *c + z * sum; } sum } } use std::f64; /// `erf` calculates the error function at `x`. pub fn erf(x: f64) -> f64 { if x.is_nan() { f64::NAN } else if x >= 0.0 && x.is_infinite() { 1.0 } else if x <= 0.0 && x.is_infinite() { -1.0 } else if x == 0. { 0.0 } else { erf_impl(x, false) } } /// `erf_inv` calculates the inverse error function /// at `x`. pub fn erf_inv(x: f64) -> f64 { if x == 0.0 { 0.0 } else if x >= 1.0 { f64::INFINITY } else if x <= -1.0 { f64::NEG_INFINITY } else if x < 0.0 { erf_inv_impl(-x, 1.0 + x, -1.0) } else { erf_inv_impl(x, 1.0 - x, 1.0) } } /// `erfc` calculates the complementary error function /// at `x`. pub fn erfc(x: f64) -> f64 { if x.is_nan() { f64::NAN } else if x == f64::INFINITY { 0.0 } else if x == f64::NEG_INFINITY { 2.0 } else { erf_impl(x, true) } } /// `erfc_inv` calculates the complementary inverse /// error function at `x`. pub fn erfc_inv(x: f64) -> f64 { if x <= 0.0 { f64::INFINITY } else if x >= 2.0 { f64::NEG_INFINITY } else if x > 1.0 { erf_inv_impl(-1.0 + x, 2.0 - x, -1.0) } else { erf_inv_impl(1.0 - x, x, 1.0) } } // ********************************************************** // ********** Coefficients for erf_impl polynomial ********** // ********************************************************** /// Polynomial coefficients for a numerator of `erf_impl` /// in the interval [1e-10, 0.5]. const ERF_IMPL_AN: &[f64] = &[ 0.00337916709551257388990745, -0.00073695653048167948530905, -0.374732337392919607868241, 0.0817442448733587196071743, -0.0421089319936548595203468, 0.0070165709512095756344528, -0.00495091255982435110337458, 0.000871646599037922480317225, ]; /// Polynomial coefficients for a denominator of `erf_impl` /// in the interval [1e-10, 0.5] const ERF_IMPL_AD: &[f64] = &[ 1.0, -0.218088218087924645390535, 0.412542972725442099083918, -0.0841891147873106755410271, 0.0655338856400241519690695, -0.0120019604454941768171266, 0.00408165558926174048329689, -0.000615900721557769691924509, ]; /// Polynomial coefficients for a numerator in `erf_impl` /// in the interval [0.5, 0.75]. const ERF_IMPL_BN: &[f64] = &[ -0.0361790390718262471360258, 0.292251883444882683221149, 0.281447041797604512774415, 0.125610208862766947294894, 0.0274135028268930549240776, 0.00250839672168065762786937, ]; /// Polynomial coefficients for a denominator in `erf_impl` /// in the interval [0.5, 0.75]. const ERF_IMPL_BD: &[f64] = &[ 1.0, 1.8545005897903486499845, 1.43575803037831418074962, 0.582827658753036572454135, 0.124810476932949746447682, 0.0113724176546353285778481, ]; /// Polynomial coefficients for a numerator in `erf_impl` /// in the interval [0.75, 1.25]. const ERF_IMPL_CN: &[f64] = &[ -0.0397876892611136856954425, 0.153165212467878293257683, 0.191260295600936245503129, 0.10276327061989304213645, 0.029637090615738836726027, 0.0046093486780275489468812, 0.000307607820348680180548455, ]; /// Polynomial coefficients for a denominator in `erf_impl` /// in the interval [0.75, 1.25]. const ERF_IMPL_CD: &[f64] = &[ 1.0, 1.95520072987627704987886, 1.64762317199384860109595, 0.768238607022126250082483, 0.209793185936509782784315, 0.0319569316899913392596356, 0.00213363160895785378615014, ]; /// Polynomial coefficients for a numerator in `erf_impl` /// in the interval [1.25, 2.25]. const ERF_IMPL_DN: &[f64] = &[ -0.0300838560557949717328341, 0.0538578829844454508530552, 0.0726211541651914182692959, 0.0367628469888049348429018, 0.00964629015572527529605267, 0.00133453480075291076745275, 0.778087599782504251917881e-4, ]; /// Polynomial coefficients for a denominator in `erf_impl` /// in the interval [1.25, 2.25]. const ERF_IMPL_DD: &[f64] = &[ 1.0, 1.75967098147167528287343, 1.32883571437961120556307, 0.552528596508757581287907, 0.133793056941332861912279, 0.0179509645176280768640766, 0.00104712440019937356634038, -0.106640381820357337177643e-7, ]; /// Polynomial coefficients for a numerator in `erf_impl` /// in the interval [2.25, 3.5]. const ERF_IMPL_EN: &[f64] = &[ -0.0117907570137227847827732, 0.014262132090538809896674, 0.0202234435902960820020765, 0.00930668299990432009042239, 0.00213357802422065994322516, 0.00025022987386460102395382, 0.120534912219588189822126e-4, ]; /// Polynomial coefficients for a denominator in `erf_impl` /// in the interval [2.25, 3.5]. const ERF_IMPL_ED: &[f64] = &[ 1.0, 1.50376225203620482047419, 0.965397786204462896346934, 0.339265230476796681555511, 0.0689740649541569716897427, 0.00771060262491768307365526, 0.000371421101531069302990367, ]; /// Polynomial coefficients for a numerator in `erf_impl` /// in the interval [3.5, 5.25]. const ERF_IMPL_FN: &[f64] = &[ -0.00546954795538729307482955, 0.00404190278731707110245394, 0.0054963369553161170521356, 0.00212616472603945399437862, 0.000394984014495083900689956, 0.365565477064442377259271e-4, 0.135485897109932323253786e-5, ]; /// Polynomial coefficients for a denominator in `erf_impl` /// in the interval [3.5, 5.25]. const ERF_IMPL_FD: &[f64] = &[ 1.0, 1.21019697773630784832251, 0.620914668221143886601045, 0.173038430661142762569515, 0.0276550813773432047594539, 0.00240625974424309709745382, 0.891811817251336577241006e-4, -0.465528836283382684461025e-11, ]; /// Polynomial coefficients for a numerator in `erf_impl` /// in the interval [5.25, 8]. const ERF_IMPL_GN: &[f64] = &[ -0.00270722535905778347999196, 0.0013187563425029400461378, 0.00119925933261002333923989, 0.00027849619811344664248235, 0.267822988218331849989363e-4, 0.923043672315028197865066e-6, ]; /// Polynomial coefficients for a denominator in `erf_impl` /// in the interval [5.25, 8]. const ERF_IMPL_GD: &[f64] = &[ 1.0, 0.814632808543141591118279, 0.268901665856299542168425, 0.0449877216103041118694989, 0.00381759663320248459168994, 0.000131571897888596914350697, 0.404815359675764138445257e-11, ]; /// Polynomial coefficients for a numerator in `erf_impl` /// in the interval [8, 11.5]. const ERF_IMPL_HN: &[f64] = &[ -0.00109946720691742196814323, 0.000406425442750422675169153, 0.000274499489416900707787024, 0.465293770646659383436343e-4, 0.320955425395767463401993e-5, 0.778286018145020892261936e-7, ]; /// Polynomial coefficients for a denominator in `erf_impl` /// in the interval [8, 11.5]. const ERF_IMPL_HD: &[f64] = &[ 1.0, 0.588173710611846046373373, 0.139363331289409746077541, 0.0166329340417083678763028, 0.00100023921310234908642639, 0.24254837521587225125068e-4, ]; /// Polynomial coefficients for a numerator in `erf_impl` /// in the interval [11.5, 17]. const ERF_IMPL_IN: &[f64] = &[ -0.00056907993601094962855594, 0.000169498540373762264416984, 0.518472354581100890120501e-4, 0.382819312231928859704678e-5, 0.824989931281894431781794e-7, ]; /// Polynomial coefficients for a denominator in `erf_impl` /// in the interval [11.5, 17]. const ERF_IMPL_ID: &[f64] = &[ 1.0, 0.339637250051139347430323, 0.043472647870310663055044, 0.00248549335224637114641629, 0.535633305337152900549536e-4, -0.117490944405459578783846e-12, ]; /// Polynomial coefficients for a numerator in `erf_impl` /// in the interval [17, 24]. const ERF_IMPL_JN: &[f64] = &[ -0.000241313599483991337479091, 0.574224975202501512365975e-4, 0.115998962927383778460557e-4, 0.581762134402593739370875e-6, 0.853971555085673614607418e-8, ]; /// Polynomial coefficients for a denominator in `erf_impl` /// in the interval [17, 24]. const ERF_IMPL_JD: &[f64] = &[ 1.0, 0.233044138299687841018015, 0.0204186940546440312625597, 0.000797185647564398289151125, 0.117019281670172327758019e-4, ]; /// Polynomial coefficients for a numerator in `erf_impl` /// in the interval [24, 38]. const ERF_IMPL_KN: &[f64] = &[ -0.000146674699277760365803642, 0.162666552112280519955647e-4, 0.269116248509165239294897e-5, 0.979584479468091935086972e-7, 0.101994647625723465722285e-8, ]; /// Polynomial coefficients for a denominator in `erf_impl` /// in the interval [24, 38]. const ERF_IMPL_KD: &[f64] = &[ 1.0, 0.165907812944847226546036, 0.0103361716191505884359634, 0.000286593026373868366935721, 0.298401570840900340874568e-5, ]; /// Polynomial coefficients for a numerator in `erf_impl` /// in the interval [38, 60]. const ERF_IMPL_LN: &[f64] = &[ -0.583905797629771786720406e-4, 0.412510325105496173512992e-5, 0.431790922420250949096906e-6, 0.993365155590013193345569e-8, 0.653480510020104699270084e-10, ]; /// Polynomial coefficients for a denominator in `erf_impl` /// in the interval [38, 60]. const ERF_IMPL_LD: &[f64] = &[ 1.0, 0.105077086072039915406159, 0.00414278428675475620830226, 0.726338754644523769144108e-4, 0.477818471047398785369849e-6, ]; /// Polynomial coefficients for a numerator in `erf_impl` /// in the interval [60, 85]. const ERF_IMPL_MN: &[f64] = &[ -0.196457797609229579459841e-4, 0.157243887666800692441195e-5, 0.543902511192700878690335e-7, 0.317472492369117710852685e-9, ]; /// Polynomial coefficients for a denominator in `erf_impl` /// in the interval [60, 85]. const ERF_IMPL_MD: &[f64] = &[ 1.0, 0.052803989240957632204885, 0.000926876069151753290378112, 0.541011723226630257077328e-5, 0.535093845803642394908747e-15, ]; /// Polynomial coefficients for a numerator in `erf_impl` /// in the interval [85, 110]. const ERF_IMPL_NN: &[f64] = &[ -0.789224703978722689089794e-5, 0.622088451660986955124162e-6, 0.145728445676882396797184e-7, 0.603715505542715364529243e-10, ]; /// Polynomial coefficients for a denominator in `erf_impl` /// in the interval [85, 110]. const ERF_IMPL_ND: &[f64] = &[ 1.0, 0.0375328846356293715248719, 0.000467919535974625308126054, 0.193847039275845656900547e-5, ]; // ********************************************************** // ********** Coefficients for erf_inv_impl polynomial ****** // ********************************************************** /// Polynomial coefficients for a numerator of `erf_inv_impl` /// in the interval [0, 0.5]. const ERF_INV_IMPL_AN: &[f64] = &[ -0.000508781949658280665617, -0.00836874819741736770379, 0.0334806625409744615033, -0.0126926147662974029034, -0.0365637971411762664006, 0.0219878681111168899165, 0.00822687874676915743155, -0.00538772965071242932965, ]; /// Polynomial coefficients for a denominator of `erf_inv_impl` /// in the interval [0, 0.5]. const ERF_INV_IMPL_AD: &[f64] = &[ 1.0, -0.970005043303290640362, -1.56574558234175846809, 1.56221558398423026363, 0.662328840472002992063, -0.71228902341542847553, -0.0527396382340099713954, 0.0795283687341571680018, -0.00233393759374190016776, 0.000886216390456424707504, ]; /// Polynomial coefficients for a numerator of `erf_inv_impl` /// in the interval [0.5, 0.75]. const ERF_INV_IMPL_BN: &[f64] = &[ -0.202433508355938759655, 0.105264680699391713268, 8.37050328343119927838, 17.6447298408374015486, -18.8510648058714251895, -44.6382324441786960818, 17.445385985570866523, 21.1294655448340526258, -3.67192254707729348546, ]; /// Polynomial coefficients for a denominator of `erf_inv_impl` /// in the interval [0.5, 0.75]. const ERF_INV_IMPL_BD: &[f64] = &[ 1.0, 6.24264124854247537712, 3.9713437953343869095, -28.6608180499800029974, -20.1432634680485188801, 48.5609213108739935468, 10.8268667355460159008, -22.6436933413139721736, 1.72114765761200282724, ]; /// Polynomial coefficients for a numerator of `erf_inv_impl` /// in the interval [0.75, 1] with x less than 3. const ERF_INV_IMPL_CN: &[f64] = &[ -0.131102781679951906451, -0.163794047193317060787, 0.117030156341995252019, 0.387079738972604337464, 0.337785538912035898924, 0.142869534408157156766, 0.0290157910005329060432, 0.00214558995388805277169, -0.679465575181126350155e-6, 0.285225331782217055858e-7, -0.681149956853776992068e-9, ]; /// Polynomial coefficients for a denominator of `erf_inv_impl` /// in the interval [0.75, 1] with x less than 3. const ERF_INV_IMPL_CD: &[f64] = &[ 1.0, 3.46625407242567245975, 5.38168345707006855425, 4.77846592945843778382, 2.59301921623620271374, 0.848854343457902036425, 0.152264338295331783612, 0.01105924229346489121, ]; /// Polynomial coefficients for a numerator of `erf_inv_impl` /// in the interval [0.75, 1] with x between 3 and 6. const ERF_INV_IMPL_DN: &[f64] = &[ -0.0350353787183177984712, -0.00222426529213447927281, 0.0185573306514231072324, 0.00950804701325919603619, 0.00187123492819559223345, 0.000157544617424960554631, 0.460469890584317994083e-5, -0.230404776911882601748e-9, 0.266339227425782031962e-11, ]; /// Polynomial coefficients for a denominator of `erf_inv_impl` /// in the interval [0.75, 1] with x between 3 and 6. const ERF_INV_IMPL_DD: &[f64] = &[ 1.0, 1.3653349817554063097, 0.762059164553623404043, 0.220091105764131249824, 0.0341589143670947727934, 0.00263861676657015992959, 0.764675292302794483503e-4, ]; /// Polynomial coefficients for a numerator of `erf_inv_impl` /// in the interval [0.75, 1] with x between 6 and 18. const ERF_INV_IMPL_EN: &[f64] = &[ -0.0167431005076633737133, -0.00112951438745580278863, 0.00105628862152492910091, 0.000209386317487588078668, 0.149624783758342370182e-4, 0.449696789927706453732e-6, 0.462596163522878599135e-8, -0.281128735628831791805e-13, 0.99055709973310326855e-16, ]; /// Polynomial coefficients for a denominator of `erf_inv_impl` /// in the interval [0.75, 1] with x between 6 and 18. const ERF_INV_IMPL_ED: &[f64] = &[ 1.0, 0.591429344886417493481, 0.138151865749083321638, 0.0160746087093676504695, 0.000964011807005165528527, 0.275335474764726041141e-4, 0.282243172016108031869e-6, ]; /// Polynomial coefficients for a numerator of `erf_inv_impl` /// in the interval [0.75, 1] with x between 18 and 44. const ERF_INV_IMPL_FN: &[f64] = &[ -0.0024978212791898131227, -0.779190719229053954292e-5, 0.254723037413027451751e-4, 0.162397777342510920873e-5, 0.396341011304801168516e-7, 0.411632831190944208473e-9, 0.145596286718675035587e-11, -0.116765012397184275695e-17, ]; /// Polynomial coefficients for a denominator of `erf_inv_impl` /// in the interval [0.75, 1] with x between 18 and 44. const ERF_INV_IMPL_FD: &[f64] = &[ 1.0, 0.207123112214422517181, 0.0169410838120975906478, 0.000690538265622684595676, 0.145007359818232637924e-4, 0.144437756628144157666e-6, 0.509761276599778486139e-9, ]; /// Polynomial coefficients for a numerator of `erf_inv_impl` /// in the interval [0.75, 1] with x greater than 44. const ERF_INV_IMPL_GN: &[f64] = &[ -0.000539042911019078575891, -0.28398759004727721098e-6, 0.899465114892291446442e-6, 0.229345859265920864296e-7, 0.225561444863500149219e-9, 0.947846627503022684216e-12, 0.135880130108924861008e-14, -0.348890393399948882918e-21, ]; /// Polynomial coefficients for a denominator of `erf_inv_impl` /// in the interval [0.75, 1] with x greater than 44. const ERF_INV_IMPL_GD: &[f64] = &[ 1.0, 0.0845746234001899436914, 0.00282092984726264681981, 0.468292921940894236786e-4, 0.399968812193862100054e-6, 0.161809290887904476097e-8, 0.231558608310259605225e-11, ]; /// `erf_impl` computes the error function at `z`. /// If `inv` is true, `1 - erf` is calculated as opposed to `erf` fn erf_impl(z: f64, inv: bool) -> f64 { if z < 0.0 { if !inv { return -erf_impl(-z, false); } if z < -0.5 { return 2.0 - erf_impl(-z, true); } return 1.0 + erf_impl(-z, false); } let result = if z < 0.5 { if z < 1e-10 { z * 1.125 + z * 0.003379167095512573896158903121545171688 } else { z * 1.125 + z * evaluate::polynomial(z, ERF_IMPL_AN) / evaluate::polynomial(z, ERF_IMPL_AD) } } else if z < 110.0 { let (r, b) = if z < 0.75 { ( evaluate::polynomial(z - 0.5, ERF_IMPL_BN) / evaluate::polynomial(z - 0.5, ERF_IMPL_BD), 0.3440242112, ) } else if z < 1.25 { ( evaluate::polynomial(z - 0.75, ERF_IMPL_CN) / evaluate::polynomial(z - 0.75, ERF_IMPL_CD), 0.419990927, ) } else if z < 2.25 { ( evaluate::polynomial(z - 1.25, ERF_IMPL_DN) / evaluate::polynomial(z - 1.25, ERF_IMPL_DD), 0.4898625016, ) } else if z < 3.5 { ( evaluate::polynomial(z - 2.25, ERF_IMPL_EN) / evaluate::polynomial(z - 2.25, ERF_IMPL_ED), 0.5317370892, ) } else if z < 5.25 { ( evaluate::polynomial(z - 3.5, ERF_IMPL_FN) / evaluate::polynomial(z - 3.5, ERF_IMPL_FD), 0.5489973426, ) } else if z < 8.0 { ( evaluate::polynomial(z - 5.25, ERF_IMPL_GN) / evaluate::polynomial(z - 5.25, ERF_IMPL_GD), 0.5571740866, ) } else if z < 11.5 { ( evaluate::polynomial(z - 8.0, ERF_IMPL_HN) / evaluate::polynomial(z - 8.0, ERF_IMPL_HD), 0.5609807968, ) } else if z < 17.0 { ( evaluate::polynomial(z - 11.5, ERF_IMPL_IN) / evaluate::polynomial(z - 11.5, ERF_IMPL_ID), 0.5626493692, ) } else if z < 24.0 { ( evaluate::polynomial(z - 17.0, ERF_IMPL_JN) / evaluate::polynomial(z - 17.0, ERF_IMPL_JD), 0.5634598136, ) } else if z < 38.0 { ( evaluate::polynomial(z - 24.0, ERF_IMPL_KN) / evaluate::polynomial(z - 24.0, ERF_IMPL_KD), 0.5638477802, ) } else if z < 60.0 { ( evaluate::polynomial(z - 38.0, ERF_IMPL_LN) / evaluate::polynomial(z - 38.0, ERF_IMPL_LD), 0.5640528202, ) } else if z < 85.0 { ( evaluate::polynomial(z - 60.0, ERF_IMPL_MN) / evaluate::polynomial(z - 60.0, ERF_IMPL_MD), 0.5641309023, ) } else { ( evaluate::polynomial(z - 85.0, ERF_IMPL_NN) / evaluate::polynomial(z - 85.0, ERF_IMPL_ND), 0.5641584396, ) }; let g = (-z * z).exp() / z; g * b + g * r } else { 0.0 }; if inv && z >= 0.5 { result } else if z >= 0.5 || inv { 1.0 - result } else { result } } // `erf_inv_impl` computes the inverse error function where // `p`,`q`, and `s` are the first, second, and third intermediate // parameters respectively fn erf_inv_impl(p: f64, q: f64, s: f64) -> f64 { let result = if p <= 0.5 { let y = 0.0891314744949340820313; let g = p * (p + 10.0); let r = evaluate::polynomial(p, ERF_INV_IMPL_AN) / evaluate::polynomial(p, ERF_INV_IMPL_AD); g * y + g * r } else if q >= 0.25 { let y = 2.249481201171875; let g = (-2.0 * q.ln()).sqrt(); let xs = q - 0.25; let r = evaluate::polynomial(xs, ERF_INV_IMPL_BN) / evaluate::polynomial(xs, ERF_INV_IMPL_BD); g / (y + r) } else { let x = (-q.ln()).sqrt(); if x < 3.0 { let y = 0.807220458984375; let xs = x - 1.125; let r = evaluate::polynomial(xs, ERF_INV_IMPL_CN) / evaluate::polynomial(xs, ERF_INV_IMPL_CD); y * x + r * x } else if x < 6.0 { let y = 0.93995571136474609375; let xs = x - 3.0; let r = evaluate::polynomial(xs, ERF_INV_IMPL_DN) / evaluate::polynomial(xs, ERF_INV_IMPL_DD); y * x + r * x } else if x < 18.0 { let y = 0.98362827301025390625; let xs = x - 6.0; let r = evaluate::polynomial(xs, ERF_INV_IMPL_EN) / evaluate::polynomial(xs, ERF_INV_IMPL_ED); y * x + r * x } else if x < 44.0 { let y = 0.99714565277099609375; let xs = x - 18.0; let r = evaluate::polynomial(xs, ERF_INV_IMPL_FN) / evaluate::polynomial(xs, ERF_INV_IMPL_FD); y * x + r * x } else { let y = 0.99941349029541015625; let xs = x - 44.0; let r = evaluate::polynomial(xs, ERF_INV_IMPL_GN) / evaluate::polynomial(xs, ERF_INV_IMPL_GD); y * x + r * x } }; s * result }
candle/candle-core/src/cpu/erf.rs/0
{ "file_path": "candle/candle-core/src/cpu/erf.rs", "repo_id": "candle", "token_count": 11974 }
27
//! Implementation of the Cuda backend when Cuda support has not been compiled in. //! #![allow(dead_code)] use crate::op::{BinaryOpT, CmpOp, ReduceOp, UnaryOpT}; use crate::{CpuStorage, DType, Error, Layout, Result, Shape}; #[derive(Debug, Clone)] pub struct CudaDevice; #[derive(Debug)] pub struct CudaStorage; macro_rules! fail { () => { unimplemented!("cuda support has not been enabled, add `cuda` feature to enable.") }; } impl CudaDevice { pub fn new_with_stream(_: usize) -> Result<Self> { Err(Error::NotCompiledWithCudaSupport) } } impl crate::backend::BackendStorage for CudaStorage { type Device = CudaDevice; fn try_clone(&self, _: &Layout) -> Result<Self> { Err(Error::NotCompiledWithCudaSupport) } fn dtype(&self) -> DType { fail!() } fn device(&self) -> &Self::Device { fail!() } fn const_set(&mut self, _: crate::scalar::Scalar, _: &Layout) -> Result<()> { Err(Error::NotCompiledWithCudaSupport) } fn to_cpu_storage(&self) -> Result<CpuStorage> { Err(Error::NotCompiledWithCudaSupport) } fn affine(&self, _: &Layout, _: f64, _: f64) -> Result<Self> { Err(Error::NotCompiledWithCudaSupport) } fn powf(&self, _: &Layout, _: f64) -> Result<Self> { Err(Error::NotCompiledWithCudaSupport) } fn elu(&self, _: &Layout, _: f64) -> Result<Self> { Err(Error::NotCompiledWithCudaSupport) } fn reduce_op(&self, _: ReduceOp, _: &Layout, _: &[usize]) -> Result<Self> { Err(Error::NotCompiledWithCudaSupport) } fn cmp(&self, _: CmpOp, _: &Self, _: &Layout, _: &Layout) -> Result<Self> { Err(Error::NotCompiledWithCudaSupport) } fn to_dtype(&self, _: &Layout, _: DType) -> Result<Self> { Err(Error::NotCompiledWithCudaSupport) } fn unary_impl<B: UnaryOpT>(&self, _: &Layout) -> Result<Self> { Err(Error::NotCompiledWithCudaSupport) } fn binary_impl<B: BinaryOpT>(&self, _: &Self, _: &Layout, _: &Layout) -> Result<Self> { Err(Error::NotCompiledWithCudaSupport) } fn where_cond(&self, _: &Layout, _: &Self, _: &Layout, _: &Self, _: &Layout) -> Result<Self> { Err(Error::NotCompiledWithCudaSupport) } fn conv1d( &self, _: &Layout, _: &Self, _: &Layout, _: &crate::conv::ParamsConv1D, ) -> Result<Self> { Err(Error::NotCompiledWithCudaSupport) } fn conv_transpose1d( &self, _: &Layout, _: &Self, _: &Layout, _: &crate::conv::ParamsConvTranspose1D, ) -> Result<Self> { Err(Error::NotCompiledWithCudaSupport) } fn conv2d( &self, _: &Layout, _: &Self, _: &Layout, _: &crate::conv::ParamsConv2D, ) -> Result<Self> { Err(Error::NotCompiledWithCudaSupport) } fn conv_transpose2d( &self, _l: &Layout, _kernel: &Self, _kernel_l: &Layout, _params: &crate::conv::ParamsConvTranspose2D, ) -> Result<Self> { Err(Error::NotCompiledWithCudaSupport) } fn index_select(&self, _: &Self, _: &Layout, _: &Layout, _: usize) -> Result<Self> { Err(Error::NotCompiledWithCudaSupport) } fn gather(&self, _: &Layout, _: &Self, _: &Layout, _: usize) -> Result<Self> { Err(Error::NotCompiledWithCudaSupport) } fn scatter_set( &mut self, _: &Layout, _: &Self, _: &Layout, _: &Self, _: &Layout, _: usize, ) -> Result<()> { Err(Error::NotCompiledWithCudaSupport) } fn scatter_add_set( &mut self, _: &Layout, _: &Self, _: &Layout, _: &Self, _: &Layout, _: usize, ) -> Result<()> { Err(Error::NotCompiledWithCudaSupport) } fn index_add( &self, _: &Layout, _: &Self, _: &Layout, _: &Self, _: &Layout, _: usize, ) -> Result<Self> { Err(Error::NotCompiledWithCudaSupport) } fn matmul( &self, _: &Self, _: (usize, usize, usize, usize), _: &Layout, _: &Layout, ) -> Result<Self> { Err(Error::NotCompiledWithCudaSupport) } fn copy_strided_src(&self, _: &mut Self, _: usize, _: &Layout) -> Result<()> { Err(Error::NotCompiledWithCudaSupport) } fn copy2d( &self, _: &mut Self, _: usize, _: usize, _: usize, _: usize, _: usize, _: usize, ) -> Result<()> { Err(Error::NotCompiledWithCudaSupport) } fn avg_pool2d(&self, _: &Layout, _: (usize, usize), _: (usize, usize)) -> Result<Self> { Err(Error::NotCompiledWithCudaSupport) } fn max_pool2d(&self, _: &Layout, _: (usize, usize), _: (usize, usize)) -> Result<Self> { Err(Error::NotCompiledWithCudaSupport) } fn upsample_nearest1d(&self, _: &Layout, _: usize) -> Result<Self> { Err(Error::NotCompiledWithCudaSupport) } fn upsample_nearest2d(&self, _: &Layout, _: usize, _: usize) -> Result<Self> { Err(Error::NotCompiledWithCudaSupport) } } impl crate::backend::BackendDevice for CudaDevice { type Storage = CudaStorage; fn new(_: usize) -> Result<Self> { Err(Error::NotCompiledWithCudaSupport) } fn set_seed(&self, _: u64) -> Result<()> { Err(Error::NotCompiledWithCudaSupport) } fn location(&self) -> crate::DeviceLocation { fail!() } fn same_device(&self, _: &Self) -> bool { fail!() } fn zeros_impl(&self, _shape: &Shape, _dtype: DType) -> Result<Self::Storage> { Err(Error::NotCompiledWithCudaSupport) } unsafe fn alloc_uninit(&self, _shape: &Shape, _dtype: DType) -> Result<Self::Storage> { Err(Error::NotCompiledWithCudaSupport) } fn storage_from_slice<T: crate::WithDType>(&self, _: &[T]) -> Result<Self::Storage> { Err(Error::NotCompiledWithCudaSupport) } fn storage_from_cpu_storage(&self, _: &CpuStorage) -> Result<Self::Storage> { Err(Error::NotCompiledWithCudaSupport) } fn storage_from_cpu_storage_owned(&self, _: CpuStorage) -> Result<Self::Storage> { Err(Error::NotCompiledWithCudaSupport) } fn rand_uniform(&self, _: &Shape, _: DType, _: f64, _: f64) -> Result<Self::Storage> { Err(Error::NotCompiledWithCudaSupport) } fn rand_normal(&self, _: &Shape, _: DType, _: f64, _: f64) -> Result<Self::Storage> { Err(Error::NotCompiledWithCudaSupport) } fn synchronize(&self) -> Result<()> { Ok(()) } } /// This bool controls whether reduced precision reductions (e.g., with fp16 accumulation type) are /// allowed with f16 GEMMs. pub fn gemm_reduced_precision_f16() -> bool { true } /// This bool controls whether reduced precision reductions (e.g., with fp16 accumulation type) are /// allowed with f16 GEMMs. pub fn set_gemm_reduced_precision_f16(_: bool) {} /// This bool controls whether reduced precision reductions (e.g., with fp16 accumulation type) are /// allowed with bf16 GEMMs. pub fn gemm_reduced_precision_bf16() -> bool { true } /// This bool controls whether reduced precision reductions (e.g., with fp16 accumulation type) are /// allowed with bf16 GEMMs. pub fn set_gemm_reduced_precision_bf16(_: bool) {} /// This bool controls whether reduced precision reductions (e.g., with tf32 accumulation type) are /// allowed with f32 GEMMs. pub fn gemm_reduced_precision_f32() -> bool { true } /// This bool controls whether reduced precision reductions (e.g., with tf32 accumulation type) are /// allowed with f32 GEMMs. pub fn set_gemm_reduced_precision_f32(_b: bool) {}
candle/candle-core/src/dummy_cuda_backend.rs/0
{ "file_path": "candle/candle-core/src/dummy_cuda_backend.rs", "repo_id": "candle", "token_count": 3546 }
28
//! Support for the GGML file format. use super::{k_quants, GgmlDType, QStorage}; use crate::{Device, Result}; use byteorder::{LittleEndian, ReadBytesExt}; use std::collections::HashMap; // https://github.com/ggerganov/llama.cpp/blob/468ea24fb4633a0d681f7ac84089566c1c6190cb/llama.h#L37 #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum Magic { Ggjt, Ggla, Ggmf, Ggml, Ggsn, } impl TryFrom<u32> for Magic { type Error = crate::Error; fn try_from(value: u32) -> Result<Self> { let magic = match value { 0x67676a74 => Self::Ggjt, 0x67676c61 => Self::Ggla, 0x67676d66 => Self::Ggmf, 0x67676d6c => Self::Ggml, 0x6767736e => Self::Ggsn, _ => crate::bail!("unknown magic {value:08x}"), }; Ok(magic) } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum VersionedMagic { GgmlUnversioned, GgmfV1, GgjtV1, GgjtV2, GgjtV3, } impl VersionedMagic { fn read<R: std::io::Read>(reader: &mut R) -> Result<Self> { let magic = reader.read_u32::<LittleEndian>()?; let magic = Magic::try_from(magic)?; if magic == Magic::Ggml { return Ok(Self::GgmlUnversioned); } let version = reader.read_u32::<LittleEndian>()?; let versioned_magic = match (magic, version) { (Magic::Ggmf, 1) => Self::GgmfV1, (Magic::Ggjt, 1) => Self::GgjtV1, (Magic::Ggjt, 2) => Self::GgjtV2, (Magic::Ggjt, 3) => Self::GgjtV3, _ => crate::bail!("ggml: unsupported magic/version {magic:?}/{version}"), }; Ok(versioned_magic) } fn align32(&self) -> bool { match self { Self::GgmlUnversioned | Self::GgmfV1 => false, Self::GgjtV1 | Self::GgjtV2 | Self::GgjtV3 => true, } } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct HParams { pub n_vocab: u32, pub n_embd: u32, pub n_mult: u32, pub n_head: u32, pub n_layer: u32, pub n_rot: u32, pub ftype: u32, } impl HParams { fn read<R: std::io::Read>(reader: &mut R) -> Result<Self> { let n_vocab = reader.read_u32::<LittleEndian>()?; let n_embd = reader.read_u32::<LittleEndian>()?; let n_mult = reader.read_u32::<LittleEndian>()?; let n_head = reader.read_u32::<LittleEndian>()?; let n_layer = reader.read_u32::<LittleEndian>()?; let n_rot = reader.read_u32::<LittleEndian>()?; let ftype = reader.read_u32::<LittleEndian>()?; Ok(Self { n_vocab, n_embd, n_mult, n_head, n_layer, n_rot, ftype, }) } } #[derive(Debug, Clone, PartialEq)] pub struct Vocab { pub token_score_pairs: Vec<(Vec<u8>, f32)>, } impl Vocab { fn read<R: std::io::Read>(reader: &mut R, n_vocab: usize) -> Result<Self> { // https://github.com/ggerganov/llama.cpp/blob/468ea24fb4633a0d681f7ac84089566c1c6190cb/llama.cpp#L556 let mut token_score_pairs = Vec::with_capacity(n_vocab); for _index in 0..n_vocab { let len = reader.read_u32::<LittleEndian>()? as usize; let mut word = vec![0u8; len]; reader.read_exact(&mut word)?; let score = reader.read_f32::<LittleEndian>()?; token_score_pairs.push((word, score)) } Ok(Self { token_score_pairs }) } } fn from_raw_data<T: super::GgmlType + Send + Sync + 'static>( raw_data: &[u8], size_in_bytes: usize, dims: Vec<usize>, device: &Device, ) -> Result<super::QTensor> { let raw_data_ptr = raw_data.as_ptr(); let n_blocks = size_in_bytes / std::mem::size_of::<T>(); let data = unsafe { std::slice::from_raw_parts(raw_data_ptr as *const T, n_blocks) }; let data: QStorage = match device { Device::Cpu => QStorage::Cpu(Box::new(data.to_vec())), Device::Metal(metal) => super::metal::load_quantized(metal, data)?, Device::Cuda(cuda) => super::cuda::load_quantized(cuda, data)?, }; super::QTensor::new(data, dims) } /// Creates a Tensor from a raw GGML tensor. pub fn qtensor_from_ggml( ggml_dtype: GgmlDType, raw_data: &[u8], dims: Vec<usize>, device: &Device, ) -> Result<super::QTensor> { let tensor_elems = dims.iter().product::<usize>(); let block_size = ggml_dtype.block_size(); if tensor_elems % block_size != 0 { crate::bail!( "the number of elements {tensor_elems} is not divisible by the block size {block_size}" ) } let size_in_bytes = tensor_elems / block_size * ggml_dtype.type_size(); match ggml_dtype { GgmlDType::F32 => from_raw_data::<f32>(raw_data, size_in_bytes, dims, device), GgmlDType::F16 => from_raw_data::<half::f16>(raw_data, size_in_bytes, dims, device), GgmlDType::BF16 => from_raw_data::<half::bf16>(raw_data, size_in_bytes, dims, device), GgmlDType::Q4_0 => { from_raw_data::<k_quants::BlockQ4_0>(raw_data, size_in_bytes, dims, device) } GgmlDType::Q4_1 => { from_raw_data::<k_quants::BlockQ4_1>(raw_data, size_in_bytes, dims, device) } GgmlDType::Q5_0 => { from_raw_data::<k_quants::BlockQ5_0>(raw_data, size_in_bytes, dims, device) } GgmlDType::Q5_1 => { from_raw_data::<k_quants::BlockQ5_1>(raw_data, size_in_bytes, dims, device) } GgmlDType::Q8_0 => { from_raw_data::<k_quants::BlockQ8_0>(raw_data, size_in_bytes, dims, device) } GgmlDType::Q2K => { from_raw_data::<k_quants::BlockQ2K>(raw_data, size_in_bytes, dims, device) } GgmlDType::Q3K => { from_raw_data::<k_quants::BlockQ3K>(raw_data, size_in_bytes, dims, device) } GgmlDType::Q4K => { from_raw_data::<k_quants::BlockQ4K>(raw_data, size_in_bytes, dims, device) } GgmlDType::Q5K => { from_raw_data::<k_quants::BlockQ5K>(raw_data, size_in_bytes, dims, device) } GgmlDType::Q6K => { from_raw_data::<k_quants::BlockQ6K>(raw_data, size_in_bytes, dims, device) } _ => crate::bail!("quantized type {ggml_dtype:?} is not supported yet"), } } fn read_one_tensor<R: std::io::Seek + std::io::Read>( reader: &mut R, magic: VersionedMagic, device: &Device, ) -> Result<(String, super::QTensor)> { let n_dims = reader.read_u32::<LittleEndian>()?; let name_len = reader.read_u32::<LittleEndian>()?; let ggml_dtype = reader.read_u32::<LittleEndian>()?; let ggml_dtype = GgmlDType::from_u32(ggml_dtype)?; let mut dims = vec![0u32; n_dims as usize]; reader.read_u32_into::<LittleEndian>(&mut dims)?; // The dimensions are stored in reverse order, see for example: // https://github.com/ggerganov/llama.cpp/blob/b5ffb2849d23afe73647f68eec7b68187af09be6/convert.py#L969 dims.reverse(); let mut name = vec![0u8; name_len as usize]; reader.read_exact(&mut name)?; let name = String::from_utf8_lossy(&name).into_owned(); if magic.align32() { let pos = reader.stream_position()?; reader.seek(std::io::SeekFrom::Current(((32 - pos % 32) % 32) as i64))?; } let dims = dims.iter().map(|&u| u as usize).collect::<Vec<_>>(); let tensor_elems = dims.iter().product::<usize>(); let size_in_bytes = tensor_elems * ggml_dtype.type_size() / ggml_dtype.block_size(); // TODO: Mmap version to avoid copying the data around? let mut raw_data = vec![0u8; size_in_bytes]; reader.read_exact(&mut raw_data)?; match qtensor_from_ggml(ggml_dtype, &raw_data, dims, device) { Ok(tensor) => Ok((name, tensor)), Err(e) => crate::bail!("Error creating tensor {name}: {e}"), } } pub struct Content { pub magic: VersionedMagic, pub hparams: HParams, pub vocab: Vocab, pub tensors: HashMap<String, super::QTensor>, pub device: Device, } impl Content { pub fn read<R: std::io::Seek + std::io::Read>( reader: &mut R, device: &Device, ) -> Result<Content> { // https://github.com/ggerganov/llama.cpp/blob/468ea24fb4633a0d681f7ac84089566c1c6190cb/llama.cpp#L505 let last_position = reader.seek(std::io::SeekFrom::End(0))?; reader.seek(std::io::SeekFrom::Start(0))?; let magic = VersionedMagic::read(reader)?; let hparams = HParams::read(reader)?; let vocab = Vocab::read(reader, hparams.n_vocab as usize)?; let mut tensors = HashMap::new(); while reader.stream_position()? != last_position { let (name, tensor) = read_one_tensor(reader, magic, device)?; tensors.insert(name, tensor); } let device = device.clone(); Ok(Self { magic, hparams, vocab, tensors, device, }) } pub fn remove(&mut self, name: &str) -> Result<super::QTensor> { match self.tensors.remove(name) { None => crate::bail!("cannot find tensor with name '{name}'"), Some(tensor) => Ok(tensor), } } }
candle/candle-core/src/quantized/ggml_file.rs/0
{ "file_path": "candle/candle-core/src/quantized/ggml_file.rs", "repo_id": "candle", "token_count": 4628 }
29
use crate::{shape::Dim, Context, Error, Result, Shape, Tensor}; impl Tensor { /// Concatenates two or more tensors along a particular dimension. /// /// All tensors must of the same rank, and the output will have /// the same rank /// /// ```rust /// # use candle_core::{Tensor, DType, Device}; /// let a = Tensor::zeros((2, 3), DType::F32, &Device::Cpu)?; /// let b = Tensor::zeros((2, 3), DType::F32, &Device::Cpu)?; /// /// let c = Tensor::cat(&[&a, &b], 0)?; /// assert_eq!(c.shape().dims(), &[4, 3]); /// /// let c = Tensor::cat(&[&a, &b], 1)?; /// assert_eq!(c.shape().dims(), &[2, 6]); /// # Ok::<(), candle_core::Error>(()) /// ``` pub fn cat<A: AsRef<Tensor>, D: Dim>(args: &[A], dim: D) -> Result<Self> { if args.is_empty() { Err(Error::OpRequiresAtLeastOneTensor { op: "cat" }.bt())? } let arg0 = args[0].as_ref(); if args.len() == 1 { return Ok(arg0.clone()); } let dim = dim.to_index(arg0.shape(), "cat")?; for arg in args { arg.as_ref().check_dim(dim, "cat")?; } for (arg_idx, arg) in args.iter().enumerate() { let arg = arg.as_ref(); if arg0.rank() != arg.rank() { Err(Error::UnexpectedNumberOfDims { expected: arg0.rank(), got: arg.rank(), shape: arg.shape().clone(), } .bt())? } for (dim_idx, (v1, v2)) in arg0 .shape() .dims() .iter() .zip(arg.shape().dims().iter()) .enumerate() { if dim_idx != dim && v1 != v2 { Err(Error::ShapeMismatchCat { dim: dim_idx, first_shape: arg0.shape().clone(), n: arg_idx + 1, nth_shape: arg.shape().clone(), } .bt())? } } } let all_contiguous = args.iter().all(|v| v.as_ref().is_contiguous()); if all_contiguous { Self::cat_contiguous(args, dim) } else if dim == 0 { Self::cat0(args) } else { let args: Vec<Tensor> = args .iter() .map(|a| a.as_ref().transpose(0, dim)) .collect::<Result<Vec<_>>>()?; let cat = Self::cat0(&args)?; cat.transpose(0, dim) } } fn cat0<A: AsRef<Tensor>>(args: &[A]) -> Result<Self> { if args.is_empty() { Err(Error::OpRequiresAtLeastOneTensor { op: "cat" }.bt())? } let arg0 = args[0].as_ref(); if args.len() == 1 { return Ok(arg0.clone()); } let rank = arg0.rank(); let device = arg0.device(); let dtype = arg0.dtype(); let first_dims = arg0.shape().dims(); let mut cat_dims = first_dims.to_vec(); cat_dims[0] = 0; let mut offsets = vec![0usize]; for (arg_idx, arg) in args.iter().enumerate() { let arg = arg.as_ref(); if arg.dtype() != dtype { Err(Error::DTypeMismatchBinaryOp { lhs: dtype, rhs: arg.dtype(), op: "cat", } .bt())? } if arg.device().location() != device.location() { Err(Error::DeviceMismatchBinaryOp { lhs: device.location(), rhs: arg.device().location(), op: "cat", } .bt())? } if rank != arg.rank() { Err(Error::UnexpectedNumberOfDims { expected: rank, got: arg.rank(), shape: arg.shape().clone(), } .bt())? } for (dim_idx, (v1, v2)) in arg0 .shape() .dims() .iter() .zip(arg.shape().dims().iter()) .enumerate() { if dim_idx == 0 { cat_dims[0] += v2; } if dim_idx != 0 && v1 != v2 { Err(Error::ShapeMismatchCat { dim: dim_idx, first_shape: arg0.shape().clone(), n: arg_idx + 1, nth_shape: arg.shape().clone(), } .bt())? } } let next_offset = offsets.last().context("empty offsets")? + arg.elem_count(); offsets.push(next_offset); } let shape = Shape::from(cat_dims); let op = crate::op::BackpropOp::new(args, |args| crate::op::Op::Cat(args, 0)); let mut storage = unsafe { device.alloc_uninit(&shape, dtype)? }; for (arg, &offset) in args.iter().zip(offsets.iter()) { let arg = arg.as_ref(); arg.storage() .copy_strided_src(&mut storage, offset, arg.layout())?; } Ok(crate::tensor::from_storage(storage, shape, op, false)) } fn cat_contiguous<A: AsRef<Tensor>>(args: &[A], dim: usize) -> Result<Self> { if args.is_empty() { Err(Error::OpRequiresAtLeastOneTensor { op: "cat" }.bt())? } let arg0 = args[0].as_ref(); if args.len() == 1 { return Ok(arg0.clone()); } let rank = arg0.rank(); let device = arg0.device(); let dtype = arg0.dtype(); let first_dims = arg0.shape().dims(); let mut cat_dims = first_dims.to_vec(); cat_dims[dim] = 0; for (arg_idx, arg) in args.iter().enumerate() { let arg = arg.as_ref(); if arg.dtype() != dtype { Err(Error::DTypeMismatchBinaryOp { lhs: dtype, rhs: arg.dtype(), op: "cat", } .bt())? } if arg.device().location() != device.location() { Err(Error::DeviceMismatchBinaryOp { lhs: device.location(), rhs: arg.device().location(), op: "cat", } .bt())? } if rank != arg.rank() { Err(Error::UnexpectedNumberOfDims { expected: rank, got: arg.rank(), shape: arg.shape().clone(), } .bt())? } for (dim_idx, (v1, v2)) in arg0 .shape() .dims() .iter() .zip(arg.shape().dims().iter()) .enumerate() { if dim_idx == dim { cat_dims[dim] += v2; } if dim_idx != dim && v1 != v2 { Err(Error::ShapeMismatchCat { dim: dim_idx, first_shape: arg0.shape().clone(), n: arg_idx + 1, nth_shape: arg.shape().clone(), } .bt())? } } } let cat_target_dim_len = cat_dims[dim]; let block_size: usize = cat_dims.iter().skip(1 + dim).product(); let shape = Shape::from(cat_dims); let op = crate::op::BackpropOp::new(args, |args| crate::op::Op::Cat(args, dim)); let mut storage = unsafe { device.alloc_uninit(&shape, dtype)? }; let mut dst_o = 0; for arg in args.iter() { let arg = arg.as_ref(); let arg_dims = arg.shape().dims(); let d1: usize = arg_dims.iter().take(dim).product(); let d2 = block_size * arg_dims[dim]; let dst_s = block_size * cat_target_dim_len; let src_o = arg.layout().start_offset(); arg.storage().copy2d( &mut storage, d1, d2, /* src_s */ d2, dst_s, src_o, dst_o, )?; dst_o += d2; } Ok(crate::tensor::from_storage(storage, shape, op, false)) } /// Set the values on `self` using values from `src`. The copy starts at the specified /// `offset` for the target dimension `dim` on `self`. /// `self` and `src` must have the same shape except on dimension `dim` where the `self` size /// has to be greater than or equal to `offset` plus the `src` size. /// /// Note that this modifies `self` in place and as such is not compatible with /// back-propagation. pub fn slice_set<D: Dim>(&self, src: &Self, dim: D, offset: usize) -> Result<()> { let dim = dim.to_index(self.shape(), "slice-set")?; if !self.is_contiguous() || !src.is_contiguous() { Err(Error::RequiresContiguous { op: "slice-set" }.bt())? } if self.same_storage(src) { crate::bail!("cannot use slice_set when self and src share their storage") } if self.dtype() != src.dtype() { Err(Error::DTypeMismatchBinaryOp { lhs: self.dtype(), rhs: src.dtype(), op: "slice-set", } .bt())? } if self.device().location() != src.device().location() { Err(Error::DeviceMismatchBinaryOp { lhs: self.device().location(), rhs: src.device().location(), op: "slice-set", } .bt())? } if self.rank() != src.rank() { Err(Error::UnexpectedNumberOfDims { expected: self.rank(), got: src.rank(), shape: self.shape().clone(), } .bt())? } for (dim_idx, (v1, v2)) in self.dims().iter().zip(src.dims().iter()).enumerate() { if dim_idx == dim && *v2 + offset > *v1 { crate::bail!("shape mismatch on target dim, dst: {v1}, src: {v2} + {offset}") } if dim_idx != dim && v1 != v2 { crate::bail!("shape mismatch on dim {dim_idx}, {v1} <> {v2}") } } let block_size: usize = src.dims().iter().skip(1 + dim).product(); let d1: usize = src.dims().iter().take(dim).product(); let d2 = block_size * src.dims()[dim]; let dst_o = self.layout().start_offset() + offset * block_size; let src_o = src.layout().start_offset(); src.storage().copy2d( &mut self.storage_mut(), d1, d2, /* src_s */ d2, /* dst_s */ block_size * self.dims()[dim], src_o, dst_o, )?; Ok(()) } }
candle/candle-core/src/tensor_cat.rs/0
{ "file_path": "candle/candle-core/src/tensor_cat.rs", "repo_id": "candle", "token_count": 6379 }
30
use candle_core::{ bail, quantized::{self, GgmlDType}, test_device, test_utils::to_vec2_round, DType, Device, IndexOp, Module, Result, Tensor, }; use quantized::{k_quants, GgmlType}; use rand::prelude::*; const GGML_TEST_SIZE: usize = 32 * 128; const GGML_MAX_QUANTIZATION_TOTAL_ERROR: f32 = 0.002; const GGML_MAX_QUANTIZATION_TOTAL_ERROR_2BITS: f32 = 0.0075; const GGML_MAX_QUANTIZATION_TOTAL_ERROR_3BITS: f32 = 0.0040; const GGML_MAX_DOT_PRODUCT_ERROR: f32 = 0.02; fn test_matmul( device: &Device, (b, m, n, k): (usize, usize, usize, usize), dtype: GgmlDType, ) -> Result<()> { let lhs = (0..(m * k)) .map(|v| v as f32 / (m * k) as f32) .collect::<Vec<_>>(); let rhs = (0..(k * n)) .map(|v| v as f32 / (n * k) as f32) .collect::<Vec<_>>(); let lhs = Tensor::from_slice(&lhs, (m, k), device)?; let rhs = Tensor::from_slice(&rhs, (k, n), device)?; let mm = lhs.matmul(&rhs)?; let qtensor = quantized::QTensor::quantize(&rhs.t()?, dtype)?; let matmul = quantized::QMatMul::from_qtensor(qtensor)?; let res = matmul.forward(&lhs)?; let error: f32 = ((&mm - &res)?.abs()? / &mm.abs()?)? .sum_all()? .to_scalar()?; let error = error / (b * m * n) as f32; assert!( error <= 0.02, "Error {error} is too big. \nExpected:\n {mm} \nFound:\n {res}\n for {dtype:?}" ); Ok(()) } #[cfg(feature = "metal")] #[test] fn test_matmul_mm() -> Result<()> { let dtype = GgmlDType::Q8_0; let device = Device::new_metal(0)?; let m = 32; let n = 32; let k = 32; let lhs = (0..(m * k)) .map(|v| v as f32 / (m * k) as f32) .collect::<Vec<_>>(); let rhs = (0..(k * n)) .map(|v| v as f32 / (n * k) as f32) .collect::<Vec<_>>(); let lhs = Tensor::from_slice(&lhs, (m, k), &device)?; let rhs = Tensor::from_slice(&rhs, (1, 1, k, n), &device)?.repeat((5, 20, 1, 1))?; let mm = lhs.broadcast_matmul(&rhs)?; let qtensor = quantized::QTensor::quantize(&lhs.t()?, dtype)?; let matmul = quantized::QMatMul::from_qtensor(qtensor)?; let res = matmul.forward(&rhs)?; let error: f32 = ((&mm - &res)?.abs()? / &mm.abs()?)? .sum_all()? .to_scalar()?; let error = error / res.elem_count() as f32; assert!( error <= 0.001, "Error {error} is too big. \nExpected:\n {mm} \nFound:\n {res}\n for {dtype:?}" ); Ok(()) } fn quantized_matmul(device: &Device) -> Result<()> { let (m, k, n) = (3, 64, 4); let lhs_s = (0..(m * k)).map(|v| v as f32).collect::<Vec<_>>(); let lhs = Tensor::from_slice(&lhs_s, (m, k), device)?; let mut dst = vec![42.; 3 * 4]; let mut rhs_t = vec![k_quants::BlockQ4_0::zeros(); 8]; let rhs = (0..(k * n)).map(|v| v as f32).collect::<Vec<_>>(); k_quants::BlockQ4_0::from_float(&rhs, &mut rhs_t)?; k_quants::matmul((m, k, n), &lhs_s, &rhs_t, &mut dst)?; assert_eq!( dst.iter().map(|x| x.round()).collect::<Vec<_>>(), &[ 85120.0, 214562.0, 345455.0, 474748.0, 213475.0, 604465.0, 1000686.0, 1388317.0, 341876.0, 994283.0, 1655709.0, 2301518.0 ] ); let tensor_rhs = Tensor::from_slice(&rhs, (n, k), device)?.t()?; let mm = lhs.matmul(&tensor_rhs)?; assert_eq!( mm.to_vec2::<f32>()?, &[ [85344.0, 214368.0, 343392.0, 472416.0], [214368.0, 605536.0, 996704.0, 1387872.0], [343392.0, 996704.0, 1650016.0, 2303328.0] ] ); let qtensor = quantized::QTensor::quantize(&tensor_rhs.t()?, GgmlDType::Q4_0)?; let matmul = quantized::QMatMul::from_qtensor(qtensor)?; let res = matmul.forward(&lhs)?; match device { Device::Metal(_) => assert_eq!( to_vec2_round(&res, 0)?, &[ [84946.0, 214126.0, 344757.0, 473798.0], [213458.0, 604350.0, 1000469.0, 1387990.0], [341970.0, 994574.0, 1656181.0, 2302182.0] ] ), Device::Cuda(_) => assert_eq!( to_vec2_round(&res, 0)?, &[ [84866.0, 214045.0, 344676.0, 473707.0], [213425.0, 604313.0, 1000431.0, 1387960.0], [342030.0, 994630.0, 1656248.0, 2302250.0] ] ), Device::Cpu => assert_eq!( to_vec2_round(&res, 0)?, &[ [85120.0, 214562.0, 345455.0, 474748.0], [213475.0, 604465.0, 1000686.0, 1388317.0], [341876.0, 994283.0, 1655709.0, 2301518.0] ] ), } test_matmul(device, (1, 3, 4, 256), GgmlDType::Q4_0)?; Ok(()) } fn quantized_matmul_neg(device: &Device) -> Result<()> { let (m, k, n) = (3, 64, 4); let lhs_s = (0..(m * k)) .map(|v| v as f32 - (m * k) as f32 / 2.0) .collect::<Vec<_>>(); let lhs = Tensor::from_slice(&lhs_s, (m, k), device)?; let mut dst = vec![42.; 3 * 4]; let mut rhs_t = vec![k_quants::BlockQ4_0::zeros(); 8]; let rhs = (0..k * n) .map(|v| v as f32 - (k * n) as f32 / 3.0) .collect::<Vec<_>>(); let tensor_rhs = Tensor::from_slice(&rhs, (n, k), device)?.t()?; k_quants::BlockQ4_0::from_float(&rhs, &mut rhs_t)?; k_quants::matmul((m, k, n), &lhs_s, &rhs_t, &mut dst)?; assert_eq!( dst.iter().map(|x| x.round()).collect::<Vec<_>>(), &[ 243524.0, -19596.0, -285051.0, -549815.0, 23777.0, 21651.0, 19398.0, 18367.0, -196472.0, 63012.0, 324585.0, 587902.0 ] ); let mm = lhs.matmul(&tensor_rhs)?; assert_eq!( to_vec2_round(&mm, 0)?, &[ [244064.0, -20128.0, -284320.0, -548512.0], [23563.0, 21515.0, 19467.0, 17419.0], [-196939.0, 63157.0, 323253.0, 583349.0] ] ); let qtensor = quantized::QTensor::quantize(&tensor_rhs.t()?, GgmlDType::Q4_0)?; let matmul = quantized::QMatMul::from_qtensor(qtensor)?; let res = matmul.forward(&lhs)?; match device { Device::Metal(_) => assert_eq!( to_vec2_round(&res, 0)?, &[ [243659.0, -19716.0, -285444.0, -550439.0], [23779.0, 21653.0, 19404.0, 18349.0], [-196101.0, 63021.0, 324252.0, 587137.0] ] ), Device::Cuda(_) => assert_eq!( to_vec2_round(&res, 0)?, &[ [243740.0, -19762.0, -285476.0, -550498.0], [23774.0, 21645.0, 19395.0, 18364.0], [-196045.0, 63030.0, 324120.0, 587079.0] ] ), Device::Cpu => assert_eq!( to_vec2_round(&res, 0)?, &[ [243524.0, -19596.0, -285051.0, -549815.0], [23777.0, 21651.0, 19398.0, 18367.0], [-196472.0, 63012.0, 324585.0, 587902.0] ] ), } let lhs2 = Tensor::stack(&[&lhs, &lhs], 0)?; let res2 = matmul.forward(&lhs2)?; let res2 = res2.i(1)?; let diff = (&res - res2)?.abs()?.mean_all()?.to_vec0::<f32>()? / res.elem_count() as f32; if device.is_cuda() { assert!(diff < 0.1); } else { assert!(diff < 0.96); } Ok(()) } fn qmm_batch(dev: &Device) -> Result<()> { let (lhs, rhs, _mm) = get_random_tensors(2, 256, 6, dev)?; let rhs = quantized::QTensor::quantize(&rhs, GgmlDType::Q2K)?; let rhs = quantized::QMatMul::from_qtensor(rhs)?; let mm = rhs.forward(&lhs)?; assert_eq!(mm.shape().dims(), [2, 6]); let lhs2 = Tensor::cat(&[&lhs, &lhs], 0)?; let mm2 = rhs.forward(&lhs2)?; assert_eq!(mm2.shape().dims(), [4, 6]); let diff2 = (mm2.i(2..)? - &mm)?.abs()?.sum_all()?.to_vec0::<f32>()?; assert_eq!(diff2, 0.0); let lhs3 = Tensor::cat(&[&lhs2, &lhs], 0)?; let mm3 = rhs.forward(&lhs3)?; assert_eq!(mm3.shape().dims(), [6, 6]); let diff3 = (mm3.i(2..4)? - &mm)?.abs()?.sum_all()?.to_vec0::<f32>()?; assert_eq!(diff3, 0.0); let diff3 = (mm3.i(4..)? - &mm)?.abs()?.sum_all()?.to_vec0::<f32>()?; assert_eq!(diff3, 0.0); let lhs4 = Tensor::cat(&[&lhs3, &lhs3], 0)?; let mm4 = rhs.forward(&lhs4)?; assert_eq!(mm4.shape().dims(), [12, 6]); let diff4 = (mm4.i(..6)? - &mm3)?.abs()?.sum_all()?.to_vec0::<f32>()?; if dev.is_cuda() { // We use a different kernel for sizes from 1 to 8 on cuda which explains // the difference here. assert!(0. < diff4 && diff4 < 1e-4) } else { assert_eq!(diff4, 0.0) }; let diff4 = (mm4.i(6..)? - &mm4.i(..6)?)? .abs()? .sum_all()? .to_vec0::<f32>()?; assert_eq!(diff4, 0.0); Ok(()) } test_device!(quantized_matmul, qmm_cpu, qmm_cuda, qmm_metal); test_device!(quantized_matmul_neg, qmm_n_cpu, qmm_n_cuda, qmm_n_metal); test_device!(qmm_batch, qmm_b_cpu, qmm_b_cuda, qmm_b_metal); fn quantize_q4_0(device: &Device) -> Result<()> { let src = (0..32 * 4).map(|v| v as f32).collect::<Vec<_>>(); let src = Tensor::from_slice(&src, (32 * 4,), device)?; let quant = quantized::QTensor::quantize(&src, GgmlDType::Q4_0)?; let dst = quant.dequantize(device)?; let dst_f16 = quant.dequantize_f16(device)?; let diff = (dst.to_dtype(DType::F16)? - dst_f16)? .to_dtype(DType::F32)? .abs()? .sum_all()? .to_vec0::<f32>()?; assert_eq!(diff, 0.); assert_eq!( dst.to_vec1::<f32>()?, &[ -0.0, -0.0, 3.875, 3.875, 3.875, 3.875, 7.75, 7.75, 7.75, 7.75, 11.625, 11.625, 11.625, 11.625, 15.5, 15.5, 15.5, 15.5, 19.375, 19.375, 19.375, 19.375, 23.25, 23.25, 23.25, 23.25, 27.125, 27.125, 27.125, 27.125, 31.0, 31.0, 31.5, 31.5, 31.5, 31.5, 39.375, 39.375, 39.375, 39.375, 39.375, 39.375, 39.375, 39.375, 47.25, 47.25, 47.25, 47.25, 47.25, 47.25, 47.25, 47.25, 55.125, 55.125, 55.125, 55.125, 55.125, 55.125, 55.125, 55.125, 63.0, 63.0, 63.0, 63.0, 59.375, 59.375, 71.25, 71.25, 71.25, 71.25, 71.25, 71.25, 71.25, 71.25, 71.25, 71.25, 71.25, 71.25, 83.125, 83.125, 83.125, 83.125, 83.125, 83.125, 83.125, 83.125, 83.125, 83.125, 83.125, 83.125, 95.0, 95.0, 95.0, 95.0, 95.0, 95.0, 95.25, 95.25, 95.25, 95.25, 95.25, 95.25, 95.25, 95.25, 111.125, 111.125, 111.125, 111.125, 111.125, 111.125, 111.125, 111.125, 111.125, 111.125, 111.125, 111.125, 111.125, 111.125, 111.125, 111.125, 127.0, 127.0, 127.0, 127.0, 127.0, 127.0, 127.0, 127.0 ] ); ggml_quantization_error_test(GgmlDType::Q4_0, device, GGML_MAX_QUANTIZATION_TOTAL_ERROR)?; Ok(()) } fn quantize_q4_1(device: &Device) -> Result<()> { let src = (0..32 * 4).map(|v| v as f32).collect::<Vec<_>>(); let src = Tensor::from_slice(&src, (32 * 4,), device)?; let quant = quantized::QTensor::quantize(&src, GgmlDType::Q4_1)?; let dst = quant.dequantize(device)?; let dst_f16 = quant.dequantize_f16(device)?; let diff = (dst.to_dtype(DType::F16)? - dst_f16)? .to_dtype(DType::F32)? .abs()? .sum_all()? .to_vec0::<f32>()?; assert_eq!(diff, 0.); assert_eq!( round_vector(&dst.to_vec1::<f32>()?), &[ 0.0, 0.0, 2.066, 2.066, 4.133, 4.133, 6.199, 6.199, 8.266, 8.266, 10.332, 10.332, 12.398, 12.398, 14.465, 14.465, 16.531, 16.531, 18.598, 18.598, 20.664, 20.664, 22.73, 22.73, 24.797, 24.797, 26.863, 26.863, 28.93, 28.93, 30.996, 30.996, 32.0, 32.0, 34.066, 34.066, 36.133, 36.133, 38.199, 38.199, 40.266, 40.266, 42.332, 42.332, 44.398, 44.398, 46.465, 46.465, 48.531, 48.531, 50.598, 50.598, 52.664, 52.664, 54.73, 54.73, 56.797, 56.797, 58.863, 58.863, 60.93, 60.93, 62.996, 62.996, 64.0, 64.0, 66.066, 66.066, 68.133, 68.133, 70.199, 70.199, 72.266, 72.266, 74.332, 74.332, 76.398, 76.398, 78.465, 78.465, 80.531, 80.531, 82.598, 82.598, 84.664, 84.664, 86.73, 86.73, 88.797, 88.797, 90.863, 90.863, 92.93, 92.93, 94.996, 94.996, 96.0, 96.0, 98.066, 98.066, 100.133, 100.133, 102.199, 102.199, 104.266, 104.266, 106.332, 106.332, 108.398, 108.398, 110.465, 110.465, 112.531, 112.531, 114.598, 114.598, 116.664, 116.664, 118.73, 118.73, 120.797, 120.797, 122.863, 122.863, 124.93, 124.93, 126.996, 126.996 ] ); ggml_quantization_error_test(GgmlDType::Q4_1, device, GGML_MAX_QUANTIZATION_TOTAL_ERROR)?; Ok(()) } fn quantize_q5_0(device: &Device) -> Result<()> { let src = (0..32 * 4).map(|v| v as f32).collect::<Vec<_>>(); let src = Tensor::from_slice(&src, (32 * 4,), device)?; let quant = quantized::QTensor::quantize(&src, GgmlDType::Q5_0)?; let dst = quant.dequantize(device)?; let dst_f16 = quant.dequantize_f16(device)?; let diff = (dst.to_dtype(DType::F16)? - dst_f16)? .to_dtype(DType::F32)? .abs()? .sum_all()? .to_vec0::<f32>()?; assert_eq!(diff, 0.); assert_eq!( round_vector(&dst.to_vec1::<f32>()?), &[ -0.0, 1.938, 1.938, 3.875, 3.875, 5.813, 5.813, 7.75, 7.75, 9.688, 9.688, 11.625, 11.625, 13.563, 13.563, 15.5, 15.5, 17.438, 17.438, 19.375, 19.375, 21.313, 21.313, 23.25, 23.25, 25.188, 25.188, 27.125, 27.125, 29.063, 29.063, 31.0, 31.5, 31.5, 35.438, 35.438, 35.438, 35.438, 39.375, 39.375, 39.375, 39.375, 43.313, 43.313, 43.313, 43.313, 47.25, 47.25, 47.25, 47.25, 51.188, 51.188, 51.188, 51.188, 55.125, 55.125, 55.125, 55.125, 59.063, 59.063, 59.063, 59.063, 63.0, 63.0, 65.313, 65.313, 65.313, 65.313, 65.313, 71.25, 71.25, 71.25, 71.25, 71.25, 71.25, 77.188, 77.188, 77.188, 77.188, 77.188, 77.188, 83.125, 83.125, 83.125, 83.125, 83.125, 83.125, 89.063, 89.063, 89.063, 89.063, 89.063, 89.063, 95.0, 95.0, 95.0, 95.25, 95.25, 95.25, 95.25, 103.188, 103.188, 103.188, 103.188, 103.188, 103.188, 103.188, 103.188, 111.125, 111.125, 111.125, 111.125, 111.125, 111.125, 111.125, 111.125, 119.063, 119.063, 119.063, 119.063, 119.063, 119.063, 119.063, 119.063, 127.0, 127.0, 127.0, 127.0 ] ); ggml_quantization_error_test(GgmlDType::Q5_0, device, GGML_MAX_QUANTIZATION_TOTAL_ERROR)?; Ok(()) } fn quantize_q5_1(device: &Device) -> Result<()> { let src = (0..32 * 4).map(|v| v as f32).collect::<Vec<_>>(); let src = Tensor::from_slice(&src, (32 * 4,), device)?; let quant = quantized::QTensor::quantize(&src, GgmlDType::Q5_1)?; let dst = quant.dequantize(device)?; let dst_f16 = quant.dequantize_f16(device)?; let diff = (dst.to_dtype(DType::F16)? - dst_f16)? .to_dtype(DType::F32)? .abs()? .sum_all()? .to_vec0::<f32>()?; assert_eq!(diff, 0.); assert_eq!( round_vector(&dst.to_vec1::<f32>()?), &[ 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 30.0, 31.0, 32.0, 33.0, 34.0, 35.0, 36.0, 37.0, 38.0, 39.0, 40.0, 41.0, 42.0, 43.0, 44.0, 45.0, 46.0, 47.0, 48.0, 49.0, 50.0, 51.0, 52.0, 53.0, 54.0, 55.0, 56.0, 57.0, 58.0, 59.0, 60.0, 61.0, 62.0, 63.0, 64.0, 65.0, 66.0, 67.0, 68.0, 69.0, 70.0, 71.0, 72.0, 73.0, 74.0, 75.0, 76.0, 77.0, 78.0, 79.0, 80.0, 81.0, 82.0, 83.0, 84.0, 85.0, 86.0, 87.0, 88.0, 89.0, 90.0, 91.0, 92.0, 93.0, 94.0, 95.0, 96.0, 97.0, 98.0, 99.0, 100.0, 101.0, 102.0, 103.0, 104.0, 105.0, 106.0, 107.0, 108.0, 109.0, 110.0, 111.0, 112.0, 113.0, 114.0, 115.0, 116.0, 117.0, 118.0, 119.0, 120.0, 121.0, 122.0, 123.0, 124.0, 125.0, 126.0, 127.0 ] ); ggml_quantization_error_test(GgmlDType::Q5_1, device, GGML_MAX_QUANTIZATION_TOTAL_ERROR)?; Ok(()) } fn get_test_vector2(bound: f32, size: usize, device: &Device) -> Result<Tensor> { assert!( size % crate::quantized::k_quants::QK_K == 0, "size must be a multiple of {}", crate::quantized::k_quants::QK_K ); let src = (0..size) .map(|v| (v as f32 - size as f32 / 2.) * bound / (size as f32 / 2.)) .collect::<Vec<_>>(); assert_eq!([src[0], src[size / 2]], [-bound, 0.0]); Tensor::from_vec(src, (size,), device) } /// Round a vector fn round_vector(values: &[f32]) -> Vec<f32> { values .iter() .map(|x| (1000. * x).round() / 1000.) .collect::<Vec<_>>() } fn compare_with_error(values: &[f32], expected: &[f32], tolerance: f32) { for (i, (value, expected_value)) in values.iter().zip(expected.iter()).enumerate() { let difference = (value - expected_value).abs(); assert!( difference < tolerance, "Error at index {i}: value = {value}, expected = {expected_value}. Difference = {difference} exceeds tolerance = {tolerance}." ); } } /// Creates a vector similar to the ones used in GGML unit tests: /// https://github.com/ggerganov/llama.cpp/blob/master/tests/test-quantize-fns.cpp#L26-L30 fn create_ggml_like_vector(offset: f32) -> Vec<f32> { (0..GGML_TEST_SIZE) .map(|i| 0.1 + 2.0 * (i as f32 + offset).cos()) .collect() } /// Calculates the root mean square error between two vectors fn calculate_rmse(a: &[f32], b: &[f32]) -> f32 { assert_eq!(a.len(), b.len()); let sum = a .iter() .zip(b) .map(|(a, b)| (a - b).powi(2)) .sum::<f32>() .sqrt(); sum / a.len() as f32 } /// Similar to the GGML quantization unit test: /// https://github.com/ggerganov/llama.cpp/blob/master/tests/test-quantize-fns.cpp#L43-L50 fn ggml_quantization_error_test(dtype: GgmlDType, device: &Device, max_error: f32) -> Result<()> { let src = create_ggml_like_vector(0.0); let src = Tensor::from_slice(&src, (GGML_TEST_SIZE,), device)?; let quant = quantized::QTensor::quantize(&src, dtype)?; let dst = quant.dequantize(device)?; let dst_f16 = quant.dequantize_f16(device)?; let diff = (dst.to_dtype(DType::F16)? - dst_f16)? .to_dtype(DType::F32)? .abs()? .sum_all()? .to_vec0::<f32>()?; assert_eq!(diff, 0.); let error = calculate_rmse(&src.to_vec1::<f32>()?, &dst.to_vec1::<f32>()?); if error > max_error { bail!( "Quantization error {} exceeds max error {}", error, max_error ); } Ok(()) } fn quantize_q2k(device: &Device) -> Result<()> { let dtype = GgmlDType::Q2K; let src = get_test_vector2(0.5, 1024, device)?; let quant = quantized::QTensor::quantize(&src, dtype)?; let dst = quant.dequantize(device)?; let dst_f16 = quant.dequantize_f16(device)?; let diff = (dst.to_dtype(DType::F16)? - dst_f16)? .to_dtype(DType::F32)? .abs()? .sum_all()? .to_vec0::<f32>()?; assert_eq!(diff, 0.); let src = src.to_vec1::<f32>()?; let dst = dst.to_vec1::<f32>()?; compare_with_error(dst.as_slice(), src.as_slice(), 0.1); // Test some specific values assert_eq!( [src[0], src[128], src[256], src[512], src[800], src[1023]], [-0.5, -0.375, -0.25, 0.0, 0.28125, 0.49902344] ); let dst = round_vector(&dst); assert_eq!( [dst[0], dst[128], dst[256], dst[512], dst[800], dst[1023]], [-0.499, -0.366, -0.249, 0.0, 0.295, 0.492] ); let src_big = get_test_vector2(128.0, 1024, device)?; let quant_big = quantized::QTensor::quantize(&src_big, dtype)?; let dst_big = quant_big.dequantize(device)?; let dst_big_f16 = quant_big.dequantize_f16(device)?; let diff = (dst_big.to_dtype(DType::F16)? - dst_big_f16)? .to_dtype(DType::F32)? .abs()? .sum_all()? .to_vec0::<f32>()?; assert_eq!(diff, 0.); let src_big = src_big.to_vec1::<f32>()?; let dst_big = dst_big.to_vec1::<f32>()?; compare_with_error(dst_big.as_slice(), src_big.as_slice(), 6.0); ggml_quantization_error_test(dtype, device, GGML_MAX_QUANTIZATION_TOTAL_ERROR_2BITS)?; Ok(()) } fn quantize_q3k(device: &Device) -> Result<()> { let dtype = GgmlDType::Q3K; let src = get_test_vector2(0.5, 1024, device)?; let quant = quantized::QTensor::quantize(&src, dtype)?; let dst = quant.dequantize(device)?; let dst_f16 = quant.dequantize_f16(device)?; let diff = (dst.to_dtype(DType::F16)? - dst_f16)? .to_dtype(DType::F32)? .abs()? .sum_all()? .to_vec0::<f32>()?; assert_eq!(diff, 0.); let src = src.to_vec1::<f32>()?; let dst = dst.to_vec1::<f32>()?; compare_with_error(dst.as_slice(), src.as_slice(), 0.03); // Test some specific values assert_eq!( [src[0], src[128], src[256], src[512], src[800], src[1023]], [-0.5, -0.375, -0.25, 0.0, 0.28125, 0.49902344] ); let dst = round_vector(&dst); assert_eq!( [dst[0], dst[128], dst[256], dst[512], dst[800], dst[1023]], [-0.493, -0.37, -0.243, -0.0, 0.292, 0.492] ); let src_big = get_test_vector2(128.0, 1024, device)?; let quant_big = quantized::QTensor::quantize(&src_big, dtype)?; let dst_big = quant_big.dequantize(device)?; let dst_big_f16 = quant_big.dequantize_f16(device)?; let diff = (dst_big.to_dtype(DType::F16)? - dst_big_f16)? .to_dtype(DType::F32)? .abs()? .sum_all()? .to_vec0::<f32>()?; assert_eq!(diff, 0.); let src_big = src_big.to_vec1::<f32>()?; let dst_big = dst_big.to_vec1::<f32>()?; compare_with_error(dst_big.as_slice(), src_big.as_slice(), 3.5); ggml_quantization_error_test(dtype, device, GGML_MAX_QUANTIZATION_TOTAL_ERROR_3BITS)?; Ok(()) } fn quantize_q4k(device: &Device) -> Result<()> { let dtype = GgmlDType::Q4K; let src = get_test_vector2(0.5, 1024, device)?; let quant = quantized::QTensor::quantize(&src, dtype)?; let dst = quant.dequantize(device)?; let dst_f16 = quant.dequantize_f16(device)?; let diff = (dst.to_dtype(DType::F16)? - dst_f16)? .to_dtype(DType::F32)? .abs()? .sum_all()? .to_vec0::<f32>()?; assert_eq!(diff, 0.); let src = src.to_vec1::<f32>()?; let dst = dst.to_vec1::<f32>()?; compare_with_error(dst.as_slice(), src.as_slice(), 0.017); // Test some specific values assert_eq!( [src[0], src[128], src[256], src[512], src[800], src[1023]], [-0.5, -0.375, -0.25, 0.0, 0.28125, 0.49902344] ); let dst = round_vector(&dst); assert_eq!( [dst[0], dst[128], dst[256], dst[512], dst[800], dst[1023]], [-0.5, -0.373, -0.25, 0.0, 0.288, 0.498] ); let src_big = get_test_vector2(128.0, 1024, device)?; let quant_big = quantized::QTensor::quantize(&src_big, dtype)?; let dst_big = quant_big.dequantize(device)?; let dst_big_f16 = quant_big.dequantize_f16(device)?; let diff = (dst_big.to_dtype(DType::F16)? - dst_big_f16)? .to_dtype(DType::F32)? .abs()? .sum_all()? .to_vec0::<f32>()?; assert_eq!(diff, 0.); let src_big = src_big.to_vec1::<f32>()?; let dst_big = dst_big.to_vec1::<f32>()?; compare_with_error(dst_big.as_slice(), src_big.as_slice(), 4.5); ggml_quantization_error_test(dtype, device, GGML_MAX_QUANTIZATION_TOTAL_ERROR)?; Ok(()) } fn quantize_q5k(device: &Device) -> Result<()> { let dtype = GgmlDType::Q5K; let src = get_test_vector2(0.5, 1024, device)?; let quant = quantized::QTensor::quantize(&src, dtype)?; let dst = quant.dequantize(device)?; let dst_f16 = quant.dequantize_f16(device)?; let diff = (dst.to_dtype(DType::F16)? - dst_f16)? .to_dtype(DType::F32)? .abs()? .sum_all()? .to_vec0::<f32>()?; assert_eq!(diff, 0.); let src = src.to_vec1::<f32>()?; let dst = dst.to_vec1::<f32>()?; compare_with_error(dst.as_slice(), src.as_slice(), 0.009); // Test some specific values assert_eq!( [src[0], src[128], src[256], src[512], src[800], src[1023]], [-0.5, -0.375, -0.25, 0.0, 0.28125, 0.49902344] ); let dst = round_vector(&dst); assert_eq!( [dst[0], dst[128], dst[256], dst[512], dst[800], dst[1023]], [-0.5, -0.373, -0.25, 0.0, 0.279, 0.499] ); let src_big = get_test_vector2(128.0, 1024, device)?; let quant_big = quantized::QTensor::quantize(&src_big, dtype)?; let dst_big = quant_big.dequantize(device)?; let dst_big_f16 = quant_big.dequantize_f16(device)?; let diff = (dst_big.to_dtype(DType::F16)? - dst_big_f16)? .to_dtype(DType::F32)? .abs()? .sum_all()? .to_vec0::<f32>()?; assert_eq!(diff, 0.); let src_big = src_big.to_vec1::<f32>()?; let dst_big = dst_big.to_vec1::<f32>()?; compare_with_error(dst_big.as_slice(), src_big.as_slice(), 2.5); ggml_quantization_error_test(dtype, device, GGML_MAX_QUANTIZATION_TOTAL_ERROR)?; Ok(()) } fn quantize_q6k(device: &Device) -> Result<()> { let dtype = GgmlDType::Q6K; let src = get_test_vector2(0.5, 1024, device)?; let quant = quantized::QTensor::quantize(&src, dtype)?; let dst = quant.dequantize(device)?; let dst_f16 = quant.dequantize_f16(device)?; let diff = (dst.to_dtype(DType::F16)? - dst_f16)? .to_dtype(DType::F32)? .abs()? .sum_all()? .to_vec0::<f32>()?; assert_eq!(diff, 0.); let src = src.to_vec1::<f32>()?; let dst = dst.to_vec1::<f32>()?; compare_with_error(dst.as_slice(), src.as_slice(), 0.008); // Test some specific values assert_eq!( [src[0], src[128], src[256], src[512], src[800], src[1023]], [-0.5, -0.375, -0.25, 0.0, 0.28125, 0.49902344] ); let dst = round_vector(&dst); assert_eq!( [dst[0], dst[128], dst[256], dst[512], dst[800], dst[1023]], [-0.497, -0.372, -0.25, -0.0, 0.284, 0.5] ); let src_big = get_test_vector2(128.0, 1024, device)?; let quant_big = quantized::QTensor::quantize(&src_big, dtype)?; let dst_big = quant_big.dequantize(device)?; let dst_big_f16 = quant_big.dequantize_f16(device)?; let diff = (dst_big.to_dtype(DType::F16)? - dst_big_f16)? .to_dtype(DType::F32)? .abs()? .sum_all()? .to_vec0::<f32>()?; assert_eq!(diff, 0.); let src_big = src_big.to_vec1::<f32>()?; let dst_big = dst_big.to_vec1::<f32>()?; compare_with_error(dst_big.as_slice(), src_big.as_slice(), 2.0); ggml_quantization_error_test(dtype, device, GGML_MAX_QUANTIZATION_TOTAL_ERROR)?; Ok(()) } fn quantize_q8k(device: &Device) -> Result<()> { let dtype = GgmlDType::Q8K; let src = get_test_vector2(0.5, 1024, device)?; let quant = quantized::QTensor::quantize(&src, dtype)?; let dst = quant.dequantize(device)?; let dst_f16 = quant.dequantize_f16(device)?; let diff = (dst.to_dtype(DType::F16)? - dst_f16)? .to_dtype(DType::F32)? .abs()? .sum_all()? .to_vec0::<f32>()?; assert_eq!(diff, 0.); let src = src.to_vec1::<f32>()?; let dst = dst.to_vec1::<f32>()?; compare_with_error(dst.as_slice(), src.as_slice(), 0.008); // Test some specific values assert_eq!( [src[0], src[128], src[256], src[512], src[800], src[1023]], [-0.5, -0.375, -0.25, 0.0, 0.28125, 0.49902344] ); let dst = round_vector(&dst); assert_eq!( [dst[0], dst[128], dst[256], dst[512], dst[800], dst[1023]], [-0.5, -0.375, -0.25, -0.0, 0.281, 0.499] ); let src_big = get_test_vector2(128.0, 1024, device)?; let quant_big = quantized::QTensor::quantize(&src_big, dtype)?; let dst_big = quant_big.dequantize(device)?; let dst_big_f16 = quant_big.dequantize_f16(device)?; let diff = (dst_big.to_dtype(DType::F16)? - dst_big_f16)? .to_dtype(DType::F32)? .abs()? .sum_all()? .to_vec0::<f32>()?; assert_eq!(diff, 0.); let src_big = src_big.to_vec1::<f32>()?; let dst_big = dst_big.to_vec1::<f32>()?; compare_with_error(dst_big.as_slice(), src_big.as_slice(), 0.6); ggml_quantization_error_test(dtype, device, GGML_MAX_QUANTIZATION_TOTAL_ERROR)?; Ok(()) } test_device!( quantize_q4_0, quantize_q4_0_cpu, quantize_q4_0_cuda, quantize_q4_0_metal ); test_device!( quantize_q4_1, quantize_q4_1_cpu, quantize_q4_1_cuda, quantize_q4_1_metal ); test_device!( quantize_q5_0, quantize_q5_0_cpu, quantize_q5_0_cuda, quantize_q5_0_metal ); test_device!( quantize_q5_1, quantize_q5_1_cpu, quantize_q5_1_cuda, quantize_q5_1_metal ); test_device!( quantize_q2k, quantize_q2k_cpu, quantize_q2k_cuda, quantize_q2k_metal ); test_device!( quantize_q3k, quantize_q3k_cpu, quantize_q3k_cuda, quantize_q3k_metal ); test_device!( quantize_q4k, quantize_q4k_cpu, quantize_q4k_cuda, quantize_q4k_metal ); test_device!( quantize_q5k, quantize_q5k_cpu, quantize_q5k_cuda, quantize_q5k_metal ); test_device!( quantize_q6k, quantize_q6k_cpu, quantize_q6k_cuda, quantize_q6k_metal ); test_device!( quantize_q8k, quantize_q8k_cpu, quantize_q8k_cuda, quantize_q8k_metal ); /// Very simple dot product implementation fn vec_dot_reference(a: &[f32], b: &[f32]) -> f32 { a.iter().zip(b).map(|(a, b)| a * b).sum() } /// Returns the error achieved by the GGML matmul unit test. fn ggml_reference_matmul_error(dtype: GgmlDType) -> Result<f32> { let err = match dtype { GgmlDType::F16 => 0.000010, GgmlDType::Q2K => 0.004086, GgmlDType::Q3K => 0.016148, GgmlDType::Q4K => 0.002425, GgmlDType::Q5K => 0.000740, GgmlDType::Q6K => 0.000952, GgmlDType::Q4_0 => 0.001143, GgmlDType::Q4_1 => 0.008, GgmlDType::Q5_0 => 0.001353, GgmlDType::Q5_1 => 0.00149, GgmlDType::Q8_0 => 0.000092, // Not from the ggml repo. GgmlDType::Q8K => 0.00065, _ => bail!("No GGML results for quantization type {dtype:?}",), }; Ok(err) } /// Similar to the GGML matmul unit test: /// https://github.com/ggerganov/llama.cpp/blob/master/tests/test-quantize-fns.cpp#L76-L91 fn ggml_matmul_error_test<T: GgmlType>() -> Result<()> { let a = create_ggml_like_vector(0.0); let b = create_ggml_like_vector(1.0); ggml_matmul_error_test_::<T>(a.as_slice(), b.as_slice(), 1.0)?; // Another example that is more likely to trigger the overflow reported in #1526 let a = (0..GGML_TEST_SIZE) .map(|i| i as f32 / GGML_TEST_SIZE as f32) .collect::<Vec<_>>(); let b = (0..GGML_TEST_SIZE) .map(|i| i as f32 / GGML_TEST_SIZE as f32) .collect::<Vec<_>>(); ggml_matmul_error_test_::<T>(a.as_slice(), b.as_slice(), 2.0)?; Ok(()) } fn ggml_matmul_error_test_<T: GgmlType>(a: &[f32], b: &[f32], err_m: f32) -> Result<()> { let length = a.len(); let mut a_quant = vec![T::zeros(); length / T::BLCK_SIZE]; let mut b_quant = vec![T::VecDotType::zeros(); length / T::VecDotType::BLCK_SIZE]; T::from_float(a, &mut a_quant)?; T::VecDotType::from_float(b, &mut b_quant)?; let result = T::vec_dot(length, &a_quant, &b_quant)?; let result_unopt = T::vec_dot_unopt(length, &a_quant, &b_quant)?; let reference_result = vec_dot_reference(a, b); if (result - result_unopt).abs() / length as f32 > 1e-6 { bail!( "the opt and unopt vec-dot returned different values, opt {result}, unopt {result_unopt}" ) } let error = (result - reference_result).abs() / length as f32; let ggml_error = ggml_reference_matmul_error(T::DTYPE)? * err_m; if !error.is_finite() || error > GGML_MAX_DOT_PRODUCT_ERROR { bail!("Dot product error {error} exceeds max error {GGML_MAX_DOT_PRODUCT_ERROR}",); } // We diverge slightly due to different rounding behavior / f16 to f32 conversions in GGML // => we use a slightly higher error threshold const ERROR_LENIENCY: f32 = 0.00001; if error - ERROR_LENIENCY > ggml_error { bail!( "Dot product error {} exceeds ggml reference error {}", error, ggml_error ); } Ok(()) } #[test] fn quantized_mm() -> Result<()> { ggml_matmul_error_test::<k_quants::BlockQ4_0>()?; ggml_matmul_error_test::<k_quants::BlockQ4_1>()?; ggml_matmul_error_test::<k_quants::BlockQ5_0>()?; ggml_matmul_error_test::<k_quants::BlockQ5_1>()?; ggml_matmul_error_test::<k_quants::BlockQ8_0>()?; Ok(()) } /// generates random tensors of size `m x k` and `n x k` and calculates their expected matrix multiplication result. fn get_random_tensors( m: usize, k: usize, n: usize, device: &Device, ) -> Result<(Tensor, Tensor, Tensor)> { let mut rng = StdRng::seed_from_u64(314159265358979); let lhs = (0..m * k) .map(|_| rng.random::<f32>() - 0.5) .collect::<Vec<_>>(); let rhs = (0..n * k) .map(|_| rng.random::<f32>() - 0.5) .collect::<Vec<_>>(); let lhs = Tensor::from_vec(lhs, (m, k), device)?; let rhs = Tensor::from_vec(rhs, (n, k), device)?; let mm = lhs.matmul(&rhs.t()?)?; Ok((lhs, rhs, mm)) } #[macro_export] macro_rules! quantized_matmul { // TODO: Switch to generating the two last arguments automatically once concat_idents is // stable. https://github.com/rust-lang/rust/issues/29599 ($fn_name: ident, $fn_name_cpu: ident, $fn_name_cuda: ident, $fn_name_metal: ident, $dtype: expr) => { fn $fn_name(device: &Device) -> Result<()> { test_matmul(device, (1, 3, 4, 256), $dtype)?; Ok(()) } test_device!($fn_name, $fn_name_cpu, $fn_name_cuda, $fn_name_metal); }; } quantized_matmul!( quantized_matmul_q4_0_bis, quantized_matmul_q4_0_cpu, quantized_matmul_q4_0_cuda, quantized_matmul_q4_0_metal, GgmlDType::Q4_0 ); quantized_matmul!( quantized_matmul_q4_1_bis, quantized_matmul_q4_1_cpu, quantized_matmul_q4_1_cuda, quantized_matmul_q4_1_metal, GgmlDType::Q4_1 ); quantized_matmul!( quantized_matmul_q5_0_bis, quantized_matmul_q5_0_cpu, quantized_matmul_q5_0_cuda, quantized_matmul_q5_0_metal, GgmlDType::Q5_0 ); quantized_matmul!( quantized_matmul_q5_1_bis, quantized_matmul_q5_1_cpu, quantized_matmul_q5_1_cuda, quantized_matmul_q5_1_metal, GgmlDType::Q5_1 ); quantized_matmul!( quantized_matmul_q8_0_bis, quantized_matmul_q8_0_cpu, quantized_matmul_q8_0_cuda, quantized_matmul_q8_0_metal, GgmlDType::Q8_0 ); // Not implemented in Ggml // quantized_matmul!( // quantized_matmul_q8_1_bis, // quantized_matmul_q8_1_cpu, // quantized_matmul_q8_1_cuda, // quantized_matmul_q8_1_metal, // GgmlDType::Q8_1 // ); // TODO This is bugged (also bugged in GGML quantized_matmul!( quantized_matmul_q2k_bis, quantized_matmul_q2k_cpu, quantized_matmul_q2k_cuda, quantized_matmul_q2k_metal, GgmlDType::Q2K ); quantized_matmul!( quantized_matmul_q3k_bis, quantized_matmul_q3k_cpu, quantized_matmul_q3k_cuda, quantized_matmul_q3k_metal, GgmlDType::Q3K ); quantized_matmul!( quantized_matmul_q4k_bis, quantized_matmul_q4k_cpu, quantized_matmul_q4k_cuda, quantized_matmul_q4k_metal, GgmlDType::Q4K ); quantized_matmul!( quantized_matmul_q5k_bis, quantized_matmul_q5k_cpu, quantized_matmul_q5k_cuda, quantized_matmul_q5k_metal, GgmlDType::Q5K ); quantized_matmul!( quantized_matmul_q6k_bis, quantized_matmul_q6k_cpu, quantized_matmul_q6k_cuda, quantized_matmul_q6k_metal, GgmlDType::Q6K ); // Not implemented on metal // quantized_matmul!( // quantized_matmul_q8k_bis, // quantized_matmul_q8k_cpu, // quantized_matmul_q8k_cuda, // quantized_matmul_q8k_metal, // GgmlDType::Q8K // ); #[test] fn quantized_matmul_q2k() -> Result<()> { use k_quants::BlockQ2K; let cpu = &Device::Cpu; let (m, k, n) = (11, 512, 21); let (lhs, rhs, mm) = get_random_tensors(m, k, n, cpu)?; assert_eq!(mm.dims(), [m, n]); let dst = mm.flatten_all()?.to_vec1::<f32>()?; let dst = round_vector(&[dst[0], dst[m * n / 3], dst[m * n * 2 / 3], dst[m * n - 1]]); assert_eq!(dst, [1.262, 1.513, -0.208, 1.702]); let rhs = quantized::QTensor::quantize(&rhs, GgmlDType::Q2K)?; let rhs = quantized::QMatMul::from_qtensor(rhs)?; let mm = rhs.forward(&lhs)?; assert_eq!(mm.dims(), [m, n]); let dst = mm.flatten_all()?.to_vec1::<f32>()?; let dst = round_vector(&[dst[0], dst[m * n / 3], dst[m * n * 2 / 3], dst[m * n - 1]]); assert_eq!(dst, [0.916, 0.422, 0.215, 1.668]); ggml_matmul_error_test::<BlockQ2K>()?; Ok(()) } #[test] fn quantized_matmul_q3k() -> Result<()> { use k_quants::BlockQ3K; let cpu = &Device::Cpu; let (m, k, n) = (11, 512, 21); let (lhs, rhs, mm) = get_random_tensors(m, k, n, cpu)?; assert_eq!(mm.dims(), [m, n]); let dst = mm.flatten_all()?.to_vec1::<f32>()?; let dst = round_vector(&[dst[0], dst[m * n / 3], dst[m * n * 2 / 3], dst[m * n - 1]]); assert_eq!(dst, [1.262, 1.513, -0.208, 1.702]); let rhs = quantized::QTensor::quantize(&rhs, GgmlDType::Q3K)?; let rhs = quantized::QMatMul::from_qtensor(rhs)?; let mm = rhs.forward(&lhs)?; assert_eq!(mm.dims(), [m, n]); let dst = mm.flatten_all()?.to_vec1::<f32>()?; let dst = round_vector(&[dst[0], dst[m * n / 3], dst[m * n * 2 / 3], dst[m * n - 1]]); assert_eq!(dst, [1.029, 1.418, -0.314, 1.495]); ggml_matmul_error_test::<BlockQ3K>()?; Ok(()) } #[test] fn quantized_matmul_q4k() -> Result<()> { use k_quants::BlockQ4K; let cpu = &Device::Cpu; let (m, k, n) = (11, 512, 21); let (lhs, rhs, mm) = get_random_tensors(m, k, n, cpu)?; assert_eq!(mm.dims(), [m, n]); let dst = mm.flatten_all()?.to_vec1::<f32>()?; let dst = round_vector(&[dst[0], dst[m * n / 3], dst[m * n * 2 / 3], dst[m * n - 1]]); assert_eq!(dst, [1.262, 1.513, -0.208, 1.702]); let rhs = quantized::QTensor::quantize(&rhs, GgmlDType::Q4K)?; let rhs = quantized::QMatMul::from_qtensor(rhs)?; let mm = rhs.forward(&lhs)?; assert_eq!(mm.dims(), [m, n]); let dst = mm.flatten_all()?.to_vec1::<f32>()?; let dst = round_vector(&[dst[0], dst[m * n / 3], dst[m * n * 2 / 3], dst[m * n - 1]]); assert_eq!(dst, [1.125, 1.435, -0.201, 1.589]); ggml_matmul_error_test::<BlockQ4K>()?; Ok(()) } #[test] fn quantized_matmul_q5k() -> Result<()> { use k_quants::BlockQ5K; let cpu = &Device::Cpu; let (m, k, n) = (11, 512, 21); let (lhs, rhs, mm) = get_random_tensors(m, k, n, cpu)?; assert_eq!(mm.dims(), [m, n]); let dst = mm.flatten_all()?.to_vec1::<f32>()?; let dst = round_vector(&[dst[0], dst[m * n / 3], dst[m * n * 2 / 3], dst[m * n - 1]]); assert_eq!(dst, [1.262, 1.513, -0.208, 1.702]); let rhs = quantized::QTensor::quantize(&rhs, GgmlDType::Q5K)?; let rhs = quantized::QMatMul::from_qtensor(rhs)?; let mm = rhs.forward(&lhs)?; assert_eq!(mm.dims(), [m, n]); let dst = mm.flatten_all()?.to_vec1::<f32>()?; let dst = round_vector(&[dst[0], dst[m * n / 3], dst[m * n * 2 / 3], dst[m * n - 1]]); assert_eq!(dst, [1.192, 1.491, -0.18, 1.743]); //Expected: 0.000740408897 ggml_matmul_error_test::<BlockQ5K>()?; Ok(()) } #[test] fn quantized_matmul_q6k() -> Result<()> { use k_quants::BlockQ6K; let cpu = &Device::Cpu; let (m, k, n) = (11, 512, 21); let (lhs, rhs, mm) = get_random_tensors(m, k, n, cpu)?; assert_eq!(mm.dims(), [m, n]); let dst = mm.flatten_all()?.to_vec1::<f32>()?; let dst = round_vector(&[dst[0], dst[m * n / 3], dst[m * n * 2 / 3], dst[m * n - 1]]); assert_eq!(dst, [1.262, 1.513, -0.208, 1.702]); let rhs = quantized::QTensor::quantize(&rhs, GgmlDType::Q6K)?; let rhs = quantized::QMatMul::from_qtensor(rhs)?; let mm = rhs.forward(&lhs)?; assert_eq!(mm.dims(), [m, n]); let dst = mm.flatten_all()?.to_vec1::<f32>()?; let dst = round_vector(&[dst[0], dst[m * n / 3], dst[m * n * 2 / 3], dst[m * n - 1]]); assert_eq!(dst, [1.324, 1.49, -0.164, 1.741]); ggml_matmul_error_test::<BlockQ6K>()?; Ok(()) } #[test] fn quantized_matmul_q8k() -> Result<()> { use k_quants::BlockQ8K; let cpu = &Device::Cpu; let (m, k, n) = (11, 512, 21); let (lhs, rhs, mm) = get_random_tensors(m, k, n, cpu)?; assert_eq!(mm.dims(), [m, n]); let dst = mm.flatten_all()?.to_vec1::<f32>()?; let dst = round_vector(&[dst[0], dst[m * n / 3], dst[m * n * 2 / 3], dst[m * n - 1]]); assert_eq!(dst, [1.262, 1.513, -0.208, 1.702]); let rhs = quantized::QTensor::quantize(&rhs, GgmlDType::Q8K)?; let rhs = quantized::QMatMul::from_qtensor(rhs)?; let mm = rhs.forward(&lhs)?; assert_eq!(mm.dims(), [m, n]); let dst = mm.flatten_all()?.to_vec1::<f32>()?; let dst = round_vector(&[dst[0], dst[m * n / 3], dst[m * n * 2 / 3], dst[m * n - 1]]); assert_eq!(dst, [1.266, 1.504, -0.204, 1.7]); ggml_matmul_error_test::<BlockQ8K>()?; Ok(()) }
candle/candle-core/tests/quantized_tests.rs/0
{ "file_path": "candle/candle-core/tests/quantized_tests.rs", "repo_id": "candle", "token_count": 22148 }
31
//! The MNIST hand-written digit dataset. //! //! The files can be obtained from the following link: //! <http://yann.lecun.com/exdb/mnist/> use candle::{DType, Device, Error, Result, Tensor}; use hf_hub::{api::sync::Api, Repo, RepoType}; use parquet::file::reader::{FileReader, SerializedFileReader}; use std::fs::File; use std::io::{self, BufReader, Read}; fn read_u32<T: Read>(reader: &mut T) -> std::io::Result<u32> { use byteorder::ReadBytesExt; reader.read_u32::<byteorder::BigEndian>() } fn check_magic_number<T: Read>(reader: &mut T, expected: u32) -> Result<()> { let magic_number = read_u32(reader)?; if magic_number != expected { Err(io::Error::other(format!( "incorrect magic number {magic_number} != {expected}" )))?; } Ok(()) } fn read_labels(filename: &std::path::Path) -> Result<Tensor> { let mut buf_reader = BufReader::new(File::open(filename)?); check_magic_number(&mut buf_reader, 2049)?; let samples = read_u32(&mut buf_reader)?; let mut data = vec![0u8; samples as usize]; buf_reader.read_exact(&mut data)?; let samples = data.len(); Tensor::from_vec(data, samples, &Device::Cpu) } fn read_images(filename: &std::path::Path) -> Result<Tensor> { let mut buf_reader = BufReader::new(File::open(filename)?); check_magic_number(&mut buf_reader, 2051)?; let samples = read_u32(&mut buf_reader)? as usize; let rows = read_u32(&mut buf_reader)? as usize; let cols = read_u32(&mut buf_reader)? as usize; let data_len = samples * rows * cols; let mut data = vec![0u8; data_len]; buf_reader.read_exact(&mut data)?; let tensor = Tensor::from_vec(data, (samples, rows * cols), &Device::Cpu)?; tensor.to_dtype(DType::F32)? / 255. } pub fn load_dir<T: AsRef<std::path::Path>>(dir: T) -> Result<crate::vision::Dataset> { let dir = dir.as_ref(); let train_images = read_images(&dir.join("train-images-idx3-ubyte"))?; let train_labels = read_labels(&dir.join("train-labels-idx1-ubyte"))?; let test_images = read_images(&dir.join("t10k-images-idx3-ubyte"))?; let test_labels = read_labels(&dir.join("t10k-labels-idx1-ubyte"))?; Ok(crate::vision::Dataset { train_images, train_labels, test_images, test_labels, labels: 10, }) } fn load_parquet(parquet: SerializedFileReader<std::fs::File>) -> Result<(Tensor, Tensor)> { let samples = parquet.metadata().file_metadata().num_rows() as usize; let mut buffer_images: Vec<u8> = Vec::with_capacity(samples * 784); let mut buffer_labels: Vec<u8> = Vec::with_capacity(samples); for row in parquet.into_iter().flatten() { for (_name, field) in row.get_column_iter() { if let parquet::record::Field::Group(subrow) = field { for (_name, field) in subrow.get_column_iter() { if let parquet::record::Field::Bytes(value) = field { let image = image::load_from_memory(value.data()).unwrap(); buffer_images.extend(image.to_luma8().as_raw()); } } } else if let parquet::record::Field::Long(label) = field { buffer_labels.push(*label as u8); } } } let images = (Tensor::from_vec(buffer_images, (samples, 784), &Device::Cpu)? .to_dtype(DType::F32)? / 255.)?; let labels = Tensor::from_vec(buffer_labels, (samples,), &Device::Cpu)?; Ok((images, labels)) } pub(crate) fn load_mnist_like( dataset_id: &str, revision: &str, test_filename: &str, train_filename: &str, ) -> Result<crate::vision::Dataset> { let api = Api::new().map_err(|e| Error::Msg(format!("Api error: {e}")))?; let repo = Repo::with_revision( dataset_id.to_string(), RepoType::Dataset, revision.to_string(), ); let repo = api.repo(repo); let test_parquet_filename = repo .get(test_filename) .map_err(|e| Error::Msg(format!("Api error: {e}")))?; let train_parquet_filename = repo .get(train_filename) .map_err(|e| Error::Msg(format!("Api error: {e}")))?; let test_parquet = SerializedFileReader::new(std::fs::File::open(test_parquet_filename)?) .map_err(|e| Error::Msg(format!("Parquet error: {e}")))?; let train_parquet = SerializedFileReader::new(std::fs::File::open(train_parquet_filename)?) .map_err(|e| Error::Msg(format!("Parquet error: {e}")))?; let (test_images, test_labels) = load_parquet(test_parquet)?; let (train_images, train_labels) = load_parquet(train_parquet)?; Ok(crate::vision::Dataset { train_images, train_labels, test_images, test_labels, labels: 10, }) } pub fn load() -> Result<crate::vision::Dataset> { load_mnist_like( "ylecun/mnist", "refs/convert/parquet", "mnist/test/0000.parquet", "mnist/train/0000.parquet", ) }
candle/candle-datasets/src/vision/mnist.rs/0
{ "file_path": "candle/candle-datasets/src/vision/mnist.rs", "repo_id": "candle", "token_count": 2239 }
32
# candle-custom-ops This example illustrates how to implement forward and backward passes for custom operations on the CPU and GPU. The custom op in this example implements RMS normalization for the CPU and CUDA. ## Running an example ```bash $ cargo run --example custom-ops > [[ 0., 1., 2., 3., 4., 5., 6.], > [ 7., 8., 9., 10., 11., 12., 13.]] > Tensor[[2, 7], f32] > [[0.0000, 0.2773, 0.5547, 0.8320, 1.1094, 1.3867, 1.6641], > [0.6864, 0.7845, 0.8825, 0.9806, 1.0786, 1.1767, 1.2748]] > Tensor[[2, 7], f32] ```
candle/candle-examples/examples/custom-ops/README.md/0
{ "file_path": "candle/candle-examples/examples/custom-ops/README.md", "repo_id": "candle", "token_count": 215 }
33
# candle-distilbert DistilBert is a distiled version of the Bert model. ## Sentence embeddings DistilBert is used to compute the sentence embeddings for a prompt. The model weights are downloaded from the hub on the first run. ```bash $ cargo run --example distilbert --release -- --prompt "Here is a test sentence" > [[[ 0.5109, 0.1280, -0.2635, ..., 0.3462, -1.0434, 0.1441], > [ 0.1735, 0.0818, -0.5549, ..., 0.3472, -0.8264, -0.0244], > [ 0.0702, -0.1311, -0.4914, ..., 0.3483, -0.6194, 0.1829], > ... > [ 0.2993, -0.0106, -0.4640, ..., 0.2844, -0.6732, 0.0042], > [ 0.1066, -0.0081, -0.4299, ..., 0.3435, -0.7729, 0.0190], > [ 0.8903, 0.2055, -0.2541, ..., 0.3208, -0.6585, 0.0586]]] > Tensor[[1, 7, 768], f32] ``` ## Masked Token DistilBert is used to compute the top K choices for a masked token. ```bash $ cargo run --example distilbert -- --prompt "The capital of France is [MASK]." --top-k 10 > Input: The capital of France is [MASK]. > Predictions for [MASK] at position 6: > 1: marseille (probability: 12.14%) > 2: paris (probability: 10.84%) > 3: toulouse (probability: 8.57%) > 4: lyon (probability: 7.61%) > 5: montpellier (probability: 5.18%) > 6: bordeaux (probability: 4.88%) > 7: nantes (probability: 4.82%) > 8: lille (probability: 4.07%) > 9: strasbourg (probability: 3.12%) > 10: cannes (probability: 3.04%) ```
candle/candle-examples/examples/distilbert/README.md/0
{ "file_path": "candle/candle-examples/examples/distilbert/README.md", "repo_id": "candle", "token_count": 708 }
34
# candle-flux: image generation with latent rectified flow transformers ![rusty robot holding a candle](./assets/flux-robot.jpg) Flux is a 12B rectified flow transformer capable of generating images from text descriptions, [huggingface](https://huggingface.co/black-forest-labs/FLUX.1-schnell), [github](https://github.com/black-forest-labs/flux), [blog post](https://blackforestlabs.ai/announcing-black-forest-labs/). ## Running the model ```bash cargo run --features cuda --example flux -r -- \ --height 1024 --width 1024 \ --prompt "a rusty robot walking on a beach holding a small torch, the robot has the word "rust" written on it, high quality, 4k" ```
candle/candle-examples/examples/flux/README.md/0
{ "file_path": "candle/candle-examples/examples/flux/README.md", "repo_id": "candle", "token_count": 216 }
35
# candle-jina-bert Jina-Bert is a general large language model with a context size of 8192, [model card](https://huggingface.co/jinaai/jina-embeddings-v2-base-en). In this example it can be used for two different tasks: - Compute sentence embeddings for a prompt. - Compute similarities between a set of sentences. ## Sentence embeddings Jina-Bert is used to compute the sentence embeddings for a prompt. The model weights are downloaded from the hub on the first run. ```bash cargo run --example jina-bert --release -- --prompt "Here is a test sentence" > [[[ 0.1595, -0.9885, 0.6494, ..., 0.3003, -0.6901, -1.2355], > [ 0.0374, -0.1798, 1.3359, ..., 0.6731, 0.2133, -1.6807], > [ 0.1700, -0.8534, 0.8924, ..., -0.1785, -0.0727, -1.5087], > ... > [-0.3113, -1.3665, 0.2027, ..., -0.2519, 0.1711, -1.5811], > [ 0.0907, -1.0492, 0.5382, ..., 0.0242, -0.7077, -1.0830], > [ 0.0369, -0.6343, 0.6105, ..., 0.0671, 0.3778, -1.1505]]] > Tensor[[1, 7, 768], f32] ``` ## Similarities In this example, Jina-Bert is used to compute the sentence embeddings for a set of sentences (hardcoded in the examples). Then cosine similarities are computed for each sentence pair and they are reported by decreasing values, hence the first reported pair contains the two sentences that have the highest similarity score. The sentence embeddings are computed using average pooling through all the sentence tokens, including some potential padding. ```bash cargo run --example jina-bert --release > score: 0.94 'The new movie is awesome' 'The new movie is so great' > score: 0.81 'The cat sits outside' 'The cat plays in the garden' > score: 0.78 'I love pasta' 'Do you like pizza?' > score: 0.68 'I love pasta' 'The new movie is awesome' > score: 0.67 'A man is playing guitar' 'A woman watches TV' ```
candle/candle-examples/examples/jina-bert/README.md/0
{ "file_path": "candle/candle-examples/examples/jina-bert/README.md", "repo_id": "candle", "token_count": 663 }
36
# candle-mamba: Mamba implementation Candle implementation of *Mamba* [1] inference only. Mamba is an alternative to the transformer architecture. It leverages State Space Models (SSMs) with the goal of being computationally efficient on long sequences. The implementation is based on [mamba.rs](https://github.com/LaurentMazare/mamba.rs). - [1]. [Mamba: Linear-Time Sequence Modeling with Selective State Spaces](https://arxiv.org/abs/2312.00752). Compared to the mamba-minimal example, this version is far more efficient but would only work for inference. ## Running the example ```bash $ cargo run --example mamba --release -- --prompt "Mamba is the" ```
candle/candle-examples/examples/mamba/README.md/0
{ "file_path": "candle/candle-examples/examples/mamba/README.md", "repo_id": "candle", "token_count": 187 }
37
// This should reach 91.5% accuracy. #[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; use clap::{Parser, ValueEnum}; use rand::prelude::*; use rand::rng; use candle::{DType, Result, Tensor, D}; use candle_nn::{loss, ops, Conv2d, Linear, Module, ModuleT, Optimizer, VarBuilder, VarMap}; const IMAGE_DIM: usize = 784; const LABELS: usize = 10; fn linear_z(in_dim: usize, out_dim: usize, vs: VarBuilder) -> Result<Linear> { let ws = vs.get_with_hints((out_dim, in_dim), "weight", candle_nn::init::ZERO)?; let bs = vs.get_with_hints(out_dim, "bias", candle_nn::init::ZERO)?; Ok(Linear::new(ws, Some(bs))) } trait Model: Sized { fn new(vs: VarBuilder) -> Result<Self>; fn forward(&self, xs: &Tensor) -> Result<Tensor>; } struct LinearModel { linear: Linear, } impl Model for LinearModel { fn new(vs: VarBuilder) -> Result<Self> { let linear = linear_z(IMAGE_DIM, LABELS, vs)?; Ok(Self { linear }) } fn forward(&self, xs: &Tensor) -> Result<Tensor> { self.linear.forward(xs) } } struct Mlp { ln1: Linear, ln2: Linear, } impl Model for Mlp { fn new(vs: VarBuilder) -> Result<Self> { let ln1 = candle_nn::linear(IMAGE_DIM, 100, vs.pp("ln1"))?; let ln2 = candle_nn::linear(100, LABELS, vs.pp("ln2"))?; Ok(Self { ln1, ln2 }) } fn forward(&self, xs: &Tensor) -> Result<Tensor> { let xs = self.ln1.forward(xs)?; let xs = xs.relu()?; self.ln2.forward(&xs) } } #[derive(Debug)] struct ConvNet { conv1: Conv2d, conv2: Conv2d, fc1: Linear, fc2: Linear, dropout: candle_nn::Dropout, } impl ConvNet { fn new(vs: VarBuilder) -> Result<Self> { let conv1 = candle_nn::conv2d(1, 32, 5, Default::default(), vs.pp("c1"))?; let conv2 = candle_nn::conv2d(32, 64, 5, Default::default(), vs.pp("c2"))?; let fc1 = candle_nn::linear(1024, 1024, vs.pp("fc1"))?; let fc2 = candle_nn::linear(1024, LABELS, vs.pp("fc2"))?; let dropout = candle_nn::Dropout::new(0.5); Ok(Self { conv1, conv2, fc1, fc2, dropout, }) } fn forward(&self, xs: &Tensor, train: bool) -> Result<Tensor> { let (b_sz, _img_dim) = xs.dims2()?; let xs = xs .reshape((b_sz, 1, 28, 28))? .apply(&self.conv1)? .max_pool2d(2)? .apply(&self.conv2)? .max_pool2d(2)? .flatten_from(1)? .apply(&self.fc1)? .relu()?; self.dropout.forward_t(&xs, train)?.apply(&self.fc2) } } struct TrainingArgs { learning_rate: f64, load: Option<String>, save: Option<String>, epochs: usize, } fn training_loop_cnn( m: candle_datasets::vision::Dataset, args: &TrainingArgs, ) -> anyhow::Result<()> { const BSIZE: usize = 64; let dev = candle::Device::cuda_if_available(0)?; let train_labels = m.train_labels; let train_images = m.train_images.to_device(&dev)?; let train_labels = train_labels.to_dtype(DType::U32)?.to_device(&dev)?; let mut varmap = VarMap::new(); let vs = VarBuilder::from_varmap(&varmap, DType::F32, &dev); let model = ConvNet::new(vs.clone())?; if let Some(load) = &args.load { println!("loading weights from {load}"); varmap.load(load)? } let adamw_params = candle_nn::ParamsAdamW { lr: args.learning_rate, ..Default::default() }; let mut opt = candle_nn::AdamW::new(varmap.all_vars(), adamw_params)?; let test_images = m.test_images.to_device(&dev)?; let test_labels = m.test_labels.to_dtype(DType::U32)?.to_device(&dev)?; let n_batches = train_images.dim(0)? / BSIZE; let mut batch_idxs = (0..n_batches).collect::<Vec<usize>>(); for epoch in 1..args.epochs { let mut sum_loss = 0f32; batch_idxs.shuffle(&mut rng()); for batch_idx in batch_idxs.iter() { let train_images = train_images.narrow(0, batch_idx * BSIZE, BSIZE)?; let train_labels = train_labels.narrow(0, batch_idx * BSIZE, BSIZE)?; let logits = model.forward(&train_images, true)?; let log_sm = ops::log_softmax(&logits, D::Minus1)?; let loss = loss::nll(&log_sm, &train_labels)?; opt.backward_step(&loss)?; sum_loss += loss.to_vec0::<f32>()?; } let avg_loss = sum_loss / n_batches as f32; let test_logits = model.forward(&test_images, false)?; let sum_ok = test_logits .argmax(D::Minus1)? .eq(&test_labels)? .to_dtype(DType::F32)? .sum_all()? .to_scalar::<f32>()?; let test_accuracy = sum_ok / test_labels.dims1()? as f32; println!( "{epoch:4} train loss {:8.5} test acc: {:5.2}%", avg_loss, 100. * test_accuracy ); } if let Some(save) = &args.save { println!("saving trained weights in {save}"); varmap.save(save)? } Ok(()) } fn training_loop<M: Model>( m: candle_datasets::vision::Dataset, args: &TrainingArgs, ) -> anyhow::Result<()> { let dev = candle::Device::cuda_if_available(0)?; let train_labels = m.train_labels; let train_images = m.train_images.to_device(&dev)?; let train_labels = train_labels.to_dtype(DType::U32)?.to_device(&dev)?; let mut varmap = VarMap::new(); let vs = VarBuilder::from_varmap(&varmap, DType::F32, &dev); let model = M::new(vs.clone())?; if let Some(load) = &args.load { println!("loading weights from {load}"); varmap.load(load)? } let mut sgd = candle_nn::SGD::new(varmap.all_vars(), args.learning_rate)?; let test_images = m.test_images.to_device(&dev)?; let test_labels = m.test_labels.to_dtype(DType::U32)?.to_device(&dev)?; for epoch in 1..args.epochs { let logits = model.forward(&train_images)?; let log_sm = ops::log_softmax(&logits, D::Minus1)?; let loss = loss::nll(&log_sm, &train_labels)?; sgd.backward_step(&loss)?; let test_logits = model.forward(&test_images)?; let sum_ok = test_logits .argmax(D::Minus1)? .eq(&test_labels)? .to_dtype(DType::F32)? .sum_all()? .to_scalar::<f32>()?; let test_accuracy = sum_ok / test_labels.dims1()? as f32; println!( "{epoch:4} train loss: {:8.5} test acc: {:5.2}%", loss.to_scalar::<f32>()?, 100. * test_accuracy ); } if let Some(save) = &args.save { println!("saving trained weights in {save}"); varmap.save(save)? } Ok(()) } #[derive(ValueEnum, Clone)] enum WhichModel { Linear, Mlp, Cnn, } #[derive(Parser)] struct Args { #[clap(value_enum, default_value_t = WhichModel::Linear)] model: WhichModel, #[arg(long)] learning_rate: Option<f64>, #[arg(long, default_value_t = 200)] epochs: usize, /// The file where to save the trained weights, in safetensors format. #[arg(long)] save: Option<String>, /// The file where to load the trained weights from, in safetensors format. #[arg(long)] load: Option<String>, /// The directory where to load the dataset from, in ubyte format. #[arg(long)] local_mnist: Option<String>, } pub fn main() -> anyhow::Result<()> { let args = Args::parse(); // Load the dataset let m = if let Some(directory) = args.local_mnist { candle_datasets::vision::mnist::load_dir(directory)? } else { candle_datasets::vision::mnist::load()? }; println!("train-images: {:?}", m.train_images.shape()); println!("train-labels: {:?}", m.train_labels.shape()); println!("test-images: {:?}", m.test_images.shape()); println!("test-labels: {:?}", m.test_labels.shape()); let default_learning_rate = match args.model { WhichModel::Linear => 1., WhichModel::Mlp => 0.05, WhichModel::Cnn => 0.001, }; let training_args = TrainingArgs { epochs: args.epochs, learning_rate: args.learning_rate.unwrap_or(default_learning_rate), load: args.load, save: args.save, }; match args.model { WhichModel::Linear => training_loop::<LinearModel>(m, &training_args), WhichModel::Mlp => training_loop::<Mlp>(m, &training_args), WhichModel::Cnn => training_loop_cnn(m, &training_args), } }
candle/candle-examples/examples/mnist-training/main.rs/0
{ "file_path": "candle/candle-examples/examples/mnist-training/main.rs", "repo_id": "candle", "token_count": 4099 }
38
# candle-olmo: Open Language Models designed to enable the science of language models OLMo is a series of Open Language Models designed to enable the science of language models. - **Project Page:** https://allenai.org/olmo - **Papers:** [OLMo](https://arxiv.org/abs/2402.00838) [OLMo 2](https://arxiv.org/abs/2501.00656) - **Technical blog post:** https://blog.allenai.org/olmo-open-language-model-87ccfc95f580 - **W&B Logs:** https://wandb.ai/ai2-llm/OLMo-1B/reports/OLMo-1B--Vmlldzo2NzY1Njk1 <!-- - **Press release:** TODO --> ## Running the example ```bash $ cargo run --example olmo --release -- --prompt "It is only with the heart that one can see rightly" avx: true, neon: false, simd128: false, f16c: true temp: 0.20 repeat-penalty: 1.10 repeat-last-n: 64 retrieved the files in 354.977µs loaded the model in 19.87779666s It is only with the heart that one can see rightly; what is essential is invisible to the eye. ``` Various model sizes are available via the `--model` argument. ```bash $ cargo run --example olmo --release -- --model 1.7-7b --prompt 'It is only with the heart that one can see rightly' avx: true, neon: false, simd128: false, f16c: true temp: 0.20 repeat-penalty: 1.10 repeat-last-n: 64 retrieved the files in 1.226087ms loaded the model in 171.274578609s It is only with the heart that one can see rightly; what is essential is invisible to the eye.” ~ Antoine de Saint-Exupery, The Little Prince I am a big fan of this quote. It reminds me that I need to be open and aware of my surroundings in order to truly appreciate them. ```
candle/candle-examples/examples/olmo/README.md/0
{ "file_path": "candle/candle-examples/examples/olmo/README.md", "repo_id": "candle", "token_count": 527 }
39
# pixtral Pixtral-12B is a 12B text+vision model. [Blog Post](https://mistral.ai/news/pixtral-12b/) - [HF Model Card](https://huggingface.co/mistralai/Pixtral-12B-2409) - [HF Community Model Card](https://huggingface.co/mistral-community/pixtral-12b). ```bash cargo run --profile=release-with-debug --features cuda --example pixtral -- \ --image candle-examples/examples/flux/assets/flux-robot.jpg ``` ``` Describe the image. The image depicts a charming, rustic robot standing on a sandy beach at sunset. The robot has a vintage, steampunk aesthetic with visible gears and mechanical parts. It is holding a small lantern in one hand, which emits a warm glow, and its other arm is extended forward as if reaching out or guiding the way. The robot's body is adorned with the word "RUST" in bright orange letters, adding to its rustic theme. The background features a dramatic sky filled with clouds, illuminated by the setting sun, casting a golden hue over the scene. Gentle waves lap against the shore, creating a serene and picturesque atmosphere. The overall mood of the image is whimsical and nostalgic, evoking a sense of adventure and tranquility. ```
candle/candle-examples/examples/pixtral/README.md/0
{ "file_path": "candle/candle-examples/examples/pixtral/README.md", "repo_id": "candle", "token_count": 338 }
40
#[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; use anyhow::{Error as E, Result}; use clap::Parser; use candle_transformers::models::qwen2::{Config as ConfigBase, ModelForCausalLM as ModelBase}; use candle_transformers::models::qwen2_moe::{Config as ConfigMoe, Model as ModelMoe}; use candle_transformers::models::qwen3::{Config as Config3, ModelForCausalLM as Model3}; use candle_transformers::models::qwen3_moe::{Config as ConfigMoe3, ModelForCausalLM as ModelMoe3}; use candle::{DType, Device, Tensor}; use candle_examples::token_output_stream::TokenOutputStream; use candle_nn::VarBuilder; use candle_transformers::generation::LogitsProcessor; use hf_hub::{api::sync::Api, Repo, RepoType}; use tokenizers::Tokenizer; enum Model { Base(ModelBase), Moe(ModelMoe), Base3(Model3), Moe3(ModelMoe3), } impl Model { fn forward(&mut self, xs: &Tensor, s: usize) -> candle::Result<Tensor> { match self { Self::Moe(ref mut m) => m.forward(xs, s), Self::Base(ref mut m) => m.forward(xs, s), Self::Base3(ref mut m) => m.forward(xs, s), Self::Moe3(ref mut m) => m.forward(xs, s), } } } struct TextGeneration { model: Model, device: Device, tokenizer: TokenOutputStream, logits_processor: LogitsProcessor, repeat_penalty: f32, repeat_last_n: usize, } impl TextGeneration { #[allow(clippy::too_many_arguments)] fn new( model: Model, tokenizer: Tokenizer, seed: u64, temp: Option<f64>, top_p: Option<f64>, repeat_penalty: f32, repeat_last_n: usize, device: &Device, ) -> Self { let logits_processor = LogitsProcessor::new(seed, temp, top_p); Self { model, tokenizer: TokenOutputStream::new(tokenizer), logits_processor, repeat_penalty, repeat_last_n, device: device.clone(), } } fn run(&mut self, prompt: &str, sample_len: usize) -> Result<()> { use std::io::Write; self.tokenizer.clear(); let mut tokens = self .tokenizer .tokenizer() .encode(prompt, true) .map_err(E::msg)? .get_ids() .to_vec(); for &t in tokens.iter() { if let Some(t) = self.tokenizer.next_token(t)? { print!("{t}") } } std::io::stdout().flush()?; let mut generated_tokens = 0usize; let eos_token = match self.tokenizer.get_token("<|endoftext|>") { Some(token) => token, None => anyhow::bail!("cannot find the <|endoftext|> token"), }; let eos_token2 = match self.tokenizer.get_token("<|im_end|>") { Some(token) => token, None => anyhow::bail!("cannot find the <|im_end|> token"), }; let start_gen = std::time::Instant::now(); for index in 0..sample_len { let context_size = if index > 0 { 1 } else { tokens.len() }; let start_pos = tokens.len().saturating_sub(context_size); let ctxt = &tokens[start_pos..]; let input = Tensor::new(ctxt, &self.device)?.unsqueeze(0)?; let logits = self.model.forward(&input, start_pos)?; let logits = logits.squeeze(0)?.squeeze(0)?.to_dtype(DType::F32)?; let logits = if self.repeat_penalty == 1. { logits } else { let start_at = tokens.len().saturating_sub(self.repeat_last_n); candle_transformers::utils::apply_repeat_penalty( &logits, self.repeat_penalty, &tokens[start_at..], )? }; let next_token = self.logits_processor.sample(&logits)?; tokens.push(next_token); generated_tokens += 1; if next_token == eos_token || next_token == eos_token2 { break; } if let Some(t) = self.tokenizer.next_token(next_token)? { print!("{t}"); std::io::stdout().flush()?; } } let dt = start_gen.elapsed(); if let Some(rest) = self.tokenizer.decode_rest().map_err(E::msg)? { print!("{rest}"); } std::io::stdout().flush()?; println!( "\n{generated_tokens} tokens generated ({:.2} token/s)", generated_tokens as f64 / dt.as_secs_f64(), ); Ok(()) } } #[derive(Clone, Copy, Debug, clap::ValueEnum, PartialEq, Eq)] enum WhichModel { #[value(name = "0.5b")] W0_5b, #[value(name = "1.8b")] W1_8b, #[value(name = "4b")] W4b, #[value(name = "7b")] W7b, #[value(name = "14b")] W14b, #[value(name = "72b")] W72b, #[value(name = "moe-a2.7b")] MoeA27b, #[value(name = "2-0.5b")] W2_0_5b, #[value(name = "2-1.5b")] W2_1_5b, #[value(name = "2-7b")] W2_7b, #[value(name = "2-72b")] W2_72b, #[value(name = "3-0.6b")] W3_0_6b, #[value(name = "3-1.7b")] W3_1_7b, #[value(name = "3-4b")] W3_4b, #[value(name = "3-8b")] W3_8b, #[value(name = "3-moe-a3b")] W3MoeA3b, } #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] struct Args { /// Run on CPU rather than on GPU. #[arg(long)] cpu: bool, /// Enable tracing (generates a trace-timestamp.json file). #[arg(long)] tracing: bool, #[arg(long)] use_flash_attn: bool, #[arg(long)] prompt: String, /// The temperature used to generate samples. #[arg(long)] temperature: Option<f64>, /// Nucleus sampling probability cutoff. #[arg(long)] top_p: Option<f64>, /// The seed to use when generating random samples. #[arg(long, default_value_t = 299792458)] seed: u64, /// The length of the sample to generate (in tokens). #[arg(long, short = 'n', default_value_t = 10000)] sample_len: usize, #[arg(long)] model_id: Option<String>, #[arg(long, default_value = "main")] revision: String, #[arg(long)] tokenizer_file: Option<String>, #[arg(long)] weight_files: Option<String>, /// Penalty to be applied for repeating tokens, 1. means no penalty. #[arg(long, default_value_t = 1.1)] repeat_penalty: f32, /// The context size to consider for the repeat penalty. #[arg(long, default_value_t = 64)] repeat_last_n: usize, #[arg(long, default_value = "0.5b")] model: WhichModel, } fn main() -> Result<()> { use tracing_chrome::ChromeLayerBuilder; use tracing_subscriber::prelude::*; let args = Args::parse(); let _guard = if args.tracing { let (chrome_layer, guard) = ChromeLayerBuilder::new().build(); tracing_subscriber::registry().with(chrome_layer).init(); Some(guard) } else { None }; println!( "avx: {}, neon: {}, simd128: {}, f16c: {}", candle::utils::with_avx(), candle::utils::with_neon(), candle::utils::with_simd128(), candle::utils::with_f16c() ); println!( "temp: {:.2} repeat-penalty: {:.2} repeat-last-n: {}", args.temperature.unwrap_or(0.), args.repeat_penalty, args.repeat_last_n ); let start = std::time::Instant::now(); let api = Api::new()?; let model_id = match args.model_id { Some(model_id) => model_id, None => { let (version, size) = match args.model { WhichModel::W2_0_5b => ("2", "0.5B"), WhichModel::W2_1_5b => ("2", "1.5B"), WhichModel::W2_7b => ("2", "7B"), WhichModel::W2_72b => ("2", "72B"), WhichModel::W0_5b => ("1.5", "0.5B"), WhichModel::W1_8b => ("1.5", "1.8B"), WhichModel::W4b => ("1.5", "4B"), WhichModel::W7b => ("1.5", "7B"), WhichModel::W14b => ("1.5", "14B"), WhichModel::W72b => ("1.5", "72B"), WhichModel::MoeA27b => ("1.5", "MoE-A2.7B"), WhichModel::W3_0_6b => ("3", "0.6B"), WhichModel::W3_1_7b => ("3", "1.7B"), WhichModel::W3_4b => ("3", "4B"), WhichModel::W3_8b => ("3", "8B"), WhichModel::W3MoeA3b => ("3", "30B-A3B"), }; format!("Qwen/Qwen{version}-{size}") } }; let repo = api.repo(Repo::with_revision( model_id, RepoType::Model, args.revision, )); let tokenizer_filename = match args.tokenizer_file { Some(file) => std::path::PathBuf::from(file), None => repo.get("tokenizer.json")?, }; let filenames = match args.weight_files { Some(files) => files .split(',') .map(std::path::PathBuf::from) .collect::<Vec<_>>(), None => match args.model { WhichModel::W0_5b | WhichModel::W2_0_5b | WhichModel::W2_1_5b | WhichModel::W1_8b | WhichModel::W3_0_6b => { vec![repo.get("model.safetensors")?] } WhichModel::W4b | WhichModel::W7b | WhichModel::W2_7b | WhichModel::W14b | WhichModel::W72b | WhichModel::W2_72b | WhichModel::MoeA27b | WhichModel::W3_1_7b | WhichModel::W3_4b | WhichModel::W3_8b | WhichModel::W3MoeA3b => { candle_examples::hub_load_safetensors(&repo, "model.safetensors.index.json")? } }, }; println!("retrieved the files in {:?}", start.elapsed()); let tokenizer = Tokenizer::from_file(tokenizer_filename).map_err(E::msg)?; let start = std::time::Instant::now(); let config_file = repo.get("config.json")?; let device = candle_examples::device(args.cpu)?; let dtype = if device.is_cuda() || device.is_metal() { DType::BF16 } else { DType::F32 }; let vb = unsafe { VarBuilder::from_mmaped_safetensors(&filenames, dtype, &device)? }; let model = match args.model { WhichModel::MoeA27b => { let config: ConfigMoe = serde_json::from_slice(&std::fs::read(config_file)?)?; Model::Moe(ModelMoe::new(&config, vb)?) } WhichModel::W3_0_6b | WhichModel::W3_1_7b | WhichModel::W3_4b | WhichModel::W3_8b => { let config: Config3 = serde_json::from_slice(&std::fs::read(config_file)?)?; Model::Base3(Model3::new(&config, vb)?) } WhichModel::W3MoeA3b => { let config: ConfigMoe3 = serde_json::from_slice(&std::fs::read(config_file)?)?; Model::Moe3(ModelMoe3::new(&config, vb)?) } _ => { let config: ConfigBase = serde_json::from_slice(&std::fs::read(config_file)?)?; Model::Base(ModelBase::new(&config, vb)?) } }; println!("loaded the model in {:?}", start.elapsed()); let mut pipeline = TextGeneration::new( model, tokenizer, args.seed, args.temperature, args.top_p, args.repeat_penalty, args.repeat_last_n, &device, ); pipeline.run(&args.prompt, args.sample_len)?; Ok(()) }
candle/candle-examples/examples/qwen/main.rs/0
{ "file_path": "candle/candle-examples/examples/qwen/main.rs", "repo_id": "candle", "token_count": 5862 }
41
# This script exports pre-trained model weights in the safetensors format. import numpy as np import torch import torchvision from safetensors import torch as stt m = torchvision.models.resnet50(pretrained=True) stt.save_file(m.state_dict(), 'resnet50.safetensors') m = torchvision.models.resnet101(pretrained=True) stt.save_file(m.state_dict(), 'resnet101.safetensors') m = torchvision.models.resnet152(pretrained=True) stt.save_file(m.state_dict(), 'resnet152.safetensors')
candle/candle-examples/examples/resnet/export_models.py/0
{ "file_path": "candle/candle-examples/examples/resnet/export_models.py", "repo_id": "candle", "token_count": 166 }
42
use anyhow::{Context, Result}; use std::sync::{Arc, Mutex}; pub const SAMPLE_RATE: usize = 24_000; pub(crate) struct AudioOutputData_ { resampled_data: std::collections::VecDeque<f32>, resampler: rubato::FastFixedIn<f32>, output_buffer: Vec<f32>, input_buffer: Vec<f32>, input_len: usize, } impl AudioOutputData_ { pub(crate) fn new(input_sample_rate: usize, output_sample_rate: usize) -> Result<Self> { use rubato::Resampler; let resampled_data = std::collections::VecDeque::with_capacity(output_sample_rate * 10); let resample_ratio = output_sample_rate as f64 / input_sample_rate as f64; let resampler = rubato::FastFixedIn::new( resample_ratio, f64::max(resample_ratio, 1.0), rubato::PolynomialDegree::Septic, 1024, 1, )?; let input_buffer = resampler.input_buffer_allocate(true).remove(0); let output_buffer = resampler.output_buffer_allocate(true).remove(0); Ok(Self { resampled_data, resampler, input_buffer, output_buffer, input_len: 0, }) } pub fn reset(&mut self) { use rubato::Resampler; self.output_buffer.fill(0.); self.input_buffer.fill(0.); self.resampler.reset(); self.resampled_data.clear(); } pub(crate) fn take_all(&mut self) -> Vec<f32> { let mut data = Vec::with_capacity(self.resampled_data.len()); while let Some(elem) = self.resampled_data.pop_back() { data.push(elem); } data } pub(crate) fn is_empty(&self) -> bool { self.resampled_data.is_empty() } // Assumes that the input buffer is large enough. fn push_input_buffer(&mut self, samples: &[f32]) { self.input_buffer[self.input_len..self.input_len + samples.len()].copy_from_slice(samples); self.input_len += samples.len() } pub(crate) fn push_samples(&mut self, samples: &[f32]) -> Result<()> { use rubato::Resampler; let mut pos_in = 0; loop { let rem = self.input_buffer.len() - self.input_len; let pos_end = usize::min(pos_in + rem, samples.len()); self.push_input_buffer(&samples[pos_in..pos_end]); pos_in = pos_end; if self.input_len < self.input_buffer.len() { break; } let (_, out_len) = self.resampler.process_into_buffer( &[&self.input_buffer], &mut [&mut self.output_buffer], None, )?; for &elem in self.output_buffer[..out_len].iter() { self.resampled_data.push_front(elem) } self.input_len = 0; } Ok(()) } } type AudioOutputData = Arc<Mutex<AudioOutputData_>>; pub(crate) fn setup_output_stream() -> Result<(cpal::Stream, AudioOutputData)> { use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; println!("Setup audio output stream!"); let host = cpal::default_host(); let device = host .default_output_device() .context("no output device available")?; let mut supported_configs_range = device.supported_output_configs()?; let config_range = match supported_configs_range.find(|c| c.channels() == 1) { // On macOS, it's commonly the case that there are only stereo outputs. None => device .supported_output_configs()? .next() .context("no audio output available")?, Some(config_range) => config_range, }; let sample_rate = cpal::SampleRate(SAMPLE_RATE as u32).clamp( config_range.min_sample_rate(), config_range.max_sample_rate(), ); let config: cpal::StreamConfig = config_range.with_sample_rate(sample_rate).into(); let channels = config.channels as usize; println!( "cpal device: {} {} {config:?}", device.name().unwrap_or_else(|_| "unk".to_string()), config.sample_rate.0 ); let audio_data = Arc::new(Mutex::new(AudioOutputData_::new( SAMPLE_RATE, config.sample_rate.0 as usize, )?)); let ad = audio_data.clone(); let stream = device.build_output_stream( &config, move |data: &mut [f32], _: &cpal::OutputCallbackInfo| { data.fill(0.); let mut ad = ad.lock().unwrap(); let mut last_elem = 0f32; for (idx, elem) in data.iter_mut().enumerate() { if idx % channels == 0 { match ad.resampled_data.pop_back() { None => break, Some(v) => { last_elem = v; *elem = v } } } else { *elem = last_elem } } }, move |err| eprintln!("cpal error: {err}"), None, // None=blocking, Some(Duration)=timeout )?; stream.play()?; Ok((stream, audio_data)) } pub(crate) fn setup_input_stream() -> Result<(cpal::Stream, AudioOutputData)> { use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; println!("Setup audio input stream!"); let host = cpal::default_host(); let device = host .default_input_device() .context("no input device available")?; let mut supported_configs_range = device.supported_input_configs()?; let config_range = supported_configs_range .find(|c| c.channels() == 1) .context("no audio input available")?; let sample_rate = cpal::SampleRate(SAMPLE_RATE as u32).clamp( config_range.min_sample_rate(), config_range.max_sample_rate(), ); let config: cpal::StreamConfig = config_range.with_sample_rate(sample_rate).into(); println!( "cpal device: {} {} {config:?}", device.name().unwrap_or_else(|_| "unk".to_string()), config.sample_rate.0 ); let audio_data = Arc::new(Mutex::new(AudioOutputData_::new( config.sample_rate.0 as usize, SAMPLE_RATE, )?)); let ad = audio_data.clone(); let stream = device.build_input_stream( &config, move |data: &[f32], _: &cpal::InputCallbackInfo| { let mut ad = ad.lock().unwrap(); if let Err(err) = ad.push_samples(data) { eprintln!("error processing audio input {err:?}") } }, move |err| eprintln!("cpal error: {err}"), None, // None=blocking, Some(Duration)=timeout )?; stream.play()?; Ok((stream, audio_data)) } fn conv<T>(samples: &mut Vec<f32>, data: std::borrow::Cow<symphonia::core::audio::AudioBuffer<T>>) where T: symphonia::core::sample::Sample, f32: symphonia::core::conv::FromSample<T>, { use symphonia::core::audio::Signal; use symphonia::core::conv::FromSample; samples.extend(data.chan(0).iter().map(|v| f32::from_sample(*v))) } pub(crate) fn pcm_decode<P: AsRef<std::path::Path>>(path: P) -> Result<(Vec<f32>, u32)> { use symphonia::core::audio::{AudioBufferRef, Signal}; let src = std::fs::File::open(path)?; let mss = symphonia::core::io::MediaSourceStream::new(Box::new(src), Default::default()); let hint = symphonia::core::probe::Hint::new(); let meta_opts: symphonia::core::meta::MetadataOptions = Default::default(); let fmt_opts: symphonia::core::formats::FormatOptions = Default::default(); let probed = symphonia::default::get_probe().format(&hint, mss, &fmt_opts, &meta_opts)?; let mut format = probed.format; let track = format .tracks() .iter() .find(|t| t.codec_params.codec != symphonia::core::codecs::CODEC_TYPE_NULL) .expect("no supported audio tracks"); let mut decoder = symphonia::default::get_codecs() .make(&track.codec_params, &Default::default()) .expect("unsupported codec"); let track_id = track.id; let sample_rate = track.codec_params.sample_rate.unwrap_or(0); let mut pcm_data = Vec::new(); while let Ok(packet) = format.next_packet() { while !format.metadata().is_latest() { format.metadata().pop(); } if packet.track_id() != track_id { continue; } match decoder.decode(&packet)? { AudioBufferRef::F32(buf) => pcm_data.extend(buf.chan(0)), AudioBufferRef::U8(data) => conv(&mut pcm_data, data), AudioBufferRef::U16(data) => conv(&mut pcm_data, data), AudioBufferRef::U24(data) => conv(&mut pcm_data, data), AudioBufferRef::U32(data) => conv(&mut pcm_data, data), AudioBufferRef::S8(data) => conv(&mut pcm_data, data), AudioBufferRef::S16(data) => conv(&mut pcm_data, data), AudioBufferRef::S24(data) => conv(&mut pcm_data, data), AudioBufferRef::S32(data) => conv(&mut pcm_data, data), AudioBufferRef::F64(data) => conv(&mut pcm_data, data), } } Ok((pcm_data, sample_rate)) }
candle/candle-examples/examples/snac/audio_io.rs/0
{ "file_path": "candle/candle-examples/examples/snac/audio_io.rs", "repo_id": "candle", "token_count": 4299 }
43
#[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; use anyhow::{Error as E, Result}; use clap::Parser; use candle_transformers::models::starcoder2::Model; use candle::{DType, Device, Tensor}; use candle_examples::token_output_stream::TokenOutputStream; use candle_nn::VarBuilder; use candle_transformers::generation::LogitsProcessor; use hf_hub::{api::sync::Api, Repo, RepoType}; use tokenizers::Tokenizer; struct TextGeneration { model: Model, device: Device, tokenizer: TokenOutputStream, logits_processor: LogitsProcessor, repeat_penalty: f32, repeat_last_n: usize, } impl TextGeneration { #[allow(clippy::too_many_arguments)] fn new( model: Model, tokenizer: Tokenizer, seed: u64, temp: Option<f64>, top_p: Option<f64>, repeat_penalty: f32, repeat_last_n: usize, device: &Device, ) -> Self { let logits_processor = LogitsProcessor::new(seed, temp, top_p); Self { model, tokenizer: TokenOutputStream::new(tokenizer), logits_processor, repeat_penalty, repeat_last_n, device: device.clone(), } } fn run(&mut self, prompt: &str, sample_len: usize) -> Result<()> { use std::io::Write; self.tokenizer.clear(); let mut tokens = self .tokenizer .tokenizer() .encode(prompt, true) .map_err(E::msg)? .get_ids() .to_vec(); for &t in tokens.iter() { if let Some(t) = self.tokenizer.next_token(t)? { print!("{t}") } } std::io::stdout().flush()?; let mut generated_tokens = 0usize; let eos_token = match self.tokenizer.get_token("<|endoftext|>") { Some(token) => token, None => anyhow::bail!("cannot find the <|endoftext|> token"), }; let start_gen = std::time::Instant::now(); for index in 0..sample_len { let context_size = if index > 0 { 1 } else { tokens.len() }; let start_pos = tokens.len().saturating_sub(context_size); let ctxt = &tokens[start_pos..]; let input = Tensor::new(ctxt, &self.device)?.unsqueeze(0)?; let logits = self.model.forward(&input, start_pos)?; let logits = logits.squeeze(0)?.squeeze(0)?.to_dtype(DType::F32)?; let logits = if self.repeat_penalty == 1. { logits } else { let start_at = tokens.len().saturating_sub(self.repeat_last_n); candle_transformers::utils::apply_repeat_penalty( &logits, self.repeat_penalty, &tokens[start_at..], )? }; let next_token = self.logits_processor.sample(&logits)?; tokens.push(next_token); generated_tokens += 1; if next_token == eos_token { break; } if let Some(t) = self.tokenizer.next_token(next_token)? { print!("{t}"); std::io::stdout().flush()?; } } let dt = start_gen.elapsed(); if let Some(rest) = self.tokenizer.decode_rest().map_err(E::msg)? { print!("{rest}"); } std::io::stdout().flush()?; println!( "\n{generated_tokens} tokens generated ({:.2} token/s)", generated_tokens as f64 / dt.as_secs_f64(), ); Ok(()) } } #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] struct Args { /// Run on CPU rather than on GPU. #[arg(long)] cpu: bool, /// Enable tracing (generates a trace-timestamp.json file). #[arg(long)] tracing: bool, #[arg(long)] use_flash_attn: bool, #[arg(long)] prompt: String, /// The temperature used to generate samples. #[arg(long)] temperature: Option<f64>, /// Nucleus sampling probability cutoff. #[arg(long)] top_p: Option<f64>, /// The seed to use when generating random samples. #[arg(long, default_value_t = 299792458)] seed: u64, /// The length of the sample to generate (in tokens). #[arg(long, short = 'n', default_value_t = 10000)] sample_len: usize, #[arg(long)] model_id: Option<String>, #[arg(long, default_value = "main")] revision: String, #[arg(long)] config_file: Option<String>, #[arg(long)] tokenizer_file: Option<String>, #[arg(long)] weight_files: Option<String>, /// Penalty to be applied for repeating tokens, 1. means no penalty. #[arg(long, default_value_t = 1.1)] repeat_penalty: f32, /// The context size to consider for the repeat penalty. #[arg(long, default_value_t = 64)] repeat_last_n: usize, } fn main() -> Result<()> { use tracing_chrome::ChromeLayerBuilder; use tracing_subscriber::prelude::*; let args = Args::parse(); let _guard = if args.tracing { let (chrome_layer, guard) = ChromeLayerBuilder::new().build(); tracing_subscriber::registry().with(chrome_layer).init(); Some(guard) } else { None }; println!( "avx: {}, neon: {}, simd128: {}, f16c: {}", candle::utils::with_avx(), candle::utils::with_neon(), candle::utils::with_simd128(), candle::utils::with_f16c() ); println!( "temp: {:.2} repeat-penalty: {:.2} repeat-last-n: {}", args.temperature.unwrap_or(0.), args.repeat_penalty, args.repeat_last_n ); let start = std::time::Instant::now(); let api = Api::new()?; let model_id = match args.model_id { Some(model_id) => model_id, None => "bigcode/starcoder2-3b".to_string(), }; let repo = api.repo(Repo::with_revision( model_id, RepoType::Model, args.revision, )); let config_file = match args.config_file { Some(file) => std::path::PathBuf::from(file), None => repo.get("config.json")?, }; let tokenizer_file = match args.tokenizer_file { Some(file) => std::path::PathBuf::from(file), None => repo.get("tokenizer.json")?, }; let filenames = match args.weight_files { Some(files) => files .split(',') .map(std::path::PathBuf::from) .collect::<Vec<_>>(), None => vec![repo.get("model.safetensors")?], }; println!("retrieved the files in {:?}", start.elapsed()); let tokenizer = Tokenizer::from_file(tokenizer_file).map_err(E::msg)?; let start = std::time::Instant::now(); let config = serde_json::from_reader(std::fs::File::open(config_file)?)?; let device = candle_examples::device(args.cpu)?; let dtype = if device.is_cuda() { DType::BF16 } else { DType::F32 }; let vb = unsafe { VarBuilder::from_mmaped_safetensors(&filenames, dtype, &device)? }; let model = Model::new(&config, vb)?; println!("loaded the model in {:?}", start.elapsed()); let mut pipeline = TextGeneration::new( model, tokenizer, args.seed, args.temperature, args.top_p, args.repeat_penalty, args.repeat_last_n, &device, ); pipeline.run(&args.prompt, args.sample_len)?; Ok(()) }
candle/candle-examples/examples/starcoder2/main.rs/0
{ "file_path": "candle/candle-examples/examples/starcoder2/main.rs", "repo_id": "candle", "token_count": 3545 }
44
use anyhow::{Context, Result}; use clap::Parser; use hf_hub::api::sync::Api; use model::VoxtralModel; mod download; mod model; #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] struct Args { /// Run on CPU rather than on GPU. #[arg(long, default_value_t = false)] cpu: bool, /// The input to be processed, in wav format, will default to `jfk.wav`. Alternatively /// this can be set to sample:jfk, sample:gb1, ... to fetch a sample from the following /// repo: https://huggingface.co/datasets/Narsil/candle_demo/ #[arg(long)] input: Option<String>, #[arg(long, default_value = "mistralai/Voxtral-Mini-3B-2507")] model_id: Option<String>, } #[cfg(feature = "cuda")] fn use_cpu() -> bool { true } #[cfg(not(feature = "cuda"))] fn use_cpu() -> bool { false } fn main() -> Result<()> { let args = Args::parse(); let use_cpu = args.cpu || !use_cpu(); let model_id = args.model_id.unwrap(); // Create model - equivalent to loading the model and processor in Python let mut model = VoxtralModel::new(&model_id, use_cpu).context("Failed to load Voxtral model")?; println!("Model loaded successfully on device: {:?}", model.device()); let api = Api::new()?; let dataset = api.dataset("Narsil/candle-examples".to_string()); let audio_file = if let Some(input) = args.input { if let Some(sample) = input.strip_prefix("sample:") { dataset.get(&format!("samples_{sample}.wav"))? } else { std::path::PathBuf::from(input) } } else { println!("No audio file submitted: Downloading https://huggingface.co/datasets/Narsil/candle_demo/blob/main/samples_jfk.wav"); dataset.get("samples_jfk.wav")? }; let (audio_data, sample_rate) = candle_examples::audio::pcm_decode(audio_file).context("Failed to decode audio file")?; // Transcribe audio with token output let result = model .transcribe_audio(&audio_data, sample_rate) .context("Failed to transcribe audio with tokens")?; println!("\n===================================================\n"); println!("{}", result.text); Ok(()) }
candle/candle-examples/examples/voxtral/main.rs/0
{ "file_path": "candle/candle-examples/examples/voxtral/main.rs", "repo_id": "candle", "token_count": 874 }
45
use std::path::PathBuf; use anyhow::{Error as E, Result}; use candle::{Device, Tensor}; use candle_nn::ops::softmax; use candle_nn::VarBuilder; use candle_transformers::models::xlm_roberta::{ Config, XLMRobertaForMaskedLM, XLMRobertaForSequenceClassification, }; use clap::{Parser, ValueEnum}; use hf_hub::{api::sync::Api, Repo, RepoType}; use tokenizers::{PaddingParams, Tokenizer}; #[derive(Debug, Clone, ValueEnum)] enum Model { BgeRerankerBase, BgeRerankerLarge, BgeRerankerBaseV2, XLMRobertaBase, XLMRobertaLarge, XLMRFormalityClassifier, } #[derive(Debug, Clone, ValueEnum)] enum Task { FillMask, Reranker, TextClassification, } #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] struct Args { /// Run on CPU rather than on GPU. #[arg(long)] cpu: bool, /// Enable tracing (generates a trace-timestamp.json file). #[arg(long)] tracing: bool, /// The model to use, check out available models: https://huggingface.co/models?library=sentence-transformers&sort=trending #[arg(long)] model_id: Option<String>, #[arg(long, default_value = "main")] revision: String, #[arg(long, default_value = "bge-reranker-base")] model: Model, #[arg(long, default_value = "reranker")] task: Task, // Path to the tokenizer file. #[arg(long)] tokenizer_file: Option<String>, // Path to the weight files. #[arg(long)] weight_files: Option<String>, // Path to the config file. #[arg(long)] config_file: Option<String>, /// When set, compute embeddings for this prompt. #[arg(long)] prompt: Option<String>, } fn main() -> Result<()> { let args = Args::parse(); let api = Api::new()?; let model_id = match &args.model_id { Some(model_id) => model_id.to_string(), None => match args.task { Task::FillMask => match args.model { Model::XLMRobertaBase => "FacebookAI/xlm-roberta-base".to_string(), Model::XLMRobertaLarge => "FacebookAI/xlm-roberta-large".to_string(), _ => anyhow::bail!("BGE models are not supported for fill-mask task"), }, Task::Reranker => match args.model { Model::BgeRerankerBase => "BAAI/bge-reranker-base".to_string(), Model::BgeRerankerLarge => "BAAI/bge-reranker-large".to_string(), Model::BgeRerankerBaseV2 => "BAAI/bge-reranker-base-v2-m3".to_string(), _ => anyhow::bail!("XLM-RoBERTa models are not supported for reranker task"), }, Task::TextClassification => match args.model { Model::XLMRFormalityClassifier => "s-nlp/xlmr_formality_classifier".to_string(), _ => anyhow::bail!( "XLM-RoBERTa models are not supported for text classification task" ), }, }, }; let repo = api.repo(Repo::with_revision( model_id, RepoType::Model, args.revision, )); let tokenizer_filename = match args.tokenizer_file { Some(file) => std::path::PathBuf::from(file), None => repo.get("tokenizer.json")?, }; let config_filename = match args.config_file { Some(file) => std::path::PathBuf::from(file), None => repo.get("config.json")?, }; let weights_filename = match args.weight_files { Some(files) => PathBuf::from(files), None => match repo.get("model.safetensors") { Ok(safetensors) => safetensors, Err(_) => match repo.get("pytorch_model.bin") { Ok(pytorch_model) => pytorch_model, Err(e) => { return Err(anyhow::Error::msg(format!("Model weights not found. The weights should either be a `model.safetensors` or `pytorch_model.bin` file. Error: {e}"))); } }, }, }; let config = std::fs::read_to_string(config_filename)?; let config: Config = serde_json::from_str(&config)?; let mut tokenizer = Tokenizer::from_file(tokenizer_filename).map_err(E::msg)?; let device = candle_examples::device(args.cpu)?; let vb = if weights_filename.ends_with("model.safetensors") { unsafe { VarBuilder::from_mmaped_safetensors(&[weights_filename], candle::DType::F16, &device) .unwrap() } } else { println!("Loading weights from pytorch_model.bin"); VarBuilder::from_pth(&weights_filename, candle::DType::F16, &device).unwrap() }; tokenizer .with_padding(Some(PaddingParams { strategy: tokenizers::PaddingStrategy::BatchLongest, pad_id: config.pad_token_id, ..Default::default() })) .with_truncation(None) .map_err(E::msg)?; match args.task { Task::FillMask => { let prompt = vec![ "Hello I'm a <mask> model.".to_string(), "I'm a <mask> boy.".to_string(), "I'm <mask> in berlin.".to_string(), ]; let model = XLMRobertaForMaskedLM::new(&config, vb)?; let input_ids = tokenize_batch(&tokenizer, TokenizeInput::Single(&prompt), &device)?; let attention_mask = get_attention_mask(&tokenizer, TokenizeInput::Single(&prompt), &device)?; let token_type_ids = Tensor::zeros(input_ids.dims(), input_ids.dtype(), &device)?; let output = model .forward( &input_ids, &attention_mask, &token_type_ids, None, None, None, )? .to_dtype(candle::DType::F32)?; let max_outs = output.argmax(2)?; let max_out = max_outs.to_vec2::<u32>()?; let max_out_refs: Vec<&[u32]> = max_out.iter().map(|v| v.as_slice()).collect(); let decoded = tokenizer.decode_batch(&max_out_refs, true).unwrap(); for (i, sentence) in decoded.iter().enumerate() { println!("Sentence: {} : {}", i + 1, sentence); } } Task::Reranker => { let query = "what is panda?".to_string(); let documents = ["South Korea is a country in East Asia.".to_string(), "There are forests in the mountains.".to_string(), "Pandas look like bears.".to_string(), "There are some animals with black and white fur.".to_string(), "The giant panda (Ailuropoda melanoleuca), sometimes called a panda bear or simply panda, is a bear species endemic to China.".to_string()]; // create pairs of query and documents let pairs = documents .iter() .map(|doc| (query.clone(), doc.clone())) .collect::<Vec<_>>(); let input_ids = tokenize_batch(&tokenizer, TokenizeInput::Pairs(&pairs), &device)?; let attention_mask = get_attention_mask(&tokenizer, TokenizeInput::Pairs(&pairs), &device)?; let token_type_ids = Tensor::zeros(input_ids.dims(), input_ids.dtype(), &device)?; let model = XLMRobertaForSequenceClassification::new(1, &config, vb)?; let output = model.forward(&input_ids, &attention_mask, &token_type_ids)?; let output = candle_nn::ops::sigmoid(&output)?.t().unwrap(); let ranks = output .arg_sort_last_dim(false)? .to_vec2::<u32>()? .into_iter() .flatten() .collect::<Vec<_>>(); println!("\nRanking Results:"); println!("{:-<80}", ""); documents.iter().enumerate().for_each(|(idx, doc)| { let rank = ranks.iter().position(|&r| r == idx as u32).unwrap(); let score = output .get_on_dim(1, idx) .unwrap() .to_dtype(candle::DType::F32) .unwrap() .to_vec1::<f32>() .unwrap(); println!("Rank #{:<2} | Score: {:.4} | {}", rank + 1, score[0], doc); }); println!("{:-<80}", ""); } Task::TextClassification => { let sentences = vec![ "I like you. I love you".to_string(), "Hey, what's up?".to_string(), "Siema, co porabiasz?".to_string(), "I feel deep regret and sadness about the situation in international politics." .to_string(), ]; let model = XLMRobertaForSequenceClassification::new(2, &config, vb)?; let input_ids = tokenize_batch(&tokenizer, TokenizeInput::Single(&sentences), &device)?; let attention_mask = get_attention_mask(&tokenizer, TokenizeInput::Single(&sentences), &device)?; let token_type_ids = Tensor::zeros(input_ids.dims(), input_ids.dtype(), &device)?; let logits = model .forward(&input_ids, &attention_mask, &token_type_ids)? .to_dtype(candle::DType::F32)?; let probabilities = softmax(&logits, 1)?; let probs_vec = probabilities.to_vec2::<f32>()?; println!("Formality Scores:"); for (i, (text, probs)) in sentences.iter().zip(probs_vec.iter()).enumerate() { println!("Text {}: \"{}\"", i + 1, text); println!(" formal: {:.4}", probs[0]); println!(" informal: {:.4}", probs[1]); println!(); } } } Ok(()) } #[derive(Debug)] pub enum TokenizeInput<'a> { Single(&'a [String]), Pairs(&'a [(String, String)]), } pub fn tokenize_batch( tokenizer: &Tokenizer, input: TokenizeInput, device: &Device, ) -> anyhow::Result<Tensor> { let tokens = match input { TokenizeInput::Single(text_batch) => tokenizer .encode_batch(text_batch.to_vec(), true) .map_err(E::msg)?, TokenizeInput::Pairs(pairs) => tokenizer .encode_batch(pairs.to_vec(), true) .map_err(E::msg)?, }; let token_ids = tokens .iter() .map(|tokens| { let tokens = tokens.get_ids().to_vec(); Tensor::new(tokens.as_slice(), device) }) .collect::<candle::Result<Vec<_>>>()?; Ok(Tensor::stack(&token_ids, 0)?) } pub fn get_attention_mask( tokenizer: &Tokenizer, input: TokenizeInput, device: &Device, ) -> anyhow::Result<Tensor> { let tokens = match input { TokenizeInput::Single(text_batch) => tokenizer .encode_batch(text_batch.to_vec(), true) .map_err(E::msg)?, TokenizeInput::Pairs(pairs) => tokenizer .encode_batch(pairs.to_vec(), true) .map_err(E::msg)?, }; let attention_mask = tokens .iter() .map(|tokens| { let tokens = tokens.get_attention_mask().to_vec(); Tensor::new(tokens.as_slice(), device) }) .collect::<candle::Result<Vec<_>>>()?; Ok(Tensor::stack(&attention_mask, 0)?) }
candle/candle-examples/examples/xlm-roberta/main.rs/0
{ "file_path": "candle/candle-examples/examples/xlm-roberta/main.rs", "repo_id": "candle", "token_count": 5543 }
46
use candle::{Result, Tensor}; // https://github.com/facebookresearch/audiocraft/blob/69fea8b290ad1b4b40d28f92d1dfc0ab01dbab85/audiocraft/data/audio_utils.py#L57 pub fn normalize_loudness( wav: &Tensor, sample_rate: u32, loudness_compressor: bool, ) -> Result<Tensor> { let energy = wav.sqr()?.mean_all()?.sqrt()?.to_vec0::<f32>()?; if energy < 2e-3 { return Ok(wav.clone()); } let wav_array = wav.to_vec1::<f32>()?; let mut meter = crate::bs1770::ChannelLoudnessMeter::new(sample_rate); meter.push(wav_array.into_iter()); let power = meter.as_100ms_windows(); let loudness = match crate::bs1770::gated_mean(power) { None => return Ok(wav.clone()), Some(gp) => gp.loudness_lkfs() as f64, }; let delta_loudness = -14. - loudness; let gain = 10f64.powf(delta_loudness / 20.); let wav = (wav * gain)?; if loudness_compressor { wav.tanh() } else { Ok(wav) } } #[cfg(feature = "symphonia")] pub fn pcm_decode<P: AsRef<std::path::Path>>(path: P) -> Result<(Vec<f32>, u32)> { use symphonia::core::audio::{AudioBufferRef, Signal}; use symphonia::core::codecs::{DecoderOptions, CODEC_TYPE_NULL}; use symphonia::core::conv::FromSample; fn conv<T>( samples: &mut Vec<f32>, data: std::borrow::Cow<symphonia::core::audio::AudioBuffer<T>>, ) where T: symphonia::core::sample::Sample, f32: symphonia::core::conv::FromSample<T>, { samples.extend(data.chan(0).iter().map(|v| f32::from_sample(*v))) } // Open the media source. let src = std::fs::File::open(path).map_err(candle::Error::wrap)?; // Create the media source stream. let mss = symphonia::core::io::MediaSourceStream::new(Box::new(src), Default::default()); // Create a probe hint using the file's extension. [Optional] let hint = symphonia::core::probe::Hint::new(); // Use the default options for metadata and format readers. let meta_opts: symphonia::core::meta::MetadataOptions = Default::default(); let fmt_opts: symphonia::core::formats::FormatOptions = Default::default(); // Probe the media source. let probed = symphonia::default::get_probe() .format(&hint, mss, &fmt_opts, &meta_opts) .map_err(candle::Error::wrap)?; // Get the instantiated format reader. let mut format = probed.format; // Find the first audio track with a known (decodeable) codec. let track = format .tracks() .iter() .find(|t| t.codec_params.codec != CODEC_TYPE_NULL) .ok_or_else(|| candle::Error::Msg("no supported audio tracks".to_string()))?; // Use the default options for the decoder. let dec_opts: DecoderOptions = Default::default(); // Create a decoder for the track. let mut decoder = symphonia::default::get_codecs() .make(&track.codec_params, &dec_opts) .map_err(|_| candle::Error::Msg("unsupported codec".to_string()))?; let track_id = track.id; let sample_rate = track.codec_params.sample_rate.unwrap_or(0); let mut pcm_data = Vec::new(); // The decode loop. while let Ok(packet) = format.next_packet() { // Consume any new metadata that has been read since the last packet. while !format.metadata().is_latest() { format.metadata().pop(); } // If the packet does not belong to the selected track, skip over it. if packet.track_id() != track_id { continue; } match decoder.decode(&packet).map_err(candle::Error::wrap)? { AudioBufferRef::F32(buf) => pcm_data.extend(buf.chan(0)), AudioBufferRef::U8(data) => conv(&mut pcm_data, data), AudioBufferRef::U16(data) => conv(&mut pcm_data, data), AudioBufferRef::U24(data) => conv(&mut pcm_data, data), AudioBufferRef::U32(data) => conv(&mut pcm_data, data), AudioBufferRef::S8(data) => conv(&mut pcm_data, data), AudioBufferRef::S16(data) => conv(&mut pcm_data, data), AudioBufferRef::S24(data) => conv(&mut pcm_data, data), AudioBufferRef::S32(data) => conv(&mut pcm_data, data), AudioBufferRef::F64(data) => conv(&mut pcm_data, data), } } Ok((pcm_data, sample_rate)) } #[cfg(feature = "rubato")] pub fn resample(pcm_in: &[f32], sr_in: u32, sr_out: u32) -> Result<Vec<f32>> { use rubato::Resampler; let mut pcm_out = Vec::with_capacity((pcm_in.len() as f64 * sr_out as f64 / sr_in as f64) as usize + 1024); let mut resampler = rubato::FftFixedInOut::<f32>::new(sr_in as usize, sr_out as usize, 1024, 1) .map_err(candle::Error::wrap)?; let mut output_buffer = resampler.output_buffer_allocate(true); let mut pos_in = 0; while pos_in + resampler.input_frames_next() < pcm_in.len() { let (in_len, out_len) = resampler .process_into_buffer(&[&pcm_in[pos_in..]], &mut output_buffer, None) .map_err(candle::Error::wrap)?; pos_in += in_len; pcm_out.extend_from_slice(&output_buffer[0][..out_len]); } if pos_in < pcm_in.len() { let (_in_len, out_len) = resampler .process_partial_into_buffer(Some(&[&pcm_in[pos_in..]]), &mut output_buffer, None) .map_err(candle::Error::wrap)?; pcm_out.extend_from_slice(&output_buffer[0][..out_len]); } Ok(pcm_out) }
candle/candle-examples/src/audio.rs/0
{ "file_path": "candle/candle-examples/src/audio.rs", "repo_id": "candle", "token_count": 2409 }
47
/****************************************************************************** * Copyright (c) 2024, Tri Dao. ******************************************************************************/ #pragma once // #include "philox_unpack.cuh" // For at::cuda::philox::unpack #include <cute/tensor.hpp> #include <cutlass/cutlass.h> #include <cutlass/array.h> #include <cutlass/numeric_types.h> #include "block_info.h" #include "kernel_traits.h" #include "utils.h" #include "softmax.h" #include "mask.h" #include "dropout.h" #include "rotary.h" namespace flash { using namespace cute; //////////////////////////////////////////////////////////////////////////////////////////////////// template<typename ElementAccum, typename Params, int kBlockM, bool Is_even_MN> __forceinline__ __device__ auto get_lse_tile(const Params &params, const int bidb, const int bidh, const int m_block, const BlockInfo</*Varlen=*/!Is_even_MN> &binfo) { // When params.unpadded_lse is false, LSE is written as (b, h, seqlen_q) - this is non-variable seqlen path. // Otherwise, when params.seqlenq_ngroups_swapped is true, it is written as (h, seqlen_q, b) to account for seqlen_q <-> h swapping trick. // Otherwise, it's written as (h, b, seqlen_q). const bool varlen_q = params.unpadded_lse && !params.seqlenq_ngroups_swapped; auto lse_offset = varlen_q ? binfo.q_offset(params.seqlen_q, 1, bidb) : 0; auto gmem_ptr_lse = make_gmem_ptr(reinterpret_cast<ElementAccum*>(params.softmax_lse_ptr) + lse_offset); auto lse_shape = varlen_q ? make_shape(1, params.h, params.total_q) : make_shape(params.b, params.h, params.seqlen_q); auto lse_stride = params.seqlenq_ngroups_swapped ? make_stride(1, params.seqlen_q * params.b, params.b) : ( params.unpadded_lse ? make_stride(params.h * params.total_q, params.total_q, 1) : make_stride(params.h * params.seqlen_q, params.seqlen_q, 1) ); auto lse_layout = make_layout(lse_shape, lse_stride); Tensor mLSE = make_tensor(gmem_ptr_lse, lse_layout); auto mLSE_slice = varlen_q ? mLSE(0, bidh, _) : mLSE(bidb, bidh, _); return local_tile(mLSE_slice, Shape<Int<kBlockM>>{}, make_coord(m_block)); } template<typename Kernel_traits, bool Is_dropout, bool Is_causal, bool Is_local, bool Has_alibi, bool Is_even_MN, bool Is_even_K, bool Is_softcap, bool Return_softmax, typename Params> inline __device__ void compute_attn_1rowblock(const Params &params, const int bidb, const int bidh, const int m_block) { using Element = typename Kernel_traits::Element; using ElementAccum = typename Kernel_traits::ElementAccum; using index_t = typename Kernel_traits::index_t; // Shared memory. extern __shared__ char smem_[]; // The thread index. const int tidx = threadIdx.x; constexpr int kBlockM = Kernel_traits::kBlockM; constexpr int kBlockN = Kernel_traits::kBlockN; constexpr int kHeadDim = Kernel_traits::kHeadDim; constexpr int kNWarps = Kernel_traits::kNWarps; auto seed_offset = std::make_tuple(0ull, 0ull); // auto seed_offset = at::cuda::philox::unpack(params.philox_args); flash::Dropout dropout(std::get<0>(seed_offset), std::get<1>(seed_offset), params.p_dropout_in_uint8_t, bidb, bidh, tidx, params.h); // Save seed and offset for backward, before any early exiting. Otherwise the 0-th thread block might // exit early and no one saves the rng states. if (Is_dropout && blockIdx.x == 0 && blockIdx.y == 0 && blockIdx.z == 0 && tidx == 0) { params.rng_state[0] = std::get<0>(seed_offset); params.rng_state[1] = std::get<1>(seed_offset); } const BlockInfo</*Varlen=*/!Is_even_MN> binfo(params, bidb); if (m_block * kBlockM >= binfo.actual_seqlen_q) return; const int n_block_min = !Is_local ? 0 : std::max(0, (m_block * kBlockM + binfo.actual_seqlen_k - binfo.actual_seqlen_q - params.window_size_left) / kBlockN); int n_block_max = cute::ceil_div(binfo.actual_seqlen_k, kBlockN); if (Is_causal || Is_local) { n_block_max = std::min(n_block_max, cute::ceil_div((m_block + 1) * kBlockM + binfo.actual_seqlen_k - binfo.actual_seqlen_q + params.window_size_right, kBlockN)); // if (threadIdx.x == 0 && blockIdx.y == 0 && blockIdx.z == 0) { // printf("m_block = %d, n_block_max = %d\n", m_block, n_block_max); // } } // We exit early and write 0 to gO and gLSE. This also covers the case where actual_seqlen_k == 0. // Otherwise we might read OOB elements from gK and gV. if ((Is_causal || Is_local || !Is_even_MN) && n_block_max <= n_block_min) { Tensor mO = make_tensor(make_gmem_ptr(reinterpret_cast<Element*>(params.o_ptr) + binfo.q_offset(params.o_batch_stride, params.o_row_stride, bidb)), make_shape(binfo.actual_seqlen_q, params.h, params.d), make_stride(params.o_row_stride, params.o_head_stride, _1{})); Tensor gO = local_tile(mO(_, bidh, _), Shape<Int<kBlockM>, Int<kHeadDim>>{}, make_coord(m_block, 0)); // (kBlockM, kHeadDim) Tensor gLSE = get_lse_tile<ElementAccum, Params, kBlockM, Is_even_MN>(params, bidb, bidh, m_block, binfo); typename Kernel_traits::GmemTiledCopyO gmem_tiled_copy_O; auto gmem_thr_copy_O = gmem_tiled_copy_O.get_thread_slice(tidx); Tensor tOgO = gmem_thr_copy_O.partition_D(gO); Tensor tOrO = make_tensor<Element>(shape(tOgO)); clear(tOrO); // Construct identity layout for sO Tensor cO = make_identity_tensor(make_shape(size<0>(gO), size<1>(gO))); // (BLK_M,BLK_K) -> (blk_m,blk_k) // Repeat the partitioning with identity layouts Tensor tOcO = gmem_thr_copy_O.partition_D(cO); Tensor tOpO = make_tensor<bool>(make_shape(size<2>(tOgO))); if (!Is_even_K) { #pragma unroll for (int k = 0; k < size(tOpO); ++k) { tOpO(k) = get<1>(tOcO(0, 0, k)) < params.d; } } // Clear_OOB_K must be false since we don't want to write zeros to gmem flash::copy<Is_even_MN, Is_even_K, /*Clear_OOB_MN=*/false, /*Clear_OOB_K=*/false>( gmem_tiled_copy_O, tOrO, tOgO, tOcO, tOpO, binfo.actual_seqlen_q - m_block * kBlockM ); #pragma unroll for (int m = 0; m < size<1>(tOgO); ++m) { const int row = get<0>(tOcO(0, m, 0)); if (row < binfo.actual_seqlen_q - m_block * kBlockM && get<1>(tOcO(0, m, 0)) == 0) { gLSE(row) = INFINITY; } } return; } // if (tidx == 0) { printf("m_block = %d, n_block_min = %d, n_block_max = %d\n", m_block, n_block_min, n_block_max); } // We iterate over the blocks in reverse order. This is because the last block is the only one // that needs masking when we read K and V from global memory. Moreover, iterating in reverse // might save us 1 register (we just need n_block instead of both n_block and n_block_max). const index_t row_offset_p = ((bidb * params.h + bidh) * params.seqlen_q_rounded + m_block * kBlockM) * params.seqlen_k_rounded + (n_block_max - 1) * kBlockN; Tensor mQ = make_tensor(make_gmem_ptr(reinterpret_cast<Element*>(params.q_ptr) + binfo.q_offset(params.q_batch_stride, params.q_row_stride, bidb)), make_shape(binfo.actual_seqlen_q, params.h, params.d), make_stride(params.q_row_stride, params.q_head_stride, _1{})); Tensor gQ = local_tile(mQ(_, bidh, _), Shape<Int<kBlockM>, Int<kHeadDim>>{}, make_coord(m_block, 0)); // (kBlockM, kHeadDim) Tensor mK = make_tensor(make_gmem_ptr(reinterpret_cast<Element*>(params.k_ptr) + binfo.k_offset(params.k_batch_stride, params.k_row_stride, bidb)), make_shape(binfo.actual_seqlen_k, params.h_k, params.d), make_stride(params.k_row_stride, params.k_head_stride, _1{})); Tensor gK = local_tile(mK(_, bidh / params.h_h_k_ratio, _), Shape<Int<kBlockN>, Int<kHeadDim>>{}, make_coord(_, 0)); // (kBlockN, kHeadDim, nblocksN) Tensor mV = make_tensor(make_gmem_ptr(reinterpret_cast<Element*>(params.v_ptr) + binfo.k_offset(params.v_batch_stride, params.v_row_stride, bidb)), make_shape(binfo.actual_seqlen_k, params.h_k, params.d), make_stride(params.v_row_stride, params.v_head_stride, _1{})); Tensor gV = local_tile(mV(_, bidh / params.h_h_k_ratio, _), Shape<Int<kBlockN>, Int<kHeadDim>>{}, make_coord(_, 0)); // (kBlockN, kHeadDim, nblocksN) Tensor gP = make_tensor(make_gmem_ptr(reinterpret_cast<Element *>(params.p_ptr) + row_offset_p), Shape<Int<kBlockM>, Int<kBlockN>>{}, make_stride(params.seqlen_k_rounded, _1{})); Tensor sQ = make_tensor(make_smem_ptr(reinterpret_cast<Element *>(smem_)), typename Kernel_traits::SmemLayoutQ{}); // Careful we're using the same smem for sQ and sK | sV if Share_Q_K_smem; Tensor sK = make_tensor(sQ.data() + (Kernel_traits::Share_Q_K_smem ? 0 : size(sQ)), typename Kernel_traits::SmemLayoutKV{}); Tensor sV = make_tensor(sK.data() + size(sK), typename Kernel_traits::SmemLayoutKV{}); Tensor sVt = make_tensor(sV.data(), typename Kernel_traits::SmemLayoutVtransposed{}); Tensor sVtNoSwizzle = make_tensor(sV.data().get(), typename Kernel_traits::SmemLayoutVtransposedNoSwizzle{}); typename Kernel_traits::GmemTiledCopyQKV gmem_tiled_copy_QKV; auto gmem_thr_copy_QKV = gmem_tiled_copy_QKV.get_thread_slice(tidx); Tensor tQgQ = gmem_thr_copy_QKV.partition_S(gQ); Tensor tQsQ = gmem_thr_copy_QKV.partition_D(sQ); Tensor tKgK = gmem_thr_copy_QKV.partition_S(gK); // (KCPY, KCPY_N, KCPY_K, nblocksN) Tensor tKsK = gmem_thr_copy_QKV.partition_D(sK); Tensor tVgV = gmem_thr_copy_QKV.partition_S(gV); // (VCPY, VCPY_N, VCPY_K, nblocksN) Tensor tVsV = gmem_thr_copy_QKV.partition_D(sV); typename Kernel_traits::TiledMma tiled_mma; auto thr_mma = tiled_mma.get_thread_slice(tidx); Tensor tSrQ = thr_mma.partition_fragment_A(sQ); // (MMA,MMA_M,MMA_K) Tensor tSrK = thr_mma.partition_fragment_B(sK); // (MMA,MMA_N,MMA_K) Tensor tOrVt = thr_mma.partition_fragment_B(sVtNoSwizzle); // (MMA, MMA_K,MMA_N) Tensor tSgS = thr_mma.partition_C(gP); Tensor acc_o = partition_fragment_C(tiled_mma, Shape<Int<kBlockM>, Int<kHeadDim>>{}); // MMA, MMA_M, MMA_K // // Copy Atom retiling // auto smem_tiled_copy_Q = make_tiled_copy_A(typename Kernel_traits::SmemCopyAtom{}, tiled_mma); auto smem_thr_copy_Q = smem_tiled_copy_Q.get_thread_slice(tidx); // if (cute::thread0()) {smem_thr_copy_Q.print_all();} Tensor tSsQ = smem_thr_copy_Q.partition_S(sQ); // if (cute::thread0()) {print(tSsQ.layout()); printf("\n");} auto smem_tiled_copy_K = make_tiled_copy_B(typename Kernel_traits::SmemCopyAtom{}, tiled_mma); auto smem_thr_copy_K = smem_tiled_copy_K.get_thread_slice(tidx); Tensor tSsK = smem_thr_copy_K.partition_S(sK); auto smem_tiled_copy_V = make_tiled_copy_B(typename Kernel_traits::SmemCopyAtomTransposed{}, tiled_mma); auto smem_thr_copy_V = smem_tiled_copy_V.get_thread_slice(tidx); Tensor tOsVt = smem_thr_copy_V.partition_S(sVt); // // PREDICATES // // // Allocate predicate tensors for m and n // Tensor tQpQ = make_tensor<bool>(make_shape(size<1>(tQsQ), size<2>(tQsQ)), Stride<_1,_0>{}); // Tensor tKVpKV = make_tensor<bool>(make_shape(size<1>(tKsK), size<2>(tKsK)), Stride<_1,_0>{}); // Construct identity layout for sQ and sK Tensor cQ = make_identity_tensor(make_shape(size<0>(sQ), size<1>(sQ))); // (BLK_M,BLK_K) -> (blk_m,blk_k) Tensor cKV = make_identity_tensor(make_shape(size<0>(sK), size<1>(sK))); // (BLK_N,BLK_K) -> (blk_n,blk_k) // Tensor tScQ = thr_mma.partition_A(cQ); // (MMA,MMA_M,MMA_K) // if (cute::thread0()) { // print(tScQ.layout()); printf("\n"); // for (int i = 0; i < size(tScQ); ++i) { // printf("%d ", get<0>(tScQ(i))); // } // printf("\n"); // for (int i = 0; i < size(tScQ); ++i) { // printf("%d ", get<1>(tScQ(i))); // } // printf("\n"); // } // Repeat the partitioning with identity layouts Tensor tQcQ = gmem_thr_copy_QKV.partition_S(cQ); // (ACPY,ACPY_M,ACPY_K) -> (blk_m,blk_k) Tensor tKVcKV = gmem_thr_copy_QKV.partition_S(cKV); // (BCPY,BCPY_N,BCPY_K) -> (blk_n,blk_k) // Allocate predicate tensors for k Tensor tQpQ = make_tensor<bool>(make_shape(size<2>(tQsQ))); Tensor tKVpKV = make_tensor<bool>(make_shape(size<2>(tKsK))); // Set predicates for k bounds if (!Is_even_K) { #pragma unroll for (int k = 0; k < size(tQpQ); ++k) { tQpQ(k) = get<1>(tQcQ(0, 0, k)) < params.d; } #pragma unroll for (int k = 0; k < size(tKVpKV); ++k) { tKVpKV(k) = get<1>(tKVcKV(0, 0, k)) < params.d; } } // Prologue // We don't need to clear the sQ smem tiles since we'll only write out the valid outputs flash::copy<Is_even_MN, Is_even_K>(gmem_tiled_copy_QKV, tQgQ, tQsQ, tQcQ, tQpQ, binfo.actual_seqlen_q - m_block * kBlockM); if (Kernel_traits::Is_Q_in_regs) { cute::cp_async_fence(); } // // if (cute::thread(1, 0)) { print(tQsQ); } // // Tensor sQNoSwizzle = make_tensor(make_smem_ptr(reinterpret_cast<Element *>(smem_)), typename Kernel_traits::SmemLayoutQNoSwizzle{}); // // if (cute::thread0()) { print(sQNoSwizzle); } if (Kernel_traits::Share_Q_K_smem) { flash::cp_async_wait<0>(); __syncthreads(); Tensor tSrQ_copy_view = smem_thr_copy_Q.retile_D(tSrQ); CUTE_STATIC_ASSERT_V(size<1>(tSsQ) == size<1>(tSrQ_copy_view)); // M cute::copy(smem_tiled_copy_Q, tSsQ, tSrQ_copy_view); __syncthreads(); } int n_block = n_block_max - 1; // We don't need to clear the sK smem tiles since we'll mask out the scores anyway. flash::copy<Is_even_MN, Is_even_K>(gmem_tiled_copy_QKV, tKgK(_, _, _, n_block), tKsK, tKVcKV, tKVpKV, binfo.actual_seqlen_k - n_block * kBlockN); cute::cp_async_fence(); // if (threadIdx.x == 0 && blockIdx.y == 0 && blockIdx.z < 2) { print(tKgK); } // __syncthreads(); if (Kernel_traits::Is_Q_in_regs && !Kernel_traits::Share_Q_K_smem) { flash::cp_async_wait<1>(); __syncthreads(); Tensor tSrQ_copy_view = smem_thr_copy_Q.retile_D(tSrQ); CUTE_STATIC_ASSERT_V(size<1>(tSsQ) == size<1>(tSrQ_copy_view)); // M cute::copy(smem_tiled_copy_Q, tSsQ, tSrQ_copy_view); } clear(acc_o); flash::Softmax<2 * size<1>(acc_o)> softmax; const float alibi_slope = !Has_alibi || params.alibi_slopes_ptr == nullptr ? 0.0f : reinterpret_cast<float *>(params.alibi_slopes_ptr)[bidb * params.alibi_slopes_batch_stride + bidh] / params.scale_softmax; flash::Mask<Is_causal, Is_local, Has_alibi> mask(binfo.actual_seqlen_k, binfo.actual_seqlen_q, params.window_size_left, params.window_size_right, alibi_slope); // For performance reason, we separate out two kinds of iterations: // those that need masking on S, and those that don't. // We need masking on S for the very last block when K and V has length not multiple of kBlockN. // We also need masking on S if it's causal, for the last ceil_div(kBlockM, kBlockN) blocks. // We will have at least 1 "masking" iteration. // If not even_N, then seqlen_k might end in the middle of a block. In that case we need to // mask 2 blocks (e.g. when kBlockM == kBlockN), not just 1. constexpr int n_masking_steps = (!Is_causal && !Is_local) ? 1 : ((Is_even_MN && Is_causal) ? cute::ceil_div(kBlockM, kBlockN) : cute::ceil_div(kBlockM, kBlockN) + 1); #pragma unroll for (int masking_step = 0; masking_step < n_masking_steps; ++masking_step, --n_block) { Tensor acc_s = partition_fragment_C(tiled_mma, Shape<Int<kBlockM>, Int<kBlockN>>{}); // (MMA=4, MMA_M, MMA_N) clear(acc_s); flash::cp_async_wait<0>(); __syncthreads(); // Advance gV if (masking_step > 0) { flash::copy</*Is_even_MN=*/true, Is_even_K>(gmem_tiled_copy_QKV, tVgV(_, _, _, n_block), tVsV, tKVcKV, tKVpKV); } else { // Clear the smem tiles to account for predicated off loads flash::copy<Is_even_MN, Is_even_K, /*Clear_OOB_MN=*/true>( gmem_tiled_copy_QKV, tVgV(_, _, _, n_block), tVsV, tKVcKV, tKVpKV, binfo.actual_seqlen_k - n_block * kBlockN ); } cute::cp_async_fence(); flash::gemm</*A_in_regs=*/Kernel_traits::Is_Q_in_regs>( acc_s, tSrQ, tSrK, tSsQ, tSsK, tiled_mma, smem_tiled_copy_Q, smem_tiled_copy_K, smem_thr_copy_Q, smem_thr_copy_K ); // if (cute::thread0()) { print(acc_s); } if constexpr (Is_softcap){ flash::apply_softcap(acc_s, params.softcap); } mask.template apply_mask<Is_causal, Is_even_MN>( acc_s, n_block * kBlockN, m_block * kBlockM + (tidx / 32) * 16 + (tidx % 32) / 4, kNWarps * 16 ); flash::cp_async_wait<0>(); __syncthreads(); if (n_block > n_block_min) { flash::copy</*Is_even_MN=*/true, Is_even_K>(gmem_tiled_copy_QKV, tKgK(_, _, _, n_block - 1), tKsK, tKVcKV, tKVpKV); // This cp_async_fence needs to be in the if block, otherwise the synchronization // isn't right and we get race conditions. cute::cp_async_fence(); } // TODO: when we have key_padding_mask we'll need to Check_inf masking_step == 0 ? softmax.template softmax_rescale_o</*Is_first=*/true, /*Check_inf=*/Is_causal || Is_local>(acc_s, acc_o, params.scale_softmax_log2) : softmax.template softmax_rescale_o</*Is_first=*/false, /*Check_inf=*/Is_causal || Is_local>(acc_s, acc_o, params.scale_softmax_log2); // Convert acc_s from fp32 to fp16/bf16 Tensor rP = flash::convert_type<Element>(acc_s); int block_row_idx = m_block * (kBlockM / 16) + tidx / 32; int block_col_idx = n_block * (kBlockN / 32); if (Return_softmax) { Tensor rP_drop = make_fragment_like(rP); cute::copy(rP, rP_drop); dropout.template apply_dropout</*encode_dropout_in_sign_bit=*/true>( rP_drop, block_row_idx, block_col_idx, kNWarps ); cute::copy(rP_drop, tSgS); tSgS.data() = tSgS.data() + (-kBlockN); } if (Is_dropout) { dropout.apply_dropout(rP, block_row_idx, block_col_idx, kNWarps); } // Reshape rP from (MMA=4, MMA_M, MMA_N) to ((4, 2), MMA_M, MMA_N / 2) // if using m16n8k16 or (4, MMA_M, MMA_N) if using m16n8k8. Tensor tOrP = make_tensor(rP.data(), flash::convert_layout_acc_Aregs<Kernel_traits::TiledMma>(rP.layout())); // if (cute::thread0()) { print(tOrP); } flash::gemm_rs(acc_o, tOrP, tOrVt, tOsVt, tiled_mma, smem_tiled_copy_V, smem_thr_copy_V); // if (cute::thread0()) { print(scores); } // This check is at the end of the loop since we always have at least 1 iteration if (n_masking_steps > 1 && n_block <= n_block_min) { --n_block; break; } } // These are the iterations where we don't need masking on S for (; n_block >= n_block_min; --n_block) { Tensor acc_s = partition_fragment_C(tiled_mma, Shape<Int<kBlockM>, Int<kBlockN>>{}); // (MMA=4, MMA_M, MMA_N) clear(acc_s); flash::cp_async_wait<0>(); __syncthreads(); flash::copy</*Is_even_MN=*/true, Is_even_K>(gmem_tiled_copy_QKV, tVgV(_, _, _, n_block), tVsV, tKVcKV, tKVpKV); cute::cp_async_fence(); flash::gemm</*A_in_regs=*/Kernel_traits::Is_Q_in_regs>( acc_s, tSrQ, tSrK, tSsQ, tSsK, tiled_mma, smem_tiled_copy_Q, smem_tiled_copy_K, smem_thr_copy_Q, smem_thr_copy_K ); if constexpr (Is_softcap){ flash::apply_softcap(acc_s, params.softcap); } flash::cp_async_wait<0>(); __syncthreads(); if (n_block > n_block_min) { flash::copy</*Is_even_MN=*/true, Is_even_K>(gmem_tiled_copy_QKV, tKgK(_, _, _, n_block - 1), tKsK, tKVcKV, tKVpKV); // This cp_async_fence needs to be in the if block, otherwise the synchronization // isn't right and we get race conditions. cute::cp_async_fence(); } mask.template apply_mask</*Causal_mask=*/false>( acc_s, n_block * kBlockN, m_block * kBlockM + (tidx / 32) * 16 + (tidx % 32) / 4, kNWarps * 16 ); softmax.template softmax_rescale_o</*Is_first=*/false, /*Check_inf=*/Is_local>(acc_s, acc_o, params.scale_softmax_log2); Tensor rP = flash::convert_type<Element>(acc_s); int block_row_idx = m_block * (kBlockM / 16) + tidx / 32; int block_col_idx = n_block * (kBlockN / 32); if (Return_softmax) { Tensor rP_drop = make_fragment_like(rP); cute::copy(rP, rP_drop); dropout.template apply_dropout</*encode_dropout_in_sign_bit=*/true>( rP_drop, block_row_idx, block_col_idx, kNWarps ); cute::copy(rP_drop, tSgS); tSgS.data() = tSgS.data() + (-kBlockN); } if (Is_dropout) { dropout.apply_dropout(rP, block_row_idx, block_col_idx, kNWarps); } // Reshape rP from (MMA=4, MMA_M, MMA_N) to ((4, 2), MMA_M, MMA_N / 2) // if using m16n8k16 or (4, MMA_M, MMA_N) if using m16n8k8. Tensor tOrP = make_tensor(rP.data(), flash::convert_layout_acc_Aregs<Kernel_traits::TiledMma>(rP.layout())); flash::gemm_rs(acc_o, tOrP, tOrVt, tOsVt, tiled_mma, smem_tiled_copy_V, smem_thr_copy_V); } // Epilogue Tensor lse = softmax.template normalize_softmax_lse<Is_dropout>(acc_o, params.scale_softmax, params.rp_dropout); // Convert acc_o from fp32 to fp16/bf16 Tensor rO = flash::convert_type<Element>(acc_o); Tensor sO = make_tensor(sQ.data(), typename Kernel_traits::SmemLayoutO{}); // (SMEM_M,SMEM_N) // Partition sO to match the accumulator partitioning auto smem_tiled_copy_O = make_tiled_copy_C(typename Kernel_traits::SmemCopyAtomO{}, tiled_mma); auto smem_thr_copy_O = smem_tiled_copy_O.get_thread_slice(tidx); Tensor taccOrO = smem_thr_copy_O.retile_S(rO); // ((Atom,AtomNum), MMA_M, MMA_N) Tensor taccOsO = smem_thr_copy_O.partition_D(sO); // ((Atom,AtomNum),PIPE_M,PIPE_N) // sO has the same size as sQ, so we don't need to sync here. if (Kernel_traits::Share_Q_K_smem) { __syncthreads(); } cute::copy(smem_tiled_copy_O, taccOrO, taccOsO); Tensor mO = make_tensor(make_gmem_ptr(reinterpret_cast<Element*>(params.o_ptr) + binfo.q_offset(params.o_batch_stride, params.o_row_stride, bidb)), make_shape(binfo.actual_seqlen_q, params.h, params.d), make_stride(params.o_row_stride, params.o_head_stride, _1{})); Tensor gO = local_tile(mO(_, bidh, _), Shape<Int<kBlockM>, Int<kHeadDim>>{}, make_coord(m_block, 0)); // (kBlockM, kHeadDim) Tensor gLSE = get_lse_tile<ElementAccum, Params, kBlockM, Is_even_MN>(params, bidb, bidh, m_block, binfo); typename Kernel_traits::GmemTiledCopyO gmem_tiled_copy_O; auto gmem_thr_copy_O = gmem_tiled_copy_O.get_thread_slice(tidx); Tensor tOsO = gmem_thr_copy_O.partition_S(sO); // ((Atom,AtomNum),ATOM_M,ATOM_N) Tensor tOgO = gmem_thr_copy_O.partition_D(gO); __syncthreads(); Tensor tOrO = make_tensor<Element>(shape(tOgO)); cute::copy(gmem_tiled_copy_O, tOsO, tOrO); Tensor caccO = make_identity_tensor(Shape<Int<kBlockM>, Int<kHeadDim>>{}); // (BLK_M,BLK_K) -> (blk_m,blk_k) Tensor taccOcO = thr_mma.partition_C(caccO); // (MMA,MMA_M,MMA_K) static_assert(decltype(size<0>(taccOcO))::value == 4); // Convert to ((2, 2), MMA_M, MMA_K) then take only the row indices. Tensor taccOcO_row = logical_divide(taccOcO, Shape<_2>{})(make_coord(0, _), _, 0); CUTE_STATIC_ASSERT_V(size(lse) == size(taccOcO_row)); // MMA_M if (get<1>(taccOcO_row(0)) == 0) { #pragma unroll for (int mi = 0; mi < size(lse); ++mi) { const int row = get<0>(taccOcO_row(mi)); if (row < binfo.actual_seqlen_q - m_block * kBlockM) { gLSE(row) = lse(mi); } } } // Construct identity layout for sO Tensor cO = make_identity_tensor(make_shape(size<0>(sO), size<1>(sO))); // (BLK_M,BLK_K) -> (blk_m,blk_k) // Repeat the partitioning with identity layouts Tensor tOcO = gmem_thr_copy_O.partition_D(cO); // (ACPY,ACPY_M,ACPY_K) -> (blk_m,blk_k) Tensor tOpO = make_tensor<bool>(make_shape(size<2>(tOgO))); if (!Is_even_K) { #pragma unroll for (int k = 0; k < size(tOpO); ++k) { tOpO(k) = get<1>(tOcO(0, 0, k)) < params.d; } } // Clear_OOB_K must be false since we don't want to write zeros to gmem flash::copy<Is_even_MN, Is_even_K, /*Clear_OOB_MN=*/false, /*Clear_OOB_K=*/false>( gmem_tiled_copy_O, tOrO, tOgO, tOcO, tOpO, binfo.actual_seqlen_q - m_block * kBlockM ); } //////////////////////////////////////////////////////////////////////////////////////////////////// template<typename Kernel_traits, bool Is_causal, bool Is_local, bool Has_alibi, bool Is_even_MN, bool Is_even_K, bool Is_softcap, bool Split, bool Append_KV, typename Params> inline __device__ void compute_attn_1rowblock_splitkv(const Params &params, const int bidb, const int bidh, const int m_block, const int n_split_idx, const int num_n_splits) { using Element = typename Kernel_traits::Element; using ElementAccum = typename Kernel_traits::ElementAccum; using index_t = typename Kernel_traits::index_t; // Shared memory. extern __shared__ char smem_[]; // The thread index. const int tidx = threadIdx.x; constexpr int kBlockM = Kernel_traits::kBlockM; constexpr int kBlockN = Kernel_traits::kBlockN; constexpr int kHeadDim = Kernel_traits::kHeadDim; constexpr int kNWarps = Kernel_traits::kNWarps; using GmemTiledCopyO = std::conditional_t< !Split, typename Kernel_traits::GmemTiledCopyO, typename Kernel_traits::GmemTiledCopyOaccum >; using ElementO = std::conditional_t<!Split, Element, ElementAccum>; const BlockInfo</*Varlen=*/!Is_even_MN> binfo(params, bidb); // if (threadIdx.x == 0 && blockIdx.y == 0 && blockIdx.z == 0) { printf("Is_even_MN = %d, is_cumulativ = %d, seqlen_k_cache = %d, actual_seqlen_k = %d\n", Is_even_MN, params.is_seqlens_k_cumulative, binfo.seqlen_k_cache, binfo.actual_seqlen_k); } // if (threadIdx.x == 0 && blockIdx.y == 1 && blockIdx.z == 0) { printf("params.knew_ptr = %p, seqlen_k_cache + seqlen_knew = %d\n", params.knew_ptr, binfo.seqlen_k_cache + (params.knew_ptr == nullptr ? 0 : params.seqlen_knew)); } if (m_block * kBlockM >= binfo.actual_seqlen_q) return; const int n_blocks_per_split = ((params.seqlen_k + kBlockN - 1) / kBlockN + num_n_splits - 1) / num_n_splits; const int n_block_min = !Is_local ? n_split_idx * n_blocks_per_split : std::max(n_split_idx * n_blocks_per_split, (m_block * kBlockM + binfo.actual_seqlen_k - binfo.actual_seqlen_q - params.window_size_left) / kBlockN); int n_block_max = std::min(cute::ceil_div(binfo.actual_seqlen_k, kBlockN), (n_split_idx + 1) * n_blocks_per_split); if (Is_causal || Is_local) { n_block_max = std::min(n_block_max, cute::ceil_div((m_block + 1) * kBlockM + binfo.actual_seqlen_k - binfo.actual_seqlen_q + params.window_size_right, kBlockN)); } if (n_block_min >= n_block_max) { // This also covers the case where n_block_max <= 0 // We exit early and write 0 to gOaccum and -inf to gLSEaccum. // Otherwise we might read OOB elements from gK and gV, // or get wrong results when we combine gOaccum from different blocks. const index_t row_offset_o = binfo.q_offset(params.o_batch_stride, params.o_row_stride, bidb) + m_block * kBlockM * params.o_row_stride + bidh * params.o_head_stride; const index_t row_offset_oaccum = (((n_split_idx * params.b + bidb) * params.h + bidh) * params.seqlen_q + m_block * kBlockM) * params.d_rounded; const index_t row_offset_lseaccum = ((n_split_idx * params.b + bidb) * params.h + bidh) * params.seqlen_q + m_block * kBlockM; Tensor gOaccum = make_tensor(make_gmem_ptr(reinterpret_cast<ElementO *>(Split ? params.oaccum_ptr : params.o_ptr) + (Split ? row_offset_oaccum : row_offset_o)), Shape<Int<kBlockM>, Int<kHeadDim>>{}, make_stride(Split ? kHeadDim : params.o_row_stride, _1{})); Tensor gLSEaccum = make_tensor(make_gmem_ptr(reinterpret_cast<ElementAccum *>(Split ? params.softmax_lseaccum_ptr : params.softmax_lse_ptr) + row_offset_lseaccum), Shape<Int<kBlockM>>{}, Stride<_1>{}); GmemTiledCopyO gmem_tiled_copy_Oaccum; auto gmem_thr_copy_Oaccum = gmem_tiled_copy_Oaccum.get_thread_slice(tidx); Tensor tOgOaccum = gmem_thr_copy_Oaccum.partition_D(gOaccum); Tensor tOrOaccum = make_tensor<ElementO>(shape(tOgOaccum)); clear(tOrOaccum); // Construct identity layout for sO Tensor cO = make_identity_tensor(make_shape(size<0>(gOaccum), size<1>(gOaccum))); // (BLK_M,BLK_K) -> (blk_m,blk_k) // Repeat the partitioning with identity layouts Tensor tOcO = gmem_thr_copy_Oaccum.partition_D(cO); Tensor tOpO = make_tensor<bool>(make_shape(size<2>(tOgOaccum))); if (!Is_even_K) { #pragma unroll for (int k = 0; k < size(tOpO); ++k) { tOpO(k) = get<1>(tOcO(0, 0, k)) < params.d; } } // Clear_OOB_K must be false since we don't want to write zeros to gmem flash::copy<Is_even_MN, Is_even_K, /*Clear_OOB_MN=*/false, /*Clear_OOB_K=*/false>( gmem_tiled_copy_Oaccum, tOrOaccum, tOgOaccum, tOcO, tOpO, binfo.actual_seqlen_q - m_block * kBlockM ); #pragma unroll for (int m = 0; m < size<1>(tOgOaccum); ++m) { const int row = get<0>(tOcO(0, m, 0)); if (row < binfo.actual_seqlen_q - m_block * kBlockM && get<1>(tOcO(0, m, 0)) == 0) { gLSEaccum(row) = Split ? -INFINITY : INFINITY; } } return; } // We iterate over the blocks in reverse order. This is because the last block is the only one // that needs masking when we read K and V from global memory. Moreover, iterating in reverse // might save us 1 register (we just need n_block instead of both n_block and n_block_max). // We move K and V to the last block. const int bidb_cache = params.cache_batch_idx == nullptr ? bidb : params.cache_batch_idx[bidb]; const int *block_table = params.block_table == nullptr ? nullptr : params.block_table + bidb * params.block_table_batch_stride; const int block_table_idx = block_table == nullptr ? 0 : (n_block_max - 1) * kBlockN / params.page_block_size; const int block_table_offset = block_table == nullptr ? 0 : (n_block_max - 1) * kBlockN - block_table_idx * params.page_block_size; const index_t row_offset_k = block_table == nullptr ? binfo.k_offset(params.k_batch_stride, params.k_row_stride, bidb_cache) + (n_block_max - 1) * kBlockN * params.k_row_stride + (bidh / params.h_h_k_ratio) * params.k_head_stride : block_table[block_table_idx] * params.k_batch_stride + block_table_offset * params.k_row_stride + (bidh / params.h_h_k_ratio) * params.k_head_stride; const index_t row_offset_v = block_table == nullptr ? binfo.k_offset(params.v_batch_stride, params.v_row_stride, bidb_cache) + (n_block_max - 1) * kBlockN * params.v_row_stride + (bidh / params.h_h_k_ratio) * params.v_head_stride : block_table[block_table_idx] * params.v_batch_stride + block_table_offset * params.v_row_stride + (bidh / params.h_h_k_ratio) * params.v_head_stride; Tensor mQ = make_tensor(make_gmem_ptr(reinterpret_cast<Element*>(params.q_ptr) + binfo.q_offset(params.q_batch_stride, params.q_row_stride, bidb)), make_shape(binfo.actual_seqlen_q, params.h, params.d), make_stride(params.q_row_stride, params.q_head_stride, _1{})); Tensor gQ = local_tile(mQ(_, bidh, _), Shape<Int<kBlockM>, Int<kHeadDim>>{}, make_coord(m_block, 0)); // (kBlockM, kHeadDim) Tensor gK = make_tensor(make_gmem_ptr(reinterpret_cast<Element *>(params.k_ptr) + row_offset_k), Shape<Int<kBlockN>, Int<kHeadDim>>{}, make_stride(params.k_row_stride, _1{})); // if (threadIdx.x == 0 && blockIdx.y == 0 && blockIdx.z == 0) { printf("k_ptr = %p, row_offset_k = %d, gK_ptr = %p\n", params.k_ptr, row_offset_k, gK.data()); } Tensor gV = make_tensor(make_gmem_ptr(reinterpret_cast<Element *>(params.v_ptr) + row_offset_v), Shape<Int<kBlockN>, Int<kHeadDim>>{}, make_stride(params.v_row_stride, _1{})); Tensor sQ = make_tensor(make_smem_ptr(reinterpret_cast<Element *>(smem_)), typename Kernel_traits::SmemLayoutQ{}); Tensor sK = make_tensor(sQ.data() + size(sQ), typename Kernel_traits::SmemLayoutKV{}); Tensor sV = make_tensor(sK.data() + size(sK), typename Kernel_traits::SmemLayoutKV{}); Tensor sVt = make_tensor(sV.data(), typename Kernel_traits::SmemLayoutVtransposed{}); Tensor sVtNoSwizzle = make_tensor(sV.data().get(), typename Kernel_traits::SmemLayoutVtransposedNoSwizzle{}); typename Kernel_traits::GmemTiledCopyQKV gmem_tiled_copy_QKV; auto gmem_thr_copy_QKV = gmem_tiled_copy_QKV.get_thread_slice(tidx); Tensor tQgQ = gmem_thr_copy_QKV.partition_S(gQ); Tensor tQsQ = gmem_thr_copy_QKV.partition_D(sQ); Tensor tKgK = gmem_thr_copy_QKV.partition_S(gK); // (KCPY, KCPY_N, KCPY_K) Tensor tKsK = gmem_thr_copy_QKV.partition_D(sK); Tensor tVgV = gmem_thr_copy_QKV.partition_S(gV); // (VCPY, VCPY_N, VCPY_K) Tensor tVsV = gmem_thr_copy_QKV.partition_D(sV); typename Kernel_traits::TiledMma tiled_mma; auto thr_mma = tiled_mma.get_thread_slice(tidx); Tensor tSrQ = thr_mma.partition_fragment_A(sQ); // (MMA,MMA_M,MMA_K) Tensor tSrK = thr_mma.partition_fragment_B(sK); // (MMA,MMA_N,MMA_K) Tensor tOrVt = thr_mma.partition_fragment_B(sVtNoSwizzle); // (MMA, MMA_K,MMA_N) Tensor acc_o = partition_fragment_C(tiled_mma, Shape<Int<kBlockM>, Int<kHeadDim>>{}); // MMA, MMA_M, MMA_K // // Copy Atom retiling // auto smem_tiled_copy_Q = make_tiled_copy_A(typename Kernel_traits::SmemCopyAtom{}, tiled_mma); auto smem_thr_copy_Q = smem_tiled_copy_Q.get_thread_slice(tidx); Tensor tSsQ = smem_thr_copy_Q.partition_S(sQ); auto smem_tiled_copy_K = make_tiled_copy_B(typename Kernel_traits::SmemCopyAtom{}, tiled_mma); auto smem_thr_copy_K = smem_tiled_copy_K.get_thread_slice(tidx); Tensor tSsK = smem_thr_copy_K.partition_S(sK); auto smem_tiled_copy_V = make_tiled_copy_B(typename Kernel_traits::SmemCopyAtomTransposed{}, tiled_mma); auto smem_thr_copy_V = smem_tiled_copy_V.get_thread_slice(tidx); Tensor tOsVt = smem_thr_copy_V.partition_S(sVt); // PREDICATES // // // Allocate predicate tensors for m and n // Tensor tQpQ = make_tensor<bool>(make_shape(size<1>(tQsQ), size<2>(tQsQ)), Stride<_1,_0>{}); // Tensor tKVpKV = make_tensor<bool>(make_shape(size<1>(tKsK), size<2>(tKsK)), Stride<_1,_0>{}); // Construct identity layout for sQ and sK Tensor cQ = make_identity_tensor(make_shape(size<0>(sQ), size<1>(sQ))); // (BLK_M,BLK_K) -> (blk_m,blk_k) Tensor cKV = make_identity_tensor(make_shape(size<0>(sK), size<1>(sK))); // (BLK_N,BLK_K) -> (blk_n,blk_k) // Repeat the partitioning with identity layouts Tensor tQcQ = gmem_thr_copy_QKV.partition_S(cQ); // (ACPY,ACPY_M,ACPY_K) -> (blk_m,blk_k) Tensor tKVcKV = gmem_thr_copy_QKV.partition_S(cKV); // (BCPY,BCPY_N,BCPY_K) -> (blk_n,blk_k) // Allocate predicate tensors for k Tensor tQpQ = make_tensor<bool>(make_shape(size<2>(tQsQ))); Tensor tKVpKV = make_tensor<bool>(make_shape(size<2>(tKsK))); // Set predicates for k bounds if (!Is_even_K) { #pragma unroll for (int k = 0; k < size(tQpQ); ++k) { tQpQ(k) = get<1>(tQcQ(0, 0, k)) < params.d; } #pragma unroll for (int k = 0; k < size(tKVpKV); ++k) { tKVpKV(k) = get<1>(tKVcKV(0, 0, k)) < params.d; } } // Prologue // Copy from Knew to K, optionally apply rotary embedding. typename Kernel_traits::GmemTiledCopyRotcossin gmem_tiled_copy_rotary; auto gmem_thr_copy_rotary = gmem_tiled_copy_rotary.get_thread_slice(tidx); typename Kernel_traits::GmemTiledCopyRotcossinCont gmem_tiled_copy_rotary_cont; auto gmem_thr_copy_rotary_cont = gmem_tiled_copy_rotary_cont.get_thread_slice(tidx); if constexpr (Append_KV) { // Even if we have MQA / GQA, all threadblocks responsible for the same KV head are writing to // gmem. Technically it's a race condition, but they all write the same content anyway, and it's safe. // We want to do this so that all threadblocks can proceed right after they finish writing the KV cache. const index_t row_offset_cossin = ((n_block_max - 1) * kBlockN + (params.leftpad_k == nullptr ? 0 : params.leftpad_k[bidb])) * (params.rotary_dim / 2); Tensor gCos = make_tensor(make_gmem_ptr(reinterpret_cast<Element *>(params.rotary_cos_ptr) + row_offset_cossin), Shape<Int<kBlockN>, Int<kHeadDim / 2>>{}, make_stride(params.rotary_dim / 2, _1{})); Tensor gSin = make_tensor(make_gmem_ptr(reinterpret_cast<Element *>(params.rotary_sin_ptr) + row_offset_cossin), Shape<Int<kBlockN>, Int<kHeadDim / 2>>{}, make_stride(params.rotary_dim / 2, _1{})); Tensor gCosCont = make_tensor(make_gmem_ptr(reinterpret_cast<Element *>(params.rotary_cos_ptr) + row_offset_cossin), Shape<Int<kBlockN>, Int<kHeadDim>>{}, make_stride(params.rotary_dim / 2, _1{})); Tensor gSinCont = make_tensor(make_gmem_ptr(reinterpret_cast<Element *>(params.rotary_sin_ptr) + row_offset_cossin), Shape<Int<kBlockN>, Int<kHeadDim>>{}, make_stride(params.rotary_dim / 2, _1{})); Tensor tRgCos = gmem_thr_copy_rotary.partition_S(gCos); Tensor tRgSin = gmem_thr_copy_rotary.partition_S(gSin); Tensor tRgCosCont = gmem_thr_copy_rotary_cont.partition_S(gCosCont); Tensor tRgSinCont = gmem_thr_copy_rotary_cont.partition_S(gSinCont); // if (cute::thread(0, 0)) { printf("rotary_cos_ptr = %p, gCos.data() = %p, tRgCos.data() = %p, rotary_dim = %d\n", params.rotary_cos_ptr, gCos.data(), tRgCos.data(), params.rotary_dim); } // if (cute::thread(8, 0)) { print_tensor(gCos); } // if (cute::thread(0, 0)) { print_tensor(tRgCos); } // const index_t row_offset_knew = binfo.k_offset(params.knew_batch_stride, params.knew_row_stride, bidb) const index_t row_offset_knew = bidb * params.knew_batch_stride + ((n_block_max - 1) * kBlockN) * params.knew_row_stride + (bidh / params.h_h_k_ratio) * params.knew_head_stride; // const index_t row_offset_vnew = binfo.k_offset(params.vnew_batch_stride, params.vnew_row_stride, bidb) const index_t row_offset_vnew = bidb * params.vnew_batch_stride + ((n_block_max - 1) * kBlockN) * params.vnew_row_stride + (bidh / params.h_h_k_ratio) * params.vnew_head_stride; // Subtract seqlen_k_cache * row stride so that conceptually gK and gKnew "line up". When we access them, // e.g. if gK has 128 rows and gKnew has 64 rows, we access gK[:128] and gKNew[128:128 + 64]. // This maps to accessing the first 64 rows of knew_ptr. Tensor gKnew = make_tensor(make_gmem_ptr(reinterpret_cast<Element *>(params.knew_ptr) + row_offset_knew - binfo.seqlen_k_cache * params.knew_row_stride), Shape<Int<kBlockN>, Int<kHeadDim>>{}, make_stride(params.knew_row_stride, _1{})); // if (threadIdx.x == 0 && blockIdx.y == 0 && blockIdx.z == 0) { printf("knew_ptr = %p, row_offset_knew = %d, gKnew_ptr = %p\n", params.knew_ptr, row_offset_knew, gKnew.data()); } Tensor gVnew = make_tensor(make_gmem_ptr(reinterpret_cast<Element *>(params.vnew_ptr) + row_offset_vnew - binfo.seqlen_k_cache * params.vnew_row_stride), Shape<Int<kBlockN>, Int<kHeadDim>>{}, make_stride(params.vnew_row_stride, _1{})); Tensor tKgKnew = gmem_thr_copy_QKV.partition_S(gKnew); // (KCPY, KCPY_N, KCPY_K) Tensor tVgVnew = gmem_thr_copy_QKV.partition_S(gVnew); // (VCPY, VCPY_N, VCPY_K) const int n_block_copy_min = std::max(n_block_min, binfo.seqlen_k_cache / kBlockN); auto tKgK_data = tKgK.data(); auto tVgV_data = tVgV.data(); for (int n_block = n_block_max - 1; n_block >= n_block_copy_min; n_block--) { flash::copy_w_min_idx<Is_even_K>( tVgVnew, tVgV, tKVcKV, tKVpKV, binfo.actual_seqlen_k - n_block * kBlockN, binfo.seqlen_k_cache - n_block * kBlockN ); tVgVnew.data() = tVgVnew.data() + (-int(kBlockN * params.vnew_row_stride)); if (params.rotary_dim == 0) { flash::copy_w_min_idx<Is_even_K>( tKgKnew, tKgK, tKVcKV, tKVpKV, binfo.actual_seqlen_k - n_block * kBlockN, binfo.seqlen_k_cache - n_block * kBlockN ); } else { if (params.is_rotary_interleaved) { // Don't clear OOB_K because we're writing to global memory flash::copy_rotary_interleaved<Is_even_K, /*Clear_OOB_K=*/false>( tKgKnew, tKgK, tRgCos, tRgSin, tKVcKV, binfo.actual_seqlen_k - n_block * kBlockN, binfo.seqlen_k_cache - n_block * kBlockN, params.d, params.rotary_dim ); tRgCos.data() = tRgCos.data() + (-int(kBlockN * params.rotary_dim / 2)); tRgSin.data() = tRgSin.data() + (-int(kBlockN * params.rotary_dim / 2)); } else { // Don't clear OOB_K because we're writing to global memory flash::copy_rotary_contiguous<Is_even_K, /*Clear_OOB_K=*/false>( tKgKnew, tKgK, tRgCosCont, tRgSinCont, tKVcKV, binfo.actual_seqlen_k - n_block * kBlockN, binfo.seqlen_k_cache - n_block * kBlockN, params.d, params.rotary_dim ); tRgCosCont.data() = tRgCosCont.data() + (-int(kBlockN * params.rotary_dim / 2)); tRgSinCont.data() = tRgSinCont.data() + (-int(kBlockN * params.rotary_dim / 2)); } } tKgKnew.data() = tKgKnew.data() + (-int(kBlockN * params.knew_row_stride)); if (block_table == nullptr) { tVgV.data() = tVgV.data() + (-int(kBlockN * params.v_row_stride)); tKgK.data() = tKgK.data() + (-int(kBlockN * params.k_row_stride)); } else { if (n_block > n_block_copy_min) { const int block_table_idx_cur = n_block * kBlockN / params.page_block_size; const int block_table_offset_cur = n_block * kBlockN - block_table_idx_cur * params.page_block_size; const int block_table_idx_next = (n_block - 1) * kBlockN / params.page_block_size; const int block_table_offset_next = (n_block - 1) * kBlockN - block_table_idx_next * params.page_block_size; const int table_diff = block_table[block_table_idx_next] - block_table[block_table_idx_cur]; const int offset_diff = block_table_offset_next - block_table_offset_cur; tVgV.data() = tVgV.data() + table_diff * params.v_batch_stride + offset_diff * params.v_row_stride; tKgK.data() = tKgK.data() + table_diff * params.k_batch_stride + offset_diff * params.k_row_stride; } } } // Need this before we can read in K again, so that we'll see the updated K values. __syncthreads(); tKgK.data() = tKgK_data; tVgV.data() = tVgV_data; } // Read Q from gmem to smem, optionally apply rotary embedding. if (!Append_KV || params.rotary_dim == 0) { // We don't need to clear the sQ smem tiles since we'll only write out the valid outputs flash::copy<Is_even_MN, Is_even_K>(gmem_tiled_copy_QKV, tQgQ, tQsQ, tQcQ, tQpQ, binfo.actual_seqlen_q - m_block * kBlockM); } else { const index_t row_offset_cossin = (binfo.seqlen_k_cache + (params.leftpad_k == nullptr ? 0 : params.leftpad_k[bidb]) + (Is_causal || Is_local ? m_block * kBlockM : 0)) * (params.rotary_dim / 2); // If not causal, all the queries get the same the cos/sin, taken at location seqlen_k_cache. // We do this by setting the row stride of gCos / gSin to 0. Tensor gCos = make_tensor(make_gmem_ptr(reinterpret_cast<Element *>(params.rotary_cos_ptr) + row_offset_cossin), Shape<Int<kBlockM>, Int<kHeadDim / 2>>{}, make_stride(Is_causal || Is_local ? params.rotary_dim / 2 : 0, _1{})); Tensor gSin = make_tensor(make_gmem_ptr(reinterpret_cast<Element *>(params.rotary_sin_ptr) + row_offset_cossin), Shape<Int<kBlockM>, Int<kHeadDim / 2>>{}, make_stride(Is_causal || Is_local ? params.rotary_dim / 2 : 0, _1{})); Tensor gCosCont = make_tensor(make_gmem_ptr(reinterpret_cast<Element *>(params.rotary_cos_ptr) + row_offset_cossin), Shape<Int<kBlockM>, Int<kHeadDim>>{}, make_stride(Is_causal || Is_local ? params.rotary_dim / 2 : 0, _1{})); Tensor gSinCont = make_tensor(make_gmem_ptr(reinterpret_cast<Element *>(params.rotary_sin_ptr) + row_offset_cossin), Shape<Int<kBlockM>, Int<kHeadDim>>{}, make_stride(Is_causal || Is_local ? params.rotary_dim / 2 : 0, _1{})); Tensor tRgCos = gmem_thr_copy_rotary.partition_S(gCos); Tensor tRgSin = gmem_thr_copy_rotary.partition_S(gSin); Tensor tRgCosCont = gmem_thr_copy_rotary_cont.partition_S(gCosCont); Tensor tRgSinCont = gmem_thr_copy_rotary_cont.partition_S(gSinCont); if (params.is_rotary_interleaved) { flash::copy_rotary_interleaved<Is_even_K>( tQgQ, tQsQ, tRgCos, tRgSin, tQcQ, binfo.actual_seqlen_q - m_block * kBlockM, 0, params.d, params.rotary_dim ); } else { flash::copy_rotary_contiguous<Is_even_K>( tQgQ, tQsQ, tRgCosCont, tRgSinCont, tQcQ, binfo.actual_seqlen_q - m_block * kBlockM, 0, params.d, params.rotary_dim ); } } int n_block = n_block_max - 1; // We don't need to clear the sK smem tiles since we'll mask out the scores anyway. flash::copy<Is_even_MN, Is_even_K>(gmem_tiled_copy_QKV, tKgK, tKsK, tKVcKV, tKVpKV, binfo.actual_seqlen_k - n_block * kBlockN); cute::cp_async_fence(); // flash::cp_async_wait<0>(); // __syncthreads(); // if (tidx == 0 && blockIdx.y == 0 && blockIdx.z == 0) { print(tKsK); } // __syncthreads(); clear(acc_o); flash::Softmax<2 * size<1>(acc_o)> softmax; const float alibi_slope = !Has_alibi ? 0.0f : reinterpret_cast<float *>(params.alibi_slopes_ptr)[bidb * params.alibi_slopes_batch_stride + bidh] / params.scale_softmax; flash::Mask<Is_causal, Is_local, Has_alibi> mask(binfo.actual_seqlen_k, binfo.actual_seqlen_q, params.window_size_left, params.window_size_right, alibi_slope); // For performance reason, we separate out two kinds of iterations: // those that need masking on S, and those that don't. // We need masking on S for the very last block when K and V has length not multiple of kBlockN. // We also need masking on S if it's causal, for the last ceil_div(kBlockM, kBlockN) blocks. // We will have at least 1 "masking" iteration. // If not even_N, then seqlen_k might end in the middle of a block. In that case we need to // mask 2 blocks (e.g. when kBlockM == kBlockN), not just 1. constexpr int n_masking_steps = (!Is_causal && !Is_local) ? 1 : ((Is_even_MN && Is_causal) ? cute::ceil_div(kBlockM, kBlockN) : cute::ceil_div(kBlockM, kBlockN) + 1); #pragma unroll for (int masking_step = 0; masking_step < n_masking_steps; ++masking_step, --n_block) { Tensor acc_s = partition_fragment_C(tiled_mma, Shape<Int<kBlockM>, Int<kBlockN>>{}); // (MMA=4, MMA_M, MMA_N) clear(acc_s); flash::cp_async_wait<0>(); __syncthreads(); // Advance gV if (masking_step > 0) { if (block_table == nullptr) { tVgV.data() = tVgV.data() + (-int(kBlockN * params.v_row_stride)); } else { const int block_table_idx_cur = (n_block + 1) * kBlockN / params.page_block_size; const int block_table_offset_cur = (n_block + 1) * kBlockN - block_table_idx_cur * params.page_block_size; const int block_table_idx_next = n_block * kBlockN / params.page_block_size; const int block_table_offset_next = n_block * kBlockN - block_table_idx_next * params.page_block_size; tVgV.data() = tVgV.data() + (block_table[block_table_idx_next] - block_table[block_table_idx_cur]) * params.v_batch_stride + (block_table_offset_next - block_table_offset_cur) * params.v_row_stride; } flash::copy</*Is_even_MN=*/true, Is_even_K>(gmem_tiled_copy_QKV, tVgV, tVsV, tKVcKV, tKVpKV); } else { // Clear the smem tiles to account for predicated off loads flash::copy<Is_even_MN, Is_even_K, /*Clear_OOB_MN=*/true>( gmem_tiled_copy_QKV, tVgV, tVsV, tKVcKV, tKVpKV, binfo.actual_seqlen_k - n_block * kBlockN ); } cute::cp_async_fence(); flash::gemm( acc_s, tSrQ, tSrK, tSsQ, tSsK, tiled_mma, smem_tiled_copy_Q, smem_tiled_copy_K, smem_thr_copy_Q, smem_thr_copy_K ); // if (cute::thread0()) { print(acc_s); } if constexpr (Is_softcap){ flash::apply_softcap(acc_s, params.softcap); } mask.template apply_mask<Is_causal, Is_even_MN>( acc_s, n_block * kBlockN, m_block * kBlockM + (tidx / 32) * 16 + (tidx % 32) / 4, kNWarps * 16 ); flash::cp_async_wait<0>(); __syncthreads(); // if (tidx == 0 && blockIdx.y == 0 && blockIdx.z == 0) { print(tVsV); } // __syncthreads(); if (n_block > n_block_min) { // Advance gK if (block_table == nullptr) { tKgK.data() = tKgK.data() + (-int(kBlockN * params.k_row_stride)); } else { const int block_table_idx_cur = n_block * kBlockN / params.page_block_size; const int block_table_offset_cur = n_block * kBlockN - block_table_idx_cur * params.page_block_size; const int block_table_idx_next = (n_block - 1) * kBlockN / params.page_block_size; const int block_table_offset_next =(n_block - 1) * kBlockN - block_table_idx_next * params.page_block_size; tKgK.data() = tKgK.data() + (block_table[block_table_idx_next] - block_table[block_table_idx_cur]) * params.k_batch_stride + (block_table_offset_next - block_table_offset_cur) * params.k_row_stride; } flash::copy</*Is_even_MN=*/true, Is_even_K>(gmem_tiled_copy_QKV, tKgK, tKsK, tKVcKV, tKVpKV); // This cp_async_fence needs to be in the if block, otherwise the synchronization // isn't right and we get race conditions. cute::cp_async_fence(); } // We have key_padding_mask so we'll need to Check_inf masking_step == 0 ? softmax.template softmax_rescale_o</*Is_first=*/true, /*Check_inf=*/Is_causal || Is_local || !Is_even_MN>(acc_s, acc_o, params.scale_softmax_log2) : softmax.template softmax_rescale_o</*Is_first=*/false, /*Check_inf=*/Is_causal || Is_local || !Is_even_MN>(acc_s, acc_o, params.scale_softmax_log2); // if (cute::thread0()) { print(scores_max); print(scores_sum); print(scores); } // Convert acc_s from fp32 to fp16/bf16 Tensor rP = flash::convert_type<Element>(acc_s); // Reshape rP from (MMA=4, MMA_M, MMA_N) to ((4, 2), MMA_M, MMA_N / 2) // if using m16n8k16 or (4, MMA_M, MMA_N) if using m16n8k8. Tensor tOrP = make_tensor(rP.data(), flash::convert_layout_acc_Aregs<Kernel_traits::TiledMma>(rP.layout())); flash::gemm_rs(acc_o, tOrP, tOrVt, tOsVt, tiled_mma, smem_tiled_copy_V, smem_thr_copy_V); // This check is at the end of the loop since we always have at least 1 iteration if (n_masking_steps > 1 && n_block <= n_block_min) { --n_block; break; } } // These are the iterations where we don't need masking on S for (; n_block >= n_block_min; --n_block) { Tensor acc_s = partition_fragment_C(tiled_mma, Shape<Int<kBlockM>, Int<kBlockN>>{}); // (MMA=4, MMA_M, MMA_N) clear(acc_s); flash::cp_async_wait<0>(); __syncthreads(); // Advance gV if (block_table == nullptr) { tVgV.data() = tVgV.data() + (-int(kBlockN * params.v_row_stride)); } else { const int block_table_idx_cur = (n_block + 1) * kBlockN / params.page_block_size; const int block_table_offset_cur = (n_block + 1) * kBlockN - block_table_idx_cur * params.page_block_size; const int block_table_idx_next = n_block * kBlockN / params.page_block_size; const int block_table_offset_next = n_block * kBlockN - block_table_idx_next * params.page_block_size; tVgV.data() = tVgV.data() + (block_table[block_table_idx_next] - block_table[block_table_idx_cur]) * params.v_batch_stride + (block_table_offset_next - block_table_offset_cur) * params.v_row_stride; } flash::copy</*Is_even_MN=*/true, Is_even_K>(gmem_tiled_copy_QKV, tVgV, tVsV, tKVcKV, tKVpKV); cute::cp_async_fence(); flash::gemm( acc_s, tSrQ, tSrK, tSsQ, tSsK, tiled_mma, smem_tiled_copy_Q, smem_tiled_copy_K, smem_thr_copy_Q, smem_thr_copy_K ); if constexpr (Is_softcap){ flash::apply_softcap(acc_s, params.softcap); } flash::cp_async_wait<0>(); __syncthreads(); if (n_block > n_block_min) { // Advance gK if (block_table == nullptr) { tKgK.data() = tKgK.data() + (-int(kBlockN * params.k_row_stride)); } else { const int block_table_idx_cur = n_block * kBlockN / params.page_block_size; const int block_table_offset_cur = n_block * kBlockN - block_table_idx_cur * params.page_block_size; const int block_table_idx_next = (n_block - 1) * kBlockN / params.page_block_size; const int block_table_offset_next = (n_block - 1) * kBlockN - block_table_idx_next * params.page_block_size; tKgK.data() = tKgK.data() + (block_table[block_table_idx_next] - block_table[block_table_idx_cur]) * params.k_batch_stride + (block_table_offset_next - block_table_offset_cur) * params.k_row_stride; } flash::copy</*Is_even_MN=*/true, Is_even_K>(gmem_tiled_copy_QKV, tKgK, tKsK, tKVcKV, tKVpKV); // This cp_async_fence needs to be in the if block, otherwise the synchronization // isn't right and we get race conditions. cute::cp_async_fence(); } mask.template apply_mask</*Causal_mask=*/false>( acc_s, n_block * kBlockN, m_block * kBlockM + (tidx / 32) * 16 + (tidx % 32) / 4, kNWarps * 16 ); softmax.template softmax_rescale_o</*Is_first=*/false, /*Check_inf=*/Is_local>(acc_s, acc_o, params.scale_softmax_log2); Tensor rP = flash::convert_type<Element>(acc_s); // Reshape rP from (MMA=4, MMA_M, MMA_N) to ((4, 2), MMA_M, MMA_N / 2) // if using m16n8k16 or (4, MMA_M, MMA_N) if using m16n8k8. Tensor tOrP = make_tensor(rP.data(), flash::convert_layout_acc_Aregs<Kernel_traits::TiledMma>(rP.layout())); flash::gemm_rs(acc_o, tOrP, tOrVt, tOsVt, tiled_mma, smem_tiled_copy_V, smem_thr_copy_V); } // Epilogue Tensor lse = softmax.template normalize_softmax_lse</*Is_dropout=*/false, Split>(acc_o, params.scale_softmax); // if (cute::thread0()) { print(lse); } Tensor sOaccum = make_tensor(make_smem_ptr(reinterpret_cast<ElementO *>(smem_)), typename Kernel_traits::SmemLayoutO{}); // (SMEM_M,SMEM_N) // Partition sO to match the accumulator partitioning using SmemTiledCopyO = std::conditional_t< !Split, typename Kernel_traits::SmemCopyAtomO, typename Kernel_traits::SmemCopyAtomOaccum >; auto smem_tiled_copy_Oaccum = make_tiled_copy_C(SmemTiledCopyO{}, tiled_mma); auto smem_thr_copy_Oaccum = smem_tiled_copy_Oaccum.get_thread_slice(tidx); Tensor rO = flash::convert_type<ElementO>(acc_o); Tensor taccOrOaccum = smem_thr_copy_Oaccum.retile_S(rO); // ((Atom,AtomNum), MMA_M, MMA_N) Tensor taccOsOaccum = smem_thr_copy_Oaccum.partition_D(sOaccum); // ((Atom,AtomNum),PIPE_M,PIPE_N) // sOaccum is larger than sQ, so we need to syncthreads here // TODO: allocate enough smem for sOaccum if constexpr (Split) { __syncthreads(); } cute::copy(smem_tiled_copy_Oaccum, taccOrOaccum, taccOsOaccum); const index_t row_offset_o = binfo.q_offset(params.o_batch_stride, params.o_row_stride, bidb) + m_block * kBlockM * params.o_row_stride + bidh * params.o_head_stride; const index_t row_offset_oaccum = (((n_split_idx * params.b + bidb) * params.h + bidh) * params.seqlen_q + m_block * kBlockM) * params.d_rounded; const index_t row_offset_lseaccum = (Split || !params.unpadded_lse ? ((n_split_idx * params.b + bidb) * params.h + bidh) * params.seqlen_q : bidh * params.total_q + binfo.q_offset(params.seqlen_q, 1, bidb) ) + m_block * kBlockM; Tensor gOaccum = make_tensor(make_gmem_ptr(reinterpret_cast<ElementO *>(Split ? params.oaccum_ptr : params.o_ptr) + (Split ? row_offset_oaccum : row_offset_o)), Shape<Int<kBlockM>, Int<kHeadDim>>{}, make_stride(Split ? kHeadDim : params.o_row_stride, _1{})); Tensor gLSEaccum = make_tensor(make_gmem_ptr(reinterpret_cast<ElementAccum *>(Split ? params.softmax_lseaccum_ptr : params.softmax_lse_ptr) + row_offset_lseaccum), Shape<Int<kBlockM>>{}, Stride<_1>{}); // if (tidx == 0) { printf("row_offset_o = %d, bidh = %d, gOaccum = %p\n", row_offset_o, bidh, gOaccum.data()); } GmemTiledCopyO gmem_tiled_copy_Oaccum; auto gmem_thr_copy_Oaccum = gmem_tiled_copy_Oaccum.get_thread_slice(tidx); Tensor tOsOaccum = gmem_thr_copy_Oaccum.partition_S(sOaccum); // ((Atom,AtomNum),ATOM_M,ATOM_N) Tensor tOgOaccum = gmem_thr_copy_Oaccum.partition_D(gOaccum); __syncthreads(); Tensor tOrOaccum = make_tensor<ElementO>(shape(tOgOaccum)); cute::copy(gmem_tiled_copy_Oaccum, tOsOaccum, tOrOaccum); Tensor caccO = make_identity_tensor(Shape<Int<kBlockM>, Int<kHeadDim>>{}); // (BLK_M,BLK_K) -> (blk_m,blk_k) Tensor taccOcO = thr_mma.partition_C(caccO); // (MMA,MMA_M,MMA_K) static_assert(decltype(size<0>(taccOcO))::value == 4); // Convert to ((2, 2), MMA_M, MMA_K) then take only the row indices. Tensor taccOcO_row = logical_divide(taccOcO, Shape<_2>{})(make_coord(0, _), _, 0); CUTE_STATIC_ASSERT_V(size(lse) == size(taccOcO_row)); // MMA_M if (get<1>(taccOcO_row(0)) == 0) { #pragma unroll for (int mi = 0; mi < size(lse); ++mi) { const int row = get<0>(taccOcO_row(mi)); if (row < binfo.actual_seqlen_q - m_block * kBlockM) { gLSEaccum(row) = lse(mi); } } } // Construct identity layout for sO Tensor cO = make_identity_tensor(make_shape(size<0>(sOaccum), size<1>(sOaccum))); // (BLK_M,BLK_K) -> (blk_m,blk_k) // Repeat the partitioning with identity layouts Tensor tOcO = gmem_thr_copy_Oaccum.partition_D(cO); // (ACPY,ACPY_M,ACPY_K) -> (blk_m,blk_k) Tensor tOpO = make_tensor<bool>(make_shape(size<2>(tOgOaccum))); if (!Is_even_K) { #pragma unroll for (int k = 0; k < size(tOpO); ++k) { tOpO(k) = get<1>(tOcO(0, 0, k)) < params.d; } } // Clear_OOB_K must be false since we don't want to write zeros to gmem flash::copy<Is_even_MN, Is_even_K, /*Clear_OOB_MN=*/false, /*Clear_OOB_K=*/false>( gmem_tiled_copy_Oaccum, tOrOaccum, tOgOaccum, tOcO, tOpO, binfo.actual_seqlen_q - m_block * kBlockM ); } //////////////////////////////////////////////////////////////////////////////////////////////////// template<typename Kernel_traits, bool Is_dropout, bool Is_causal, bool Is_local, bool Has_alibi, bool Is_even_MN, bool Is_even_K, bool Is_softcap, bool Return_softmax, typename Params> inline __device__ void compute_attn(const Params &params) { const int m_block = blockIdx.x; // The block index for the batch. const int bidb = blockIdx.y; // The block index for the head. const int bidh = blockIdx.z; // We want the fwd and bwd to generate the same dropout pattern (RNG), without restricting // them to have the same number of threads or have to traverse the attention matrix // in the same order. // In the Philox RNG, we use the offset to store the batch, head, and the lane id // (within a warp). We use the subsequence to store the location of the 16 x 32 blocks within // the attention matrix. This way, as long as we have the batch, head, and the location of // the 16 x 32 block within the attention matrix, we can generate the exact same dropout pattern. flash::compute_attn_1rowblock<Kernel_traits, Is_dropout, Is_causal, Is_local, Has_alibi, Is_even_MN, Is_even_K, Is_softcap, Return_softmax>(params, bidb, bidh, m_block); } //////////////////////////////////////////////////////////////////////////////////////////////////// template<typename Kernel_traits, bool Is_causal, bool Is_local, bool Has_alibi, bool Is_even_MN, bool Is_even_K, bool Is_softcap, bool Split, bool Append_KV, typename Params> inline __device__ void compute_attn_splitkv(const Params &params) { const int m_block = blockIdx.x; // The block index for the batch. const int bidb = Split ? blockIdx.z / params.h : blockIdx.y; // The block index for the head. const int bidh = Split ? blockIdx.z - bidb * params.h : blockIdx.z; const int n_split_idx = Split ? blockIdx.y : 0; const int num_n_splits = Split ? gridDim.y : 1; flash::compute_attn_1rowblock_splitkv<Kernel_traits, Is_causal, Is_local, Has_alibi, Is_even_MN, Is_even_K, Is_softcap, Split, Append_KV>(params, bidb, bidh, m_block, n_split_idx, num_n_splits); } //////////////////////////////////////////////////////////////////////////////////////////////////// template<typename Kernel_traits, int kBlockM, int Log_max_splits, bool Is_even_K, typename Params> inline __device__ void combine_attn_seqk_parallel(const Params &params) { using Element = typename Kernel_traits::Element; using ElementAccum = typename Kernel_traits::ElementAccum; using index_t = typename Kernel_traits::index_t; constexpr int kMaxSplits = 1 << Log_max_splits; constexpr int kHeadDim = Kernel_traits::kHeadDim; constexpr int kNThreads = Kernel_traits::kNThreads; static_assert(kMaxSplits <= 128, "kMaxSplits must be <= 128"); static_assert(kBlockM == 4 || kBlockM == 8 || kBlockM == 16 || kBlockM == 32, "kBlockM must be 4, 8, 16 or 32"); static_assert(kNThreads == 128, "We assume that each block has 128 threads"); // Shared memory. // kBlockM + 1 instead of kBlockM to reduce bank conflicts. __shared__ ElementAccum sLSE[kMaxSplits][kBlockM + 1]; // The thread and block index. const int tidx = threadIdx.x; const int bidx = blockIdx.x; const index_t lse_size = params.b * params.h * params.seqlen_q; const index_t row_offset_lse = bidx * kBlockM; Tensor gLSEaccum = make_tensor(make_gmem_ptr(reinterpret_cast<ElementAccum *>(params.softmax_lseaccum_ptr) + row_offset_lse), Shape<Int<kMaxSplits>, Int<kBlockM>>{}, make_stride(lse_size, _1{})); // LSE format is different depending on params.unpadded_lse and params.seqlenq_ngroups_swapped, see comment in get_lse_tile. // This tensor's layout maps row_offset_lse to {bidb, bidh, q_offset}. Tensor gLSE = make_tensor(make_gmem_ptr(reinterpret_cast<ElementAccum *>(params.softmax_lse_ptr) + row_offset_lse), Shape<Int<kBlockM>>{}, Stride<_1>{}); // This layout maps row_offset_lse to {bidh, q_offset, bidb} or {bidh, bidb, q_offset}. Layout flat_layout = make_layout(lse_size); Layout orig_layout = make_layout(make_shape(params.seqlen_q, params.h, params.b)); auto transposed_stride = params.seqlenq_ngroups_swapped ? make_stride(params.b, params.seqlen_q * params.b, 1) : make_stride(1, params.seqlen_q * params.b, params.seqlen_q); Layout remapped_layout = make_layout(make_shape(params.seqlen_q, params.h, params.b), transposed_stride); Layout final_layout = cute::composition(remapped_layout, cute::composition(orig_layout, flat_layout)); Tensor gLSE_unpadded = make_tensor(make_gmem_ptr(reinterpret_cast<ElementAccum *>(params.softmax_lse_ptr)), final_layout); constexpr int kNLsePerThread = (kMaxSplits * kBlockM + kNThreads - 1) / kNThreads; // Read the LSE values from gmem and store them in shared memory, then transpose them. constexpr int kRowsPerLoadLSE = kNThreads / kBlockM; #pragma unroll for (int l = 0; l < kNLsePerThread; ++l) { const int row = l * kRowsPerLoadLSE + tidx / kBlockM; const int col = tidx % kBlockM; ElementAccum lse = (row < params.num_splits && col < lse_size - bidx * kBlockM) ? gLSEaccum(row, col) : -INFINITY; if (row < kMaxSplits) { sLSE[row][col] = lse; } // if (bidx == 0 && tidx < 32) { printf("tidx = %d, row = %d, col = %d, lse = %f\n", tidx, row, col, lse); } } // if (bidx == 1 && tidx < 32) { printf("tidx = %d, row_offset_lse = %d, lse = %f\n", tidx, row_offset_lse, lse_accum(0)); } __syncthreads(); Tensor lse_accum = make_tensor<ElementAccum>(Shape<Int<kNLsePerThread>>{}); constexpr int kRowsPerLoadTranspose = std::min(kRowsPerLoadLSE, kMaxSplits); // To make sure that kMaxSplits is within 1 warp: we decide how many elements within kMaxSplits // each thread should hold. If kMaxSplits = 16, then each thread holds 2 elements (128 threads, // kBlockM rows, so each time we load we can load 128 / kBlockM rows). // constexpr int kThreadsPerSplit = kMaxSplits / kRowsPerLoadTranspose; // static_assert(kThreadsPerSplit <= 32); static_assert(kRowsPerLoadTranspose <= 32); static_assert(kNLsePerThread * kRowsPerLoadTranspose <= kMaxSplits); #pragma unroll for (int l = 0; l < kNLsePerThread; ++l) { const int row = l * kRowsPerLoadTranspose + tidx % kRowsPerLoadTranspose; const int col = tidx / kRowsPerLoadTranspose; lse_accum(l) = (row < kMaxSplits && col < kBlockM) ? sLSE[row][col] : -INFINITY; // if (bidx == 0 && tidx < 32) { printf("tidx = %d, row = %d, col = %d, lse = %f\n", tidx, row, col, lse_accum(l)); } } // Compute the logsumexp of the LSE along the split dimension. ElementAccum lse_max = lse_accum(0); #pragma unroll for (int l = 1; l < kNLsePerThread; ++l) { lse_max = max(lse_max, lse_accum(l)); } MaxOp<float> max_op; lse_max = Allreduce<kRowsPerLoadTranspose>::run(lse_max, max_op); lse_max = lse_max == -INFINITY ? 0.0f : lse_max; // In case all local LSEs are -inf float lse_sum = expf(lse_accum(0) - lse_max); #pragma unroll for (int l = 1; l < kNLsePerThread; ++l) { lse_sum += expf(lse_accum(l) - lse_max); } SumOp<float> sum_op; lse_sum = Allreduce<kRowsPerLoadTranspose>::run(lse_sum, sum_op); // For the case where all local lse == -INFINITY, we want to set lse_logsum to INFINITY. Otherwise // lse_logsum is log(0.0) = -INFINITY and we get NaN when we do lse_accum(l) - lse_logsum. ElementAccum lse_logsum = (lse_sum == 0.f || lse_sum != lse_sum) ? INFINITY : logf(lse_sum) + lse_max; // if (bidx == 0 && tidx < 32) { printf("tidx = %d, lse = %f, lse_max = %f, lse_logsum = %f\n", tidx, lse_accum(0), lse_max, lse_logsum); } if (tidx % kRowsPerLoadTranspose == 0 && tidx / kRowsPerLoadTranspose < kBlockM) { if (params.unpadded_lse) { const index_t lse_offset = row_offset_lse + tidx / kRowsPerLoadTranspose; if (lse_offset < lse_size) { gLSE_unpadded(lse_offset) = lse_logsum; } } else { gLSE(tidx / kRowsPerLoadTranspose) = lse_logsum; } } // Store the scales exp(lse - lse_logsum) in shared memory. #pragma unroll for (int l = 0; l < kNLsePerThread; ++l) { const int row = l * kRowsPerLoadTranspose + tidx % kRowsPerLoadTranspose; const int col = tidx / kRowsPerLoadTranspose; if (row < params.num_splits && col < kBlockM) { sLSE[row][col] = expf(lse_accum(l) - lse_logsum); } } __syncthreads(); const index_t row_offset_oaccum = bidx * kBlockM * params.d_rounded; Tensor gOaccum = make_tensor(make_gmem_ptr(reinterpret_cast<ElementAccum *>(params.oaccum_ptr) + row_offset_oaccum), Shape<Int<kBlockM>, Int<kHeadDim>>{}, Stride<Int<kHeadDim>, _1>{}); constexpr int kBlockN = kNThreads / kBlockM; using GmemLayoutAtomOaccum = Layout<Shape<Int<kBlockM>, Int<kBlockN>>, Stride<Int<kBlockN>, _1>>; using GmemTiledCopyOaccum = decltype( make_tiled_copy(Copy_Atom<AutoVectorizingCopyWithAssumedAlignment<128>, ElementAccum>{}, GmemLayoutAtomOaccum{}, Layout<Shape < _1, _4>>{})); // Val layout, 4 vals per store GmemTiledCopyOaccum gmem_tiled_copy_Oaccum; auto gmem_thr_copy_Oaccum = gmem_tiled_copy_Oaccum.get_thread_slice(tidx); Tensor tOgOaccum = gmem_thr_copy_Oaccum.partition_S(gOaccum); Tensor tOrO = make_tensor<ElementAccum>(shape(tOgOaccum)); Tensor tOrOaccum = make_tensor<ElementAccum>(shape(tOgOaccum)); clear(tOrO); // Predicates Tensor cOaccum = make_identity_tensor(Shape<Int<kBlockM>, Int<kHeadDim>>{}); // Repeat the partitioning with identity layouts Tensor tOcOaccum = gmem_thr_copy_Oaccum.partition_S(cOaccum); Tensor tOpOaccum = make_tensor<bool>(make_shape(size<2>(tOgOaccum))); if (!Is_even_K) { #pragma unroll for (int k = 0; k < size(tOpOaccum); ++k) { tOpOaccum(k) = get<1>(tOcOaccum(0, 0, k)) < params.d; } } // Load Oaccum in then scale and accumulate to O for (int split = 0; split < params.num_splits; ++split) { flash::copy</*Is_even_MN=*/false, Is_even_K>( gmem_tiled_copy_Oaccum, tOgOaccum, tOrOaccum, tOcOaccum, tOpOaccum, params.b * params.h * params.seqlen_q - bidx * kBlockM ); #pragma unroll for (int m = 0; m < size<1>(tOrOaccum); ++m) { int row = get<0>(tOcOaccum(0, m, 0)); ElementAccum lse_scale = sLSE[split][row]; #pragma unroll for (int k = 0; k < size<2>(tOrOaccum); ++k) { #pragma unroll for (int i = 0; i < size<0>(tOrOaccum); ++i) { tOrO(i, m, k) += lse_scale * tOrOaccum(i, m, k); } } // if (cute::thread0()) { printf("lse_scale = %f, %f\n", sLSE[split][0], sLSE[split][1]); print(tOrOaccum); } } tOgOaccum.data() = tOgOaccum.data() + params.b * params.h * params.seqlen_q * params.d_rounded; } // if (cute::thread0()) { print_tensor(tOrO); } Tensor rO = flash::convert_type<Element>(tOrO); // Write to gO #pragma unroll for (int m = 0; m < size<1>(rO); ++m) { const int idx = bidx * kBlockM + get<0>(tOcOaccum(0, m, 0)); if (idx < params.b * params.h * params.seqlen_q) { const int batch_idx = idx / (params.h * params.seqlen_q); const int head_idx = (idx - batch_idx * (params.h * params.seqlen_q)) / params.seqlen_q; // The index to the rows of Q const int row = idx - batch_idx * (params.h * params.seqlen_q) - head_idx * params.seqlen_q; auto o_ptr = reinterpret_cast<Element *>(params.o_ptr) + batch_idx * params.o_batch_stride + head_idx * params.o_head_stride + row * params.o_row_stride; #pragma unroll for (int k = 0; k < size<2>(rO); ++k) { if (Is_even_K || tOpOaccum(k)) { const int col = get<1>(tOcOaccum(0, m, k)); Tensor gO = make_tensor(make_gmem_ptr(o_ptr + col), Shape<Int<decltype(size<0>(rO))::value>>{}, Stride<_1>{}); // TODO: Should check if this is using vectorized store, but it seems pretty fast copy(rO(_, m, k), gO); // if (bidx == 0 && tidx == 0) { printf("tidx = %d, idx = %d, batch_idx = %d, head_idx = %d, row = %d, col = %d\n", tidx, idx, batch_idx, head_idx, row, col); print(rO(_, m, k)); print(gO); } // reinterpret_cast<uint64_t *>(o_ptr)[col / 4] = recast<uint64_t>(rO)(0, m, k); } } } } } } // namespace flash
candle/candle-flash-attn/kernels/flash_fwd_kernel.h/0
{ "file_path": "candle/candle-flash-attn/kernels/flash_fwd_kernel.h", "repo_id": "candle", "token_count": 37133 }
48
[package] name = "candle-kernels" version = "0.9.1" edition = "2021" description = "CUDA kernels for Candle" repository = "https://github.com/huggingface/candle" keywords = ["blas", "tensor", "machine-learning"] categories = ["science"] license = "MIT OR Apache-2.0" [dependencies] [build-dependencies] bindgen_cuda = "0.1.1"
candle/candle-kernels/Cargo.toml/0
{ "file_path": "candle/candle-kernels/Cargo.toml", "repo_id": "candle", "token_count": 126 }
49
// Adapted from https://github.com/ggerganov/llama.cpp/blob/master/ggml-cuda/argsort.cu #define SORT_ORDER_ASC 1 #define SORT_ORDER_DESC 0 #include "cuda_utils.cuh" #include<stdint.h> template<typename T> static inline __device__ void ggml_cuda_swap(T & a, T & b) { T tmp = a; a = b; b = tmp; } template<int order, typename T> static __device__ void k_argsort(const T * x, uint32_t * dst, const int ncols, int ncols_pad) { // bitonic sort int col = threadIdx.x; int row = blockIdx.x; if (col >= ncols_pad) { return; } const T * x_row = x + row * ncols; extern __shared__ int dst_row[]; // initialize indices dst_row[col] = col; __syncthreads(); for (int k = 2; k <= ncols_pad; k *= 2) { for (int j = k / 2; j > 0; j /= 2) { int ixj = col ^ j; if (ixj > col) { if ((col & k) == 0) { if (dst_row[col] >= ncols || (dst_row[ixj] < ncols && (order == SORT_ORDER_ASC ? x_row[dst_row[col]] > x_row[dst_row[ixj]] : x_row[dst_row[col]] < x_row[dst_row[ixj]])) ) { ggml_cuda_swap(dst_row[col], dst_row[ixj]); } } else { if (dst_row[ixj] >= ncols || (dst_row[col] < ncols && (order == SORT_ORDER_ASC ? x_row[dst_row[col]] < x_row[dst_row[ixj]] : x_row[dst_row[col]] > x_row[dst_row[ixj]])) ) { ggml_cuda_swap(dst_row[col], dst_row[ixj]); } } } __syncthreads(); } } // copy the result to dst without the padding if (col < ncols) { dst[row * ncols + col] = dst_row[col]; } } #define ASORT_OP(TYPENAME, RUST_NAME) \ extern "C" __global__ void asort_asc_##RUST_NAME( \ const TYPENAME * x, uint32_t * dst, const int ncols, int ncols_pad \ ) { \ k_argsort<SORT_ORDER_ASC>(x, dst, ncols, ncols_pad); \ } \ extern "C" __global__ void asort_desc_##RUST_NAME( \ const TYPENAME * x, uint32_t * dst, const int ncols, int ncols_pad \ ) { \ k_argsort<SORT_ORDER_DESC>(x, dst, ncols, ncols_pad); \ } \ #if __CUDA_ARCH__ >= 800 ASORT_OP(__nv_bfloat16, bf16) // NOTE: No sort ops for f8 // ASORT_OP(__nv_fp8_e4m3, fp8_e4m3) #endif #if __CUDA_ARCH__ >= 530 ASORT_OP(__half, f16) #endif ASORT_OP(float, f32) ASORT_OP(double, f64) ASORT_OP(uint8_t, u8) ASORT_OP(uint32_t, u32) ASORT_OP(int64_t, i64)
candle/candle-kernels/src/sort.cu/0
{ "file_path": "candle/candle-kernels/src/sort.cu", "repo_id": "candle", "token_count": 1507 }
50
#include <metal_stdlib> using namespace metal; #define MAX(x, y) ((x) > (y) ? (x) : (y)) #define MIN(x, y) ((x) < (y) ? (x) : (y)) #define SWAP(x, y) { auto tmp = (x); (x) = (y); (y) = tmp; } #define N_SIMDWIDTH 32 // assuming SIMD group size is 32 #if defined(__HAVE_BFLOAT__) typedef matrix<bfloat, 4, 4> bfloat4x4; #endif // QK = number of values after dequantization // QK_K = super-block size #define QK_K 256 #define K_SCALE_SIZE 12 #define QK4_0 32 typedef struct { half d; // delta uint8_t qs[QK4_0 / 2]; // nibbles / quants } block_q4_0; static_assert(sizeof(block_q4_0) == sizeof(half) + QK4_0 / 2, "wrong q4_0 block size/padding"); #define QK4_1 32 typedef struct { union { struct { half d; // delta half m; // min }; half2 dm; }; uint8_t qs[QK4_1 / 2]; // nibbles / quants } block_q4_1; static_assert(sizeof(block_q4_1) == 2 * sizeof(half) + QK4_1 / 2, "wrong q4_1 block size/padding"); #define QK5_0 32 typedef struct { half d; // delta uint8_t qh[4]; // 5-th bit of quants uint8_t qs[QK5_0 / 2]; // nibbles / quants } block_q5_0; static_assert(sizeof(block_q5_0) == sizeof(half) + sizeof(uint32_t) + QK5_0 / 2, "wrong q5_0 block size/padding"); #define QK5_1 32 typedef struct { union { struct { half d; // delta half m; // min }; half2 dm; }; uint8_t qh[4]; // 5-th bit of quants uint8_t qs[QK5_1 / 2]; // nibbles / quants } block_q5_1; static_assert(sizeof(block_q5_1) == 2 * sizeof(half) + sizeof(uint32_t) + QK5_1 / 2, "wrong q5_1 block size/padding"); #define QK8_0 32 typedef struct { half d; // delta int8_t qs[QK8_0]; // quants } block_q8_0; static_assert(sizeof(block_q8_0) == sizeof(half) + QK8_0, "wrong q8_0 block size/padding"); #define QK8_1 32 typedef struct { union { struct { half d; // delta half s; // d * sum(qs[i]) }; half2 ds; }; int8_t qs[QK8_1]; // quants } block_q8_1; static_assert(sizeof(block_q8_1) == 2*sizeof(half) + QK8_1, "wrong q8_1 block size/padding"); typedef struct { half d[4]; // deltas for 4 q4_0 blocks uint8_t qs[QK4_0 * 2]; // nibbles / quants for 4 q4_0 blocks } block_q4_0x4; static_assert(sizeof(block_q4_0x4) == 4 * sizeof(half) + QK4_0 * 2, "wrong q4_0x4 block size/padding"); typedef struct { half d[8]; // deltas for 8 q4_0 blocks uint8_t qs[QK4_0 * 4]; // nibbles / quants for 8 q4_0 blocks } block_q4_0x8; static_assert(sizeof(block_q4_0x8) == 8 * sizeof(half) + QK4_0 * 4, "wrong q4_0x8 block size/padding"); typedef struct { half d[4]; // deltas for 4 q8_0 blocks int8_t qs[QK8_0 * 4]; // quants for 4 q8_0 blocks } block_q8_0x4; static_assert(sizeof(block_q8_0x4) == 4 * sizeof(half) + QK8_0 * 4, "wrong q8_0x4 block size/padding"); typedef struct { half d[8]; // deltas for 8 q8_0 blocks int8_t qs[QK8_0 * 8]; // quants for 8 q8_0 blocks } block_q8_0x8; static_assert(sizeof(block_q8_0x8) == 8 * sizeof(half) + QK8_0 * 8, "wrong q8_0x8 block size/padding"); // // Ternary quantization // // 1.6875 bpw typedef struct { uint8_t qs[(QK_K - 4 * QK_K / 64) / 5]; // 5 elements per byte (3^5 = 243 < 256) uint8_t qh[QK_K/64]; // 4 elements per byte half d; } block_tq1_0; static_assert(sizeof(block_tq1_0) == sizeof(half) + QK_K / 64 + (QK_K - 4 * QK_K / 64) / 5, "wrong tq1_0 block size/padding"); // 2.0625 bpw typedef struct { uint8_t qs[QK_K/4]; // 2 bits per element half d; } block_tq2_0; static_assert(sizeof(block_tq2_0) == sizeof(half) + QK_K / 4, "wrong tq2_0 block size/padding"); // // Super-block quantization structures // // 2-bit quantization // weight is represented as x = a * q + b // 16 blocks of 16 elements each // Effectively 2.625 bits per weight typedef struct { uint8_t scales[QK_K/16]; // scales and mins, quantized with 4 bits uint8_t qs[QK_K/4]; // quants union { struct { half d; // super-block scale for quantized scales half dmin; // super-block scale for quantized mins }; half2 dm; }; } block_q2_K; static_assert(sizeof(block_q2_K) == 2*sizeof(half) + QK_K/16 + QK_K/4, "wrong q2_K block size/padding"); // 3-bit quantization // weight is represented as x = a * q // 16 blocks of 16 elements each // Effectively 3.4375 bits per weight typedef struct { uint8_t hmask[QK_K/8]; // quants - high bit uint8_t qs[QK_K/4]; // quants - low 2 bits uint8_t scales[12]; // scales, quantized with 6 bits half d; // super-block scale } block_q3_K; static_assert(sizeof(block_q3_K) == sizeof(half) + QK_K / 4 + QK_K / 8 + 12, "wrong q3_K block size/padding"); // 4-bit quantization // 8 blocks of 32 elements each // weight is represented as x = a * q + b // Effectively 4.5 bits per weight typedef struct { union { struct { half d; // super-block scale for quantized scales half dmin; // super-block scale for quantized mins }; half2 dm; }; uint8_t scales[K_SCALE_SIZE]; // scales and mins, quantized with 6 bits uint8_t qs[QK_K/2]; // 4--bit quants } block_q4_K; static_assert(sizeof(block_q4_K) == 2*sizeof(half) + K_SCALE_SIZE + QK_K/2, "wrong q4_K block size/padding"); // 5-bit quantization // 8 blocks of 32 elements each // weight is represented as x = a * q + b // Effectively 5.5 bits per weight typedef struct { union { struct { half d; // super-block scale for quantized scales half dmin; // super-block scale for quantized mins }; half2 dm; }; uint8_t scales[K_SCALE_SIZE]; // scales and mins, quantized with 6 bits uint8_t qh[QK_K/8]; // quants, high bit uint8_t qs[QK_K/2]; // quants, low 4 bits } block_q5_K; static_assert(sizeof(block_q5_K) == 2*sizeof(half) + K_SCALE_SIZE + QK_K/2 + QK_K/8, "wrong q5_K block size/padding"); // 6-bit quantization // weight is represented as x = a * q // 16 blocks of 16 elements each // Effectively 6.5625 bits per weight typedef struct { uint8_t ql[QK_K/2]; // quants, lower 4 bits uint8_t qh[QK_K/4]; // quants, upper 2 bits int8_t scales[QK_K/16]; // scales, quantized with 8 bits half d; // super-block scale } block_q6_K; static_assert(sizeof(block_q6_K) == sizeof(half) + QK_K / 16 + 3*QK_K/4, "wrong q6_K block size/padding"); // This is only used for intermediate quantization and dot products typedef struct { float d; // delta int8_t qs[QK_K]; // quants int16_t bsums[QK_K/16]; // sum of quants in groups of 16 } block_q8_K; static_assert(sizeof(block_q8_K) == sizeof(float) + QK_K + QK_K/16*sizeof(int16_t), "wrong q8_K block size/padding"); // (Almost) "true" 2-bit quantization. // Due to the need to use blocks as per ggml design, it ends up using // 2.0625 bpw because of the 16-bit scale for each block of 256. typedef struct { half d; uint16_t qs[QK_K/8]; } block_iq2_xxs; static_assert(sizeof(block_iq2_xxs) == sizeof(half) + QK_K/8*sizeof(uint16_t), "wrong iq2_xxs block size/padding"); // 2.3125 bpw quants typedef struct { half d; uint16_t qs[QK_K/8]; uint8_t scales[QK_K/32]; } block_iq2_xs; static_assert(sizeof(block_iq2_xs) == sizeof(half) + QK_K/8*sizeof(uint16_t) + QK_K/32, "wrong iq2_xs block size/padding"); // 2.5625 bpw quants typedef struct { half d; uint8_t qs[QK_K/4]; uint8_t qh[QK_K/32]; uint8_t scales[QK_K/32]; } block_iq2_s; static_assert(sizeof(block_iq2_s) == sizeof(half) + QK_K/4 + QK_K/16, "wrong iq2_s block size/padding"); // (Almost) "true" 3-bit quantization. // Due to the need to use blocks as per ggml design, it ends up using // 3.0625 bpw because of the 16-bit scale for each block of 256. typedef struct { half d; uint8_t qs[3*QK_K/8]; } block_iq3_xxs; static_assert(sizeof(block_iq3_xxs) == sizeof(half) + 3*(QK_K/8), "wrong iq3_xxs block size/padding"); // 3.4375 bpw #define IQ3S_N_SCALE QK_K/64 typedef struct { half d; uint8_t qs[QK_K/4]; uint8_t qh[QK_K/32]; uint8_t signs[QK_K/8]; uint8_t scales[IQ3S_N_SCALE]; } block_iq3_s; static_assert(sizeof(block_iq3_s) == sizeof(half) + 13*(QK_K/32) + IQ3S_N_SCALE, "wrong iq3_s block size/padding"); // 1.5625 bpw typedef struct { half d; uint8_t qs[QK_K/8]; uint16_t qh[QK_K/32]; } block_iq1_s; static_assert(sizeof(block_iq1_s) == sizeof(half) + QK_K/8 + QK_K/16, "wrong iq1_s block size/padding"); // 1.75 bpw typedef struct { uint8_t qs[QK_K/8]; // grid index, low 8 bits uint8_t qh[QK_K/16]; // grid index, high 3 bits + grid shift bit (for two groups of 8) uint8_t scales[QK_K/32]; // 3-bit block scales (4-bit if QK_K == 64) } block_iq1_m; static_assert(sizeof(block_iq1_m) == QK_K/8 + QK_K/16 + QK_K/32, "wrong iq1_m block size/padding"); // Used by IQ1_M quants typedef union { half f16; uint16_t u16; } iq1m_scale_t; // Non-linear quants #define QK4_NL 32 typedef struct { half d; uint8_t qs[QK4_NL/2]; } block_iq4_nl; static_assert(sizeof(block_iq4_nl) == sizeof(half) + QK4_NL/2, "wrong iq4_nl block size/padding"); typedef struct { half d; uint16_t scales_h; uint8_t scales_l[QK_K/64]; uint8_t qs[QK_K/2]; } block_iq4_xs; static_assert(sizeof(block_iq4_xs) == sizeof(half) + sizeof(uint16_t) + QK_K/64 + QK_K/2, "wrong iq4_xs block size/padding"); #define GGML_TABLE_BEGIN(type, name, size) static const constant type name[size] = { #define GGML_TABLE_END() }; GGML_TABLE_BEGIN(uint8_t, kmask_iq2xs, 8) 1, 2, 4, 8, 16, 32, 64, 128 GGML_TABLE_END() GGML_TABLE_BEGIN(uint8_t, ksigns_iq2xs, 128) 0, 129, 130, 3, 132, 5, 6, 135, 136, 9, 10, 139, 12, 141, 142, 15, 144, 17, 18, 147, 20, 149, 150, 23, 24, 153, 154, 27, 156, 29, 30, 159, 160, 33, 34, 163, 36, 165, 166, 39, 40, 169, 170, 43, 172, 45, 46, 175, 48, 177, 178, 51, 180, 53, 54, 183, 184, 57, 58, 187, 60, 189, 190, 63, 192, 65, 66, 195, 68, 197, 198, 71, 72, 201, 202, 75, 204, 77, 78, 207, 80, 209, 210, 83, 212, 85, 86, 215, 216, 89, 90, 219, 92, 221, 222, 95, 96, 225, 226, 99, 228, 101, 102, 231, 232, 105, 106, 235, 108, 237, 238, 111, 240, 113, 114, 243, 116, 245, 246, 119, 120, 249, 250, 123, 252, 125, 126, 255, GGML_TABLE_END() //#if __CUDA_ARCH__ >= MIN_CC_DP4A // lowest compute capability for integer intrinsics GGML_TABLE_BEGIN(uint64_t, ksigns64, 128) 0x0000000000000000, 0xff000000000000ff, 0xff0000000000ff00, 0x000000000000ffff, 0xff00000000ff0000, 0x0000000000ff00ff, 0x0000000000ffff00, 0xff00000000ffffff, 0xff000000ff000000, 0x00000000ff0000ff, 0x00000000ff00ff00, 0xff000000ff00ffff, 0x00000000ffff0000, 0xff000000ffff00ff, 0xff000000ffffff00, 0x00000000ffffffff, 0xff0000ff00000000, 0x000000ff000000ff, 0x000000ff0000ff00, 0xff0000ff0000ffff, 0x000000ff00ff0000, 0xff0000ff00ff00ff, 0xff0000ff00ffff00, 0x000000ff00ffffff, 0x000000ffff000000, 0xff0000ffff0000ff, 0xff0000ffff00ff00, 0x000000ffff00ffff, 0xff0000ffffff0000, 0x000000ffffff00ff, 0x000000ffffffff00, 0xff0000ffffffffff, 0xff00ff0000000000, 0x0000ff00000000ff, 0x0000ff000000ff00, 0xff00ff000000ffff, 0x0000ff0000ff0000, 0xff00ff0000ff00ff, 0xff00ff0000ffff00, 0x0000ff0000ffffff, 0x0000ff00ff000000, 0xff00ff00ff0000ff, 0xff00ff00ff00ff00, 0x0000ff00ff00ffff, 0xff00ff00ffff0000, 0x0000ff00ffff00ff, 0x0000ff00ffffff00, 0xff00ff00ffffffff, 0x0000ffff00000000, 0xff00ffff000000ff, 0xff00ffff0000ff00, 0x0000ffff0000ffff, 0xff00ffff00ff0000, 0x0000ffff00ff00ff, 0x0000ffff00ffff00, 0xff00ffff00ffffff, 0xff00ffffff000000, 0x0000ffffff0000ff, 0x0000ffffff00ff00, 0xff00ffffff00ffff, 0x0000ffffffff0000, 0xff00ffffffff00ff, 0xff00ffffffffff00, 0x0000ffffffffffff, 0xffff000000000000, 0x00ff0000000000ff, 0x00ff00000000ff00, 0xffff00000000ffff, 0x00ff000000ff0000, 0xffff000000ff00ff, 0xffff000000ffff00, 0x00ff000000ffffff, 0x00ff0000ff000000, 0xffff0000ff0000ff, 0xffff0000ff00ff00, 0x00ff0000ff00ffff, 0xffff0000ffff0000, 0x00ff0000ffff00ff, 0x00ff0000ffffff00, 0xffff0000ffffffff, 0x00ff00ff00000000, 0xffff00ff000000ff, 0xffff00ff0000ff00, 0x00ff00ff0000ffff, 0xffff00ff00ff0000, 0x00ff00ff00ff00ff, 0x00ff00ff00ffff00, 0xffff00ff00ffffff, 0xffff00ffff000000, 0x00ff00ffff0000ff, 0x00ff00ffff00ff00, 0xffff00ffff00ffff, 0x00ff00ffffff0000, 0xffff00ffffff00ff, 0xffff00ffffffff00, 0x00ff00ffffffffff, 0x00ffff0000000000, 0xffffff00000000ff, 0xffffff000000ff00, 0x00ffff000000ffff, 0xffffff0000ff0000, 0x00ffff0000ff00ff, 0x00ffff0000ffff00, 0xffffff0000ffffff, 0xffffff00ff000000, 0x00ffff00ff0000ff, 0x00ffff00ff00ff00, 0xffffff00ff00ffff, 0x00ffff00ffff0000, 0xffffff00ffff00ff, 0xffffff00ffffff00, 0x00ffff00ffffffff, 0xffffffff00000000, 0x00ffffff000000ff, 0x00ffffff0000ff00, 0xffffffff0000ffff, 0x00ffffff00ff0000, 0xffffffff00ff00ff, 0xffffffff00ffff00, 0x00ffffff00ffffff, 0x00ffffffff000000, 0xffffffffff0000ff, 0xffffffffff00ff00, 0x00ffffffff00ffff, 0xffffffffffff0000, 0x00ffffffffff00ff, 0x00ffffffffffff00, 0xffffffffffffffff, GGML_TABLE_END() //#endif GGML_TABLE_BEGIN(uint64_t, iq2xxs_grid, 256) 0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08, 0x0808080808082b2b, 0x0808080808190819, 0x0808080808191908, 0x08080808082b0808, 0x08080808082b082b, 0x08080808082b2b08, 0x08080808082b2b2b, 0x0808080819080819, 0x0808080819081908, 0x0808080819190808, 0x0808080819192b08, 0x08080808192b0819, 0x08080808192b1908, 0x080808082b080808, 0x080808082b08082b, 0x080808082b082b2b, 0x080808082b2b082b, 0x0808081908080819, 0x0808081908081908, 0x0808081908190808, 0x0808081908191919, 0x0808081919080808, 0x080808192b081908, 0x080808192b192b08, 0x0808082b08080808, 0x0808082b0808082b, 0x0808082b082b082b, 0x0808082b2b08082b, 0x0808190808080819, 0x0808190808081908, 0x0808190808190808, 0x08081908082b0819, 0x08081908082b1908, 0x0808190819080808, 0x080819081908082b, 0x0808190819082b08, 0x08081908192b0808, 0x080819082b080819, 0x080819082b081908, 0x080819082b190808, 0x080819082b2b1908, 0x0808191908080808, 0x080819190808082b, 0x0808191908082b08, 0x08081919082b0808, 0x080819191908192b, 0x08081919192b2b19, 0x080819192b080808, 0x080819192b190819, 0x0808192b08082b19, 0x0808192b08190808, 0x0808192b19080808, 0x0808192b2b081908, 0x0808192b2b2b1908, 0x08082b0808080808, 0x08082b0808081919, 0x08082b0808082b08, 0x08082b0808191908, 0x08082b08082b2b08, 0x08082b0819080819, 0x08082b0819081908, 0x08082b0819190808, 0x08082b081919082b, 0x08082b082b082b08, 0x08082b1908081908, 0x08082b1919080808, 0x08082b2b0808082b, 0x08082b2b08191908, 0x0819080808080819, 0x0819080808081908, 0x0819080808190808, 0x08190808082b0819, 0x0819080819080808, 0x08190808192b0808, 0x081908082b081908, 0x081908082b190808, 0x081908082b191919, 0x0819081908080808, 0x0819081908082b08, 0x08190819082b0808, 0x0819081919190808, 0x0819081919192b2b, 0x081908192b080808, 0x0819082b082b1908, 0x0819082b19081919, 0x0819190808080808, 0x0819190808082b08, 0x08191908082b0808, 0x08191908082b1919, 0x0819190819082b19, 0x081919082b080808, 0x0819191908192b08, 0x08191919192b082b, 0x0819192b08080808, 0x0819192b0819192b, 0x08192b0808080819, 0x08192b0808081908, 0x08192b0808190808, 0x08192b0819080808, 0x08192b082b080819, 0x08192b1908080808, 0x08192b1908081919, 0x08192b192b2b0808, 0x08192b2b19190819, 0x082b080808080808, 0x082b08080808082b, 0x082b080808082b2b, 0x082b080819081908, 0x082b0808192b0819, 0x082b08082b080808, 0x082b08082b08082b, 0x082b0819082b2b19, 0x082b081919082b08, 0x082b082b08080808, 0x082b082b0808082b, 0x082b190808080819, 0x082b190808081908, 0x082b190808190808, 0x082b190819080808, 0x082b19081919192b, 0x082b191908080808, 0x082b191919080819, 0x082b1919192b1908, 0x082b192b2b190808, 0x082b2b0808082b08, 0x082b2b08082b0808, 0x082b2b082b191908, 0x082b2b2b19081908, 0x1908080808080819, 0x1908080808081908, 0x1908080808190808, 0x1908080808192b08, 0x19080808082b0819, 0x19080808082b1908, 0x1908080819080808, 0x1908080819082b08, 0x190808081919192b, 0x19080808192b0808, 0x190808082b080819, 0x190808082b081908, 0x190808082b190808, 0x1908081908080808, 0x19080819082b0808, 0x19080819192b0819, 0x190808192b080808, 0x190808192b081919, 0x1908082b08080819, 0x1908082b08190808, 0x1908082b19082b08, 0x1908082b1919192b, 0x1908082b192b2b08, 0x1908190808080808, 0x1908190808082b08, 0x19081908082b0808, 0x190819082b080808, 0x190819082b192b19, 0x190819190819082b, 0x19081919082b1908, 0x1908192b08080808, 0x19082b0808080819, 0x19082b0808081908, 0x19082b0808190808, 0x19082b0819080808, 0x19082b0819081919, 0x19082b1908080808, 0x19082b1919192b08, 0x19082b19192b0819, 0x19082b192b08082b, 0x19082b2b19081919, 0x19082b2b2b190808, 0x1919080808080808, 0x1919080808082b08, 0x1919080808190819, 0x1919080808192b19, 0x19190808082b0808, 0x191908082b080808, 0x191908082b082b08, 0x1919081908081908, 0x191908191908082b, 0x191908192b2b1908, 0x1919082b2b190819, 0x191919082b190808, 0x191919082b19082b, 0x1919191908082b2b, 0x1919192b08080819, 0x1919192b19191908, 0x19192b0808080808, 0x19192b0808190819, 0x19192b0808192b19, 0x19192b08192b1908, 0x19192b1919080808, 0x19192b2b08082b08, 0x192b080808081908, 0x192b080808190808, 0x192b080819080808, 0x192b0808192b2b08, 0x192b081908080808, 0x192b081919191919, 0x192b082b08192b08, 0x192b082b192b0808, 0x192b190808080808, 0x192b190808081919, 0x192b191908190808, 0x192b19190819082b, 0x192b19192b081908, 0x192b2b081908082b, 0x2b08080808080808, 0x2b0808080808082b, 0x2b08080808082b2b, 0x2b08080819080819, 0x2b0808082b08082b, 0x2b08081908081908, 0x2b08081908192b08, 0x2b08081919080808, 0x2b08082b08190819, 0x2b08190808080819, 0x2b08190808081908, 0x2b08190808190808, 0x2b08190808191919, 0x2b08190819080808, 0x2b081908192b0808, 0x2b08191908080808, 0x2b0819191908192b, 0x2b0819192b191908, 0x2b08192b08082b19, 0x2b08192b19080808, 0x2b08192b192b0808, 0x2b082b080808082b, 0x2b082b1908081908, 0x2b082b2b08190819, 0x2b19080808081908, 0x2b19080808190808, 0x2b190808082b1908, 0x2b19080819080808, 0x2b1908082b2b0819, 0x2b1908190819192b, 0x2b1908192b080808, 0x2b19082b19081919, 0x2b19190808080808, 0x2b191908082b082b, 0x2b19190819081908, 0x2b19191919190819, 0x2b192b082b080819, 0x2b192b19082b0808, 0x2b2b08080808082b, 0x2b2b080819190808, 0x2b2b08082b081919, 0x2b2b081908082b19, 0x2b2b082b08080808, 0x2b2b190808192b08, 0x2b2b2b0819190808, 0x2b2b2b1908081908, GGML_TABLE_END() GGML_TABLE_BEGIN(uint64_t, iq2xs_grid, 512) 0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08, 0x0808080808082b2b, 0x0808080808190819, 0x0808080808191908, 0x080808080819192b, 0x0808080808192b19, 0x08080808082b0808, 0x08080808082b082b, 0x08080808082b1919, 0x08080808082b2b08, 0x0808080819080819, 0x0808080819081908, 0x080808081908192b, 0x0808080819082b19, 0x0808080819190808, 0x080808081919082b, 0x0808080819191919, 0x0808080819192b08, 0x08080808192b0819, 0x08080808192b1908, 0x080808082b080808, 0x080808082b08082b, 0x080808082b081919, 0x080808082b082b08, 0x080808082b190819, 0x080808082b191908, 0x080808082b192b19, 0x080808082b2b0808, 0x0808081908080819, 0x0808081908081908, 0x080808190808192b, 0x0808081908082b19, 0x0808081908190808, 0x080808190819082b, 0x0808081908191919, 0x0808081908192b08, 0x0808081908192b2b, 0x08080819082b0819, 0x08080819082b1908, 0x0808081919080808, 0x080808191908082b, 0x0808081919081919, 0x0808081919082b08, 0x0808081919190819, 0x0808081919191908, 0x08080819192b0808, 0x08080819192b2b08, 0x080808192b080819, 0x080808192b081908, 0x080808192b190808, 0x0808082b08080808, 0x0808082b0808082b, 0x0808082b08081919, 0x0808082b08082b08, 0x0808082b08190819, 0x0808082b08191908, 0x0808082b082b0808, 0x0808082b19080819, 0x0808082b19081908, 0x0808082b19190808, 0x0808082b19191919, 0x0808082b2b080808, 0x0808082b2b082b2b, 0x0808190808080819, 0x0808190808081908, 0x080819080808192b, 0x0808190808082b19, 0x0808190808190808, 0x080819080819082b, 0x0808190808191919, 0x0808190808192b08, 0x08081908082b0819, 0x08081908082b1908, 0x0808190819080808, 0x080819081908082b, 0x0808190819081919, 0x0808190819082b08, 0x0808190819190819, 0x0808190819191908, 0x080819081919192b, 0x08081908192b0808, 0x080819082b080819, 0x080819082b081908, 0x080819082b190808, 0x0808191908080808, 0x080819190808082b, 0x0808191908081919, 0x0808191908082b08, 0x0808191908190819, 0x0808191908191908, 0x08081919082b0808, 0x0808191919080819, 0x0808191919081908, 0x0808191919190808, 0x08081919192b0819, 0x080819192b080808, 0x0808192b08080819, 0x0808192b08081908, 0x0808192b08190808, 0x0808192b082b192b, 0x0808192b19080808, 0x0808192b1908082b, 0x0808192b2b081908, 0x08082b0808080808, 0x08082b080808082b, 0x08082b0808081919, 0x08082b0808082b08, 0x08082b0808082b2b, 0x08082b0808190819, 0x08082b0808191908, 0x08082b08082b0808, 0x08082b08082b1919, 0x08082b0819080819, 0x08082b0819081908, 0x08082b0819190808, 0x08082b0819192b08, 0x08082b082b080808, 0x08082b082b2b0808, 0x08082b082b2b2b2b, 0x08082b1908080819, 0x08082b1908081908, 0x08082b1908190808, 0x08082b1919080808, 0x08082b192b080819, 0x08082b192b082b19, 0x08082b2b08080808, 0x08082b2b082b0808, 0x08082b2b082b2b08, 0x08082b2b2b19192b, 0x08082b2b2b2b0808, 0x0819080808080819, 0x0819080808081908, 0x081908080808192b, 0x0819080808082b19, 0x0819080808190808, 0x081908080819082b, 0x0819080808191919, 0x0819080808192b08, 0x08190808082b0819, 0x08190808082b1908, 0x0819080819080808, 0x081908081908082b, 0x0819080819081919, 0x0819080819082b08, 0x0819080819190819, 0x0819080819191908, 0x08190808192b0808, 0x08190808192b2b2b, 0x081908082b080819, 0x081908082b081908, 0x081908082b190808, 0x0819081908080808, 0x081908190808082b, 0x0819081908081919, 0x0819081908082b08, 0x0819081908190819, 0x0819081908191908, 0x08190819082b0808, 0x0819081919080819, 0x0819081919081908, 0x0819081919190808, 0x081908192b080808, 0x081908192b191908, 0x081908192b19192b, 0x0819082b08080819, 0x0819082b08081908, 0x0819082b0808192b, 0x0819082b08190808, 0x0819082b19080808, 0x0819082b192b0808, 0x0819190808080808, 0x081919080808082b, 0x0819190808081919, 0x0819190808082b08, 0x0819190808190819, 0x0819190808191908, 0x08191908082b0808, 0x0819190819080819, 0x0819190819081908, 0x0819190819082b19, 0x0819190819190808, 0x08191908192b1908, 0x081919082b080808, 0x0819191908080819, 0x0819191908081908, 0x0819191908190808, 0x0819191919080808, 0x0819192b08080808, 0x0819192b08191908, 0x0819192b19082b19, 0x08192b0808080819, 0x08192b0808081908, 0x08192b0808190808, 0x08192b080819082b, 0x08192b0819080808, 0x08192b0819191908, 0x08192b082b08192b, 0x08192b1908080808, 0x08192b1908081919, 0x08192b19192b192b, 0x08192b2b19190819, 0x08192b2b2b2b2b19, 0x082b080808080808, 0x082b08080808082b, 0x082b080808081919, 0x082b080808082b08, 0x082b080808082b2b, 0x082b080808190819, 0x082b080808191908, 0x082b0808082b0808, 0x082b080819080819, 0x082b080819081908, 0x082b080819190808, 0x082b08082b080808, 0x082b08082b2b0808, 0x082b081908080819, 0x082b081908081908, 0x082b081908190808, 0x082b081919080808, 0x082b081919082b08, 0x082b0819192b1919, 0x082b082b08080808, 0x082b082b082b082b, 0x082b082b2b080808, 0x082b082b2b2b2b08, 0x082b190808080819, 0x082b190808081908, 0x082b190808190808, 0x082b1908082b2b19, 0x082b190819080808, 0x082b191908080808, 0x082b191919080819, 0x082b19191919082b, 0x082b19192b192b19, 0x082b192b08080819, 0x082b192b08192b2b, 0x082b192b2b2b192b, 0x082b2b0808080808, 0x082b2b0808082b08, 0x082b2b0808082b2b, 0x082b2b08082b0808, 0x082b2b0819191919, 0x082b2b082b082b08, 0x082b2b082b2b082b, 0x082b2b19192b2b08, 0x082b2b192b190808, 0x082b2b2b08082b08, 0x082b2b2b082b0808, 0x082b2b2b2b08082b, 0x082b2b2b2b082b08, 0x082b2b2b2b082b2b, 0x1908080808080819, 0x1908080808081908, 0x190808080808192b, 0x1908080808082b19, 0x1908080808190808, 0x190808080819082b, 0x1908080808191919, 0x1908080808192b08, 0x19080808082b0819, 0x19080808082b1908, 0x1908080819080808, 0x190808081908082b, 0x1908080819081919, 0x1908080819082b08, 0x1908080819082b2b, 0x1908080819190819, 0x1908080819191908, 0x19080808192b0808, 0x19080808192b1919, 0x190808082b080819, 0x190808082b081908, 0x190808082b190808, 0x1908081908080808, 0x190808190808082b, 0x1908081908081919, 0x1908081908082b08, 0x1908081908190819, 0x1908081908191908, 0x19080819082b0808, 0x1908081919080819, 0x1908081919081908, 0x1908081919190808, 0x190808192b080808, 0x190808192b081919, 0x190808192b2b082b, 0x1908082b08080819, 0x1908082b08081908, 0x1908082b08190808, 0x1908082b0819082b, 0x1908082b082b2b19, 0x1908082b19080808, 0x1908190808080808, 0x190819080808082b, 0x1908190808081919, 0x1908190808082b08, 0x1908190808190819, 0x1908190808191908, 0x1908190808192b19, 0x19081908082b0808, 0x1908190819080819, 0x1908190819081908, 0x1908190819190808, 0x190819082b080808, 0x190819082b191908, 0x1908191908080819, 0x1908191908081908, 0x1908191908190808, 0x19081919082b1908, 0x1908191919080808, 0x190819192b192b2b, 0x1908192b08080808, 0x1908192b08082b2b, 0x1908192b19081908, 0x1908192b19190808, 0x19082b0808080819, 0x19082b0808081908, 0x19082b0808190808, 0x19082b0819080808, 0x19082b0819081919, 0x19082b0819191908, 0x19082b08192b082b, 0x19082b1908080808, 0x19082b1908190819, 0x19082b1919081908, 0x19082b1919190808, 0x19082b19192b2b19, 0x19082b2b08081908, 0x1919080808080808, 0x191908080808082b, 0x1919080808081919, 0x1919080808082b08, 0x1919080808190819, 0x1919080808191908, 0x19190808082b0808, 0x19190808082b2b08, 0x1919080819080819, 0x1919080819081908, 0x1919080819190808, 0x191908082b080808, 0x1919081908080819, 0x1919081908081908, 0x1919081908190808, 0x1919081908191919, 0x1919081919080808, 0x191908191908082b, 0x1919082b08080808, 0x1919082b19081908, 0x1919082b2b2b2b2b, 0x1919190808080819, 0x1919190808081908, 0x1919190808190808, 0x19191908082b0819, 0x1919190819080808, 0x19191908192b0808, 0x191919082b080819, 0x191919082b2b0819, 0x1919191908080808, 0x1919191908082b08, 0x191919192b080808, 0x191919192b082b08, 0x1919192b082b0819, 0x1919192b192b2b08, 0x1919192b2b2b0819, 0x19192b0808080808, 0x19192b0808191908, 0x19192b0819080819, 0x19192b0819190808, 0x19192b082b192b19, 0x19192b1908192b2b, 0x19192b1919080808, 0x19192b191908082b, 0x19192b2b2b081919, 0x192b080808080819, 0x192b080808081908, 0x192b080808190808, 0x192b080819080808, 0x192b080819191908, 0x192b0808192b082b, 0x192b08082b08192b, 0x192b08082b2b2b19, 0x192b081908080808, 0x192b082b082b1908, 0x192b082b19082b2b, 0x192b082b2b19082b, 0x192b190808080808, 0x192b19080819192b, 0x192b191908190808, 0x192b191919080808, 0x192b191919081919, 0x192b19192b2b1908, 0x192b2b0808080819, 0x192b2b08192b2b2b, 0x192b2b19082b1919, 0x192b2b2b0808192b, 0x192b2b2b19191908, 0x192b2b2b192b082b, 0x2b08080808080808, 0x2b0808080808082b, 0x2b08080808081919, 0x2b08080808082b08, 0x2b08080808190819, 0x2b08080808191908, 0x2b080808082b0808, 0x2b080808082b2b2b, 0x2b08080819080819, 0x2b08080819081908, 0x2b08080819190808, 0x2b0808082b080808, 0x2b0808082b08082b, 0x2b0808082b2b2b08, 0x2b0808082b2b2b2b, 0x2b08081908080819, 0x2b08081908081908, 0x2b0808190808192b, 0x2b08081908190808, 0x2b08081919080808, 0x2b08081919190819, 0x2b08081919192b19, 0x2b08082b08080808, 0x2b08082b082b0808, 0x2b08082b2b080808, 0x2b08082b2b08082b, 0x2b08082b2b2b0808, 0x2b08082b2b2b2b08, 0x2b08190808080819, 0x2b08190808081908, 0x2b08190808190808, 0x2b0819080819082b, 0x2b08190808191919, 0x2b08190819080808, 0x2b081908192b0808, 0x2b0819082b082b19, 0x2b08191908080808, 0x2b08191919081908, 0x2b0819192b2b1919, 0x2b08192b08192b08, 0x2b08192b192b2b2b, 0x2b082b0808080808, 0x2b082b0808082b08, 0x2b082b08082b1919, 0x2b082b0819192b2b, 0x2b082b082b080808, 0x2b082b082b08082b, 0x2b082b082b2b2b08, 0x2b082b190808192b, 0x2b082b2b082b082b, 0x2b082b2b2b080808, 0x2b082b2b2b082b08, 0x2b082b2b2b19192b, 0x2b082b2b2b2b2b08, 0x2b19080808080819, 0x2b19080808081908, 0x2b19080808190808, 0x2b19080819080808, 0x2b1908081919192b, 0x2b1908082b081908, 0x2b19081908080808, 0x2b190819082b082b, 0x2b190819192b1908, 0x2b19082b1919192b, 0x2b19082b2b082b19, 0x2b19190808080808, 0x2b19190808081919, 0x2b19190819081908, 0x2b19190819190808, 0x2b19190819192b08, 0x2b191919082b2b19, 0x2b1919192b190808, 0x2b1919192b19082b, 0x2b19192b19080819, 0x2b192b0819190819, 0x2b192b082b2b192b, 0x2b192b1919082b19, 0x2b192b2b08191919, 0x2b192b2b192b0808, 0x2b2b080808080808, 0x2b2b08080808082b, 0x2b2b080808082b08, 0x2b2b080808082b2b, 0x2b2b0808082b0808, 0x2b2b0808082b2b2b, 0x2b2b08082b2b0808, 0x2b2b081919190819, 0x2b2b081919192b19, 0x2b2b08192b2b192b, 0x2b2b082b08080808, 0x2b2b082b0808082b, 0x2b2b082b08082b08, 0x2b2b082b082b2b2b, 0x2b2b082b2b080808, 0x2b2b082b2b2b0808, 0x2b2b190819080808, 0x2b2b19082b191919, 0x2b2b192b192b1919, 0x2b2b192b2b192b08, 0x2b2b2b0808082b2b, 0x2b2b2b08082b0808, 0x2b2b2b08082b082b, 0x2b2b2b08082b2b08, 0x2b2b2b082b2b0808, 0x2b2b2b082b2b2b08, 0x2b2b2b1908081908, 0x2b2b2b192b081908, 0x2b2b2b192b08192b, 0x2b2b2b2b082b2b08, 0x2b2b2b2b082b2b2b, 0x2b2b2b2b2b190819, 0x2b2b2b2b2b2b2b2b, GGML_TABLE_END() GGML_TABLE_BEGIN(uint64_t, iq2s_grid, 1024) 0x0808080808080808, 0x080808080808082b, 0x0808080808081919, 0x0808080808082b08, 0x0808080808082b2b, 0x0808080808190819, 0x0808080808191908, 0x080808080819192b, 0x0808080808192b19, 0x08080808082b0808, 0x08080808082b082b, 0x08080808082b1919, 0x08080808082b2b08, 0x0808080819080819, 0x0808080819081908, 0x080808081908192b, 0x0808080819082b19, 0x0808080819190808, 0x080808081919082b, 0x0808080819191919, 0x0808080819192b08, 0x08080808192b0819, 0x08080808192b1908, 0x08080808192b192b, 0x08080808192b2b19, 0x080808082b080808, 0x080808082b08082b, 0x080808082b081919, 0x080808082b082b08, 0x080808082b190819, 0x080808082b191908, 0x080808082b2b0808, 0x080808082b2b1919, 0x080808082b2b2b2b, 0x0808081908080819, 0x0808081908081908, 0x080808190808192b, 0x0808081908082b19, 0x0808081908190808, 0x080808190819082b, 0x0808081908191919, 0x0808081908192b08, 0x08080819082b0819, 0x08080819082b1908, 0x0808081919080808, 0x080808191908082b, 0x0808081919081919, 0x0808081919082b08, 0x0808081919190819, 0x0808081919191908, 0x080808191919192b, 0x0808081919192b19, 0x08080819192b0808, 0x08080819192b1919, 0x08080819192b2b08, 0x080808192b080819, 0x080808192b081908, 0x080808192b190808, 0x080808192b19082b, 0x080808192b191919, 0x080808192b2b0819, 0x080808192b2b1908, 0x0808082b08080808, 0x0808082b0808082b, 0x0808082b08081919, 0x0808082b08082b08, 0x0808082b08190819, 0x0808082b08191908, 0x0808082b082b0808, 0x0808082b082b2b2b, 0x0808082b19080819, 0x0808082b19081908, 0x0808082b1908192b, 0x0808082b19082b19, 0x0808082b19190808, 0x0808082b19191919, 0x0808082b2b080808, 0x0808082b2b081919, 0x0808082b2b082b2b, 0x0808082b2b191908, 0x0808082b2b2b082b, 0x0808190808080819, 0x0808190808081908, 0x080819080808192b, 0x0808190808082b19, 0x0808190808190808, 0x080819080819082b, 0x0808190808191919, 0x0808190808192b08, 0x08081908082b0819, 0x08081908082b1908, 0x08081908082b192b, 0x08081908082b2b19, 0x0808190819080808, 0x080819081908082b, 0x0808190819081919, 0x0808190819082b08, 0x0808190819082b2b, 0x0808190819190819, 0x0808190819191908, 0x080819081919192b, 0x0808190819192b19, 0x08081908192b0808, 0x08081908192b082b, 0x08081908192b1919, 0x080819082b080819, 0x080819082b081908, 0x080819082b08192b, 0x080819082b082b19, 0x080819082b190808, 0x080819082b191919, 0x080819082b192b08, 0x080819082b2b0819, 0x080819082b2b1908, 0x0808191908080808, 0x080819190808082b, 0x0808191908081919, 0x0808191908082b08, 0x0808191908082b2b, 0x0808191908190819, 0x0808191908191908, 0x080819190819192b, 0x0808191908192b19, 0x08081919082b0808, 0x08081919082b1919, 0x08081919082b2b08, 0x0808191919080819, 0x0808191919081908, 0x080819191908192b, 0x0808191919082b19, 0x0808191919190808, 0x080819191919082b, 0x0808191919191919, 0x0808191919192b08, 0x08081919192b0819, 0x08081919192b1908, 0x080819192b080808, 0x080819192b08082b, 0x080819192b081919, 0x080819192b082b08, 0x080819192b190819, 0x080819192b191908, 0x080819192b2b0808, 0x0808192b08080819, 0x0808192b08081908, 0x0808192b0808192b, 0x0808192b08082b19, 0x0808192b08190808, 0x0808192b08191919, 0x0808192b19080808, 0x0808192b19081919, 0x0808192b19082b08, 0x0808192b19190819, 0x0808192b19191908, 0x0808192b192b0808, 0x0808192b2b080819, 0x0808192b2b081908, 0x0808192b2b190808, 0x08082b0808080808, 0x08082b080808082b, 0x08082b0808081919, 0x08082b0808082b08, 0x08082b0808190819, 0x08082b0808191908, 0x08082b080819192b, 0x08082b0808192b19, 0x08082b08082b0808, 0x08082b08082b1919, 0x08082b08082b2b2b, 0x08082b0819080819, 0x08082b0819081908, 0x08082b081908192b, 0x08082b0819082b19, 0x08082b0819190808, 0x08082b081919082b, 0x08082b0819191919, 0x08082b0819192b08, 0x08082b08192b0819, 0x08082b08192b1908, 0x08082b082b080808, 0x08082b082b081919, 0x08082b082b191908, 0x08082b082b2b2b2b, 0x08082b1908080819, 0x08082b1908081908, 0x08082b1908190808, 0x08082b190819082b, 0x08082b1908191919, 0x08082b1908192b08, 0x08082b19082b0819, 0x08082b1919080808, 0x08082b1919081919, 0x08082b1919082b08, 0x08082b1919190819, 0x08082b1919191908, 0x08082b19192b0808, 0x08082b192b080819, 0x08082b192b190808, 0x08082b2b08080808, 0x08082b2b08190819, 0x08082b2b08191908, 0x08082b2b082b082b, 0x08082b2b082b2b08, 0x08082b2b082b2b2b, 0x08082b2b19190808, 0x08082b2b2b192b19, 0x0819080808080819, 0x0819080808081908, 0x081908080808192b, 0x0819080808082b19, 0x0819080808190808, 0x081908080819082b, 0x0819080808191919, 0x0819080808192b08, 0x08190808082b0819, 0x08190808082b1908, 0x08190808082b192b, 0x0819080819080808, 0x081908081908082b, 0x0819080819081919, 0x0819080819082b08, 0x0819080819190819, 0x0819080819191908, 0x081908081919192b, 0x0819080819192b19, 0x08190808192b0808, 0x08190808192b082b, 0x08190808192b1919, 0x08190808192b2b08, 0x081908082b080819, 0x081908082b081908, 0x081908082b08192b, 0x081908082b190808, 0x081908082b191919, 0x081908082b192b08, 0x081908082b2b0819, 0x081908082b2b1908, 0x0819081908080808, 0x081908190808082b, 0x0819081908081919, 0x0819081908082b08, 0x0819081908082b2b, 0x0819081908190819, 0x0819081908191908, 0x081908190819192b, 0x0819081908192b19, 0x08190819082b0808, 0x08190819082b082b, 0x08190819082b1919, 0x08190819082b2b08, 0x0819081919080819, 0x0819081919081908, 0x081908191908192b, 0x0819081919082b19, 0x0819081919190808, 0x081908191919082b, 0x0819081919191919, 0x0819081919192b08, 0x08190819192b0819, 0x08190819192b1908, 0x081908192b080808, 0x081908192b08082b, 0x081908192b081919, 0x081908192b082b08, 0x081908192b190819, 0x081908192b191908, 0x0819082b08080819, 0x0819082b08081908, 0x0819082b08082b19, 0x0819082b08190808, 0x0819082b08191919, 0x0819082b082b0819, 0x0819082b082b1908, 0x0819082b19080808, 0x0819082b19081919, 0x0819082b19190819, 0x0819082b19191908, 0x0819082b2b080819, 0x0819082b2b081908, 0x0819082b2b190808, 0x0819190808080808, 0x081919080808082b, 0x0819190808081919, 0x0819190808082b08, 0x0819190808190819, 0x0819190808191908, 0x081919080819192b, 0x0819190808192b19, 0x08191908082b0808, 0x08191908082b1919, 0x08191908082b2b08, 0x0819190819080819, 0x0819190819081908, 0x081919081908192b, 0x0819190819082b19, 0x0819190819190808, 0x081919081919082b, 0x0819190819191919, 0x0819190819192b08, 0x08191908192b0819, 0x08191908192b1908, 0x081919082b080808, 0x081919082b08082b, 0x081919082b081919, 0x081919082b082b08, 0x081919082b190819, 0x081919082b191908, 0x081919082b2b0808, 0x0819191908080819, 0x0819191908081908, 0x081919190808192b, 0x0819191908082b19, 0x0819191908190808, 0x081919190819082b, 0x0819191908191919, 0x0819191908192b08, 0x08191919082b0819, 0x08191919082b1908, 0x0819191919080808, 0x081919191908082b, 0x0819191919081919, 0x0819191919082b08, 0x0819191919190819, 0x0819191919191908, 0x08191919192b0808, 0x081919192b080819, 0x081919192b081908, 0x081919192b190808, 0x0819192b08080808, 0x0819192b08081919, 0x0819192b08082b08, 0x0819192b08190819, 0x0819192b08191908, 0x0819192b082b0808, 0x0819192b19080819, 0x0819192b19081908, 0x0819192b19190808, 0x0819192b2b080808, 0x0819192b2b2b2b2b, 0x08192b0808080819, 0x08192b0808081908, 0x08192b080808192b, 0x08192b0808082b19, 0x08192b0808190808, 0x08192b0808191919, 0x08192b0808192b08, 0x08192b08082b0819, 0x08192b0819080808, 0x08192b081908082b, 0x08192b0819081919, 0x08192b0819082b08, 0x08192b0819190819, 0x08192b0819191908, 0x08192b08192b0808, 0x08192b082b080819, 0x08192b082b081908, 0x08192b1908080808, 0x08192b190808082b, 0x08192b1908081919, 0x08192b1908082b08, 0x08192b1908190819, 0x08192b1908191908, 0x08192b19082b0808, 0x08192b1919080819, 0x08192b1919081908, 0x08192b1919190808, 0x08192b19192b2b19, 0x08192b192b2b082b, 0x08192b2b08081908, 0x08192b2b08190808, 0x08192b2b19080808, 0x08192b2b1919192b, 0x082b080808080808, 0x082b08080808082b, 0x082b080808081919, 0x082b080808082b08, 0x082b080808190819, 0x082b080808191908, 0x082b08080819192b, 0x082b080808192b19, 0x082b0808082b0808, 0x082b0808082b1919, 0x082b0808082b2b2b, 0x082b080819080819, 0x082b080819081908, 0x082b080819190808, 0x082b08081919082b, 0x082b080819191919, 0x082b0808192b1908, 0x082b08082b080808, 0x082b08082b082b2b, 0x082b08082b191908, 0x082b08082b2b2b2b, 0x082b081908080819, 0x082b081908081908, 0x082b081908190808, 0x082b08190819082b, 0x082b081908191919, 0x082b0819082b0819, 0x082b081919080808, 0x082b08191908082b, 0x082b081919081919, 0x082b081919190819, 0x082b081919191908, 0x082b0819192b0808, 0x082b08192b080819, 0x082b08192b081908, 0x082b08192b190808, 0x082b082b08080808, 0x082b082b08082b2b, 0x082b082b082b082b, 0x082b082b082b2b08, 0x082b082b082b2b2b, 0x082b082b19081908, 0x082b082b19190808, 0x082b082b2b082b08, 0x082b082b2b082b2b, 0x082b082b2b2b2b08, 0x082b190808080819, 0x082b190808081908, 0x082b19080808192b, 0x082b190808082b19, 0x082b190808190808, 0x082b190808191919, 0x082b190808192b08, 0x082b1908082b0819, 0x082b1908082b1908, 0x082b190819080808, 0x082b19081908082b, 0x082b190819081919, 0x082b190819082b08, 0x082b190819190819, 0x082b190819191908, 0x082b1908192b0808, 0x082b19082b080819, 0x082b19082b081908, 0x082b19082b190808, 0x082b191908080808, 0x082b191908081919, 0x082b191908082b08, 0x082b191908190819, 0x082b191908191908, 0x082b1919082b0808, 0x082b191919080819, 0x082b191919081908, 0x082b191919190808, 0x082b1919192b192b, 0x082b19192b080808, 0x082b192b08080819, 0x082b192b08081908, 0x082b192b08190808, 0x082b192b19080808, 0x082b192b19192b19, 0x082b2b0808080808, 0x082b2b0808081919, 0x082b2b0808190819, 0x082b2b0808191908, 0x082b2b0819080819, 0x082b2b0819081908, 0x082b2b0819190808, 0x082b2b082b082b2b, 0x082b2b082b2b2b2b, 0x082b2b1908080819, 0x082b2b1908081908, 0x082b2b1908190808, 0x082b2b192b191919, 0x082b2b2b08082b2b, 0x082b2b2b082b082b, 0x082b2b2b192b1908, 0x082b2b2b2b082b08, 0x082b2b2b2b082b2b, 0x1908080808080819, 0x1908080808081908, 0x190808080808192b, 0x1908080808082b19, 0x1908080808190808, 0x190808080819082b, 0x1908080808191919, 0x1908080808192b08, 0x1908080808192b2b, 0x19080808082b0819, 0x19080808082b1908, 0x19080808082b192b, 0x1908080819080808, 0x190808081908082b, 0x1908080819081919, 0x1908080819082b08, 0x1908080819082b2b, 0x1908080819190819, 0x1908080819191908, 0x190808081919192b, 0x1908080819192b19, 0x19080808192b0808, 0x19080808192b082b, 0x19080808192b1919, 0x190808082b080819, 0x190808082b081908, 0x190808082b190808, 0x190808082b191919, 0x190808082b192b08, 0x190808082b2b0819, 0x190808082b2b1908, 0x1908081908080808, 0x190808190808082b, 0x1908081908081919, 0x1908081908082b08, 0x1908081908190819, 0x1908081908191908, 0x190808190819192b, 0x1908081908192b19, 0x19080819082b0808, 0x19080819082b082b, 0x19080819082b1919, 0x1908081919080819, 0x1908081919081908, 0x190808191908192b, 0x1908081919082b19, 0x1908081919190808, 0x190808191919082b, 0x1908081919191919, 0x1908081919192b08, 0x19080819192b0819, 0x19080819192b1908, 0x190808192b080808, 0x190808192b08082b, 0x190808192b081919, 0x190808192b082b08, 0x190808192b190819, 0x190808192b191908, 0x190808192b2b0808, 0x1908082b08080819, 0x1908082b08081908, 0x1908082b08190808, 0x1908082b0819082b, 0x1908082b08191919, 0x1908082b08192b08, 0x1908082b082b1908, 0x1908082b19080808, 0x1908082b19081919, 0x1908082b19082b08, 0x1908082b19190819, 0x1908082b19191908, 0x1908082b192b0808, 0x1908082b2b080819, 0x1908082b2b081908, 0x1908190808080808, 0x190819080808082b, 0x1908190808081919, 0x1908190808082b08, 0x1908190808082b2b, 0x1908190808190819, 0x1908190808191908, 0x190819080819192b, 0x1908190808192b19, 0x19081908082b0808, 0x19081908082b082b, 0x19081908082b1919, 0x19081908082b2b08, 0x1908190819080819, 0x1908190819081908, 0x190819081908192b, 0x1908190819082b19, 0x1908190819190808, 0x190819081919082b, 0x1908190819191919, 0x1908190819192b08, 0x19081908192b0819, 0x19081908192b1908, 0x190819082b080808, 0x190819082b08082b, 0x190819082b081919, 0x190819082b082b08, 0x190819082b190819, 0x190819082b191908, 0x190819082b2b0808, 0x1908191908080819, 0x1908191908081908, 0x190819190808192b, 0x1908191908082b19, 0x1908191908190808, 0x190819190819082b, 0x1908191908191919, 0x1908191908192b08, 0x19081919082b0819, 0x19081919082b1908, 0x1908191919080808, 0x190819191908082b, 0x1908191919081919, 0x1908191919082b08, 0x1908191919190819, 0x1908191919191908, 0x19081919192b0808, 0x19081919192b2b2b, 0x190819192b080819, 0x190819192b081908, 0x190819192b190808, 0x1908192b08080808, 0x1908192b0808082b, 0x1908192b08081919, 0x1908192b08082b08, 0x1908192b08190819, 0x1908192b08191908, 0x1908192b082b0808, 0x1908192b19080819, 0x1908192b19081908, 0x1908192b19190808, 0x1908192b2b080808, 0x1908192b2b2b1919, 0x19082b0808080819, 0x19082b0808081908, 0x19082b0808082b19, 0x19082b0808190808, 0x19082b080819082b, 0x19082b0808191919, 0x19082b0808192b08, 0x19082b08082b0819, 0x19082b08082b1908, 0x19082b0819080808, 0x19082b081908082b, 0x19082b0819081919, 0x19082b0819082b08, 0x19082b0819190819, 0x19082b0819191908, 0x19082b08192b0808, 0x19082b082b081908, 0x19082b082b190808, 0x19082b1908080808, 0x19082b190808082b, 0x19082b1908081919, 0x19082b1908082b08, 0x19082b1908190819, 0x19082b1908191908, 0x19082b19082b0808, 0x19082b1919080819, 0x19082b1919081908, 0x19082b1919190808, 0x19082b192b080808, 0x19082b192b19192b, 0x19082b2b08080819, 0x19082b2b08081908, 0x19082b2b08190808, 0x19082b2b19080808, 0x1919080808080808, 0x191908080808082b, 0x1919080808081919, 0x1919080808082b08, 0x1919080808190819, 0x1919080808191908, 0x191908080819192b, 0x1919080808192b19, 0x19190808082b0808, 0x19190808082b082b, 0x19190808082b1919, 0x19190808082b2b08, 0x1919080819080819, 0x1919080819081908, 0x191908081908192b, 0x1919080819082b19, 0x1919080819190808, 0x191908081919082b, 0x1919080819191919, 0x1919080819192b08, 0x19190808192b0819, 0x19190808192b1908, 0x191908082b080808, 0x191908082b08082b, 0x191908082b081919, 0x191908082b082b08, 0x191908082b190819, 0x191908082b191908, 0x1919081908080819, 0x1919081908081908, 0x191908190808192b, 0x1919081908082b19, 0x1919081908190808, 0x191908190819082b, 0x1919081908191919, 0x1919081908192b08, 0x19190819082b0819, 0x19190819082b1908, 0x1919081919080808, 0x191908191908082b, 0x1919081919081919, 0x1919081919082b08, 0x1919081919190819, 0x1919081919191908, 0x19190819192b0808, 0x191908192b080819, 0x191908192b081908, 0x191908192b190808, 0x1919082b08080808, 0x1919082b08081919, 0x1919082b08082b08, 0x1919082b08190819, 0x1919082b08191908, 0x1919082b082b0808, 0x1919082b19080819, 0x1919082b19081908, 0x1919082b19190808, 0x1919082b192b2b19, 0x1919082b2b080808, 0x1919190808080819, 0x1919190808081908, 0x191919080808192b, 0x1919190808082b19, 0x1919190808190808, 0x191919080819082b, 0x1919190808191919, 0x1919190808192b08, 0x19191908082b0819, 0x19191908082b1908, 0x1919190819080808, 0x191919081908082b, 0x1919190819081919, 0x1919190819082b08, 0x1919190819190819, 0x1919190819191908, 0x19191908192b0808, 0x191919082b080819, 0x191919082b081908, 0x191919082b190808, 0x1919191908080808, 0x191919190808082b, 0x1919191908081919, 0x1919191908082b08, 0x1919191908190819, 0x1919191908191908, 0x19191919082b0808, 0x1919191919080819, 0x1919191919081908, 0x1919191919190808, 0x191919192b080808, 0x1919192b08080819, 0x1919192b08081908, 0x1919192b08190808, 0x1919192b082b192b, 0x1919192b19080808, 0x19192b0808080808, 0x19192b080808082b, 0x19192b0808081919, 0x19192b0808082b08, 0x19192b0808190819, 0x19192b0808191908, 0x19192b08082b0808, 0x19192b0819080819, 0x19192b0819081908, 0x19192b0819190808, 0x19192b0819192b2b, 0x19192b082b080808, 0x19192b1908080819, 0x19192b1908081908, 0x19192b1908190808, 0x19192b1919080808, 0x19192b2b08080808, 0x19192b2b08192b19, 0x19192b2b2b081919, 0x19192b2b2b2b2b08, 0x192b080808080819, 0x192b080808081908, 0x192b08080808192b, 0x192b080808190808, 0x192b08080819082b, 0x192b080808191919, 0x192b080808192b08, 0x192b0808082b0819, 0x192b0808082b1908, 0x192b080819080808, 0x192b080819081919, 0x192b080819082b08, 0x192b080819190819, 0x192b080819191908, 0x192b0808192b0808, 0x192b08082b081908, 0x192b08082b190808, 0x192b081908080808, 0x192b08190808082b, 0x192b081908081919, 0x192b081908082b08, 0x192b081908190819, 0x192b081908191908, 0x192b0819082b0808, 0x192b081919080819, 0x192b081919081908, 0x192b081919190808, 0x192b08192b080808, 0x192b08192b192b19, 0x192b082b08081908, 0x192b082b08190808, 0x192b082b19080808, 0x192b082b1919192b, 0x192b082b2b2b0819, 0x192b190808080808, 0x192b190808081919, 0x192b190808082b08, 0x192b190808190819, 0x192b190808191908, 0x192b1908082b0808, 0x192b190819080819, 0x192b190819081908, 0x192b190819190808, 0x192b19082b080808, 0x192b191908080819, 0x192b191908081908, 0x192b191908190808, 0x192b191919080808, 0x192b191919082b2b, 0x192b1919192b2b08, 0x192b19192b19082b, 0x192b192b08080808, 0x192b192b2b191908, 0x192b2b0808080819, 0x192b2b0808081908, 0x192b2b0808190808, 0x192b2b08192b1919, 0x192b2b082b192b08, 0x192b2b1908080808, 0x192b2b19082b2b2b, 0x192b2b2b1908082b, 0x192b2b2b2b2b0819, 0x2b08080808080808, 0x2b0808080808082b, 0x2b08080808081919, 0x2b08080808082b08, 0x2b08080808190819, 0x2b08080808191908, 0x2b08080808192b19, 0x2b080808082b0808, 0x2b080808082b1919, 0x2b08080819080819, 0x2b08080819081908, 0x2b08080819190808, 0x2b0808081919082b, 0x2b08080819191919, 0x2b08080819192b08, 0x2b080808192b0819, 0x2b0808082b080808, 0x2b0808082b081919, 0x2b0808082b190819, 0x2b0808082b191908, 0x2b08081908080819, 0x2b08081908081908, 0x2b08081908082b19, 0x2b08081908190808, 0x2b0808190819082b, 0x2b08081908191919, 0x2b08081908192b08, 0x2b080819082b0819, 0x2b080819082b1908, 0x2b08081919080808, 0x2b0808191908082b, 0x2b08081919081919, 0x2b08081919082b08, 0x2b08081919190819, 0x2b08081919191908, 0x2b0808192b080819, 0x2b0808192b081908, 0x2b0808192b190808, 0x2b0808192b2b2b19, 0x2b08082b08080808, 0x2b08082b08081919, 0x2b08082b08082b2b, 0x2b08082b08190819, 0x2b08082b08191908, 0x2b08082b19080819, 0x2b08082b19081908, 0x2b08082b19190808, 0x2b08190808080819, 0x2b08190808081908, 0x2b0819080808192b, 0x2b08190808082b19, 0x2b08190808190808, 0x2b0819080819082b, 0x2b08190808191919, 0x2b08190808192b08, 0x2b081908082b0819, 0x2b08190819080808, 0x2b0819081908082b, 0x2b08190819081919, 0x2b08190819082b08, 0x2b08190819190819, 0x2b08190819191908, 0x2b081908192b0808, 0x2b0819082b080819, 0x2b0819082b081908, 0x2b0819082b190808, 0x2b08191908080808, 0x2b0819190808082b, 0x2b08191908081919, 0x2b08191908082b08, 0x2b08191908190819, 0x2b08191908191908, 0x2b081919082b0808, 0x2b08191919080819, 0x2b08191919081908, 0x2b08191919190808, 0x2b0819192b080808, 0x2b0819192b082b2b, 0x2b08192b08080819, 0x2b08192b08081908, 0x2b08192b08190808, 0x2b08192b082b2b19, 0x2b08192b19080808, 0x2b082b0808080808, 0x2b082b0808081919, 0x2b082b0808190819, 0x2b082b0808191908, 0x2b082b0819080819, 0x2b082b0819081908, 0x2b082b0819190808, 0x2b082b082b2b082b, 0x2b082b1908080819, 0x2b082b1908081908, 0x2b082b1919080808, 0x2b082b19192b1919, 0x2b082b2b082b082b, 0x2b082b2b19192b08, 0x2b082b2b19192b2b, 0x2b082b2b2b08082b, 0x2b082b2b2b2b082b, 0x2b19080808080819, 0x2b19080808081908, 0x2b19080808082b19, 0x2b19080808190808, 0x2b1908080819082b, 0x2b19080808191919, 0x2b19080808192b08, 0x2b190808082b1908, 0x2b19080819080808, 0x2b1908081908082b, 0x2b19080819081919, 0x2b19080819082b08, 0x2b19080819190819, 0x2b19080819191908, 0x2b190808192b0808, 0x2b1908082b080819, 0x2b1908082b081908, 0x2b1908082b190808, 0x2b19081908080808, 0x2b19081908081919, 0x2b19081908190819, 0x2b19081908191908, 0x2b19081919080819, 0x2b19081919081908, 0x2b19081919190808, 0x2b19081919192b2b, 0x2b19082b08080819, 0x2b19082b08081908, 0x2b19082b08190808, 0x2b19082b19080808, 0x2b19082b2b2b192b, 0x2b19190808080808, 0x2b1919080808082b, 0x2b19190808081919, 0x2b19190808082b08, 0x2b19190808190819, 0x2b19190808191908, 0x2b191908082b0808, 0x2b19190819080819, 0x2b19190819081908, 0x2b19190819190808, 0x2b1919082b080808, 0x2b1919082b19192b, 0x2b19191908080819, 0x2b19191908081908, 0x2b19191908190808, 0x2b19191919080808, 0x2b1919192b192b08, 0x2b1919192b2b0819, 0x2b19192b08080808, 0x2b19192b1908192b, 0x2b19192b192b1908, 0x2b192b0808080819, 0x2b192b0808081908, 0x2b192b0808190808, 0x2b192b08082b192b, 0x2b192b0819080808, 0x2b192b082b2b2b19, 0x2b192b1908080808, 0x2b192b1919082b19, 0x2b192b191919082b, 0x2b192b2b2b190808, 0x2b2b080808080808, 0x2b2b080808081919, 0x2b2b080808082b2b, 0x2b2b080808191908, 0x2b2b0808082b082b, 0x2b2b0808082b2b2b, 0x2b2b080819080819, 0x2b2b080819081908, 0x2b2b080819190808, 0x2b2b08082b2b082b, 0x2b2b08082b2b2b2b, 0x2b2b081919080808, 0x2b2b0819192b1919, 0x2b2b082b0808082b, 0x2b2b082b08082b2b, 0x2b2b082b082b082b, 0x2b2b082b082b2b08, 0x2b2b082b082b2b2b, 0x2b2b082b2b08082b, 0x2b2b082b2b082b08, 0x2b2b082b2b082b2b, 0x2b2b082b2b2b2b08, 0x2b2b190808080819, 0x2b2b190808081908, 0x2b2b190808190808, 0x2b2b190819080808, 0x2b2b19082b082b19, 0x2b2b19082b2b1908, 0x2b2b191908080808, 0x2b2b191908192b19, 0x2b2b192b19190819, 0x2b2b2b0808082b2b, 0x2b2b2b08082b2b08, 0x2b2b2b082b2b082b, 0x2b2b2b1919191908, 0x2b2b2b192b08192b, 0x2b2b2b2b08082b08, 0x2b2b2b2b08082b2b, 0x2b2b2b2b082b0808, 0x2b2b2b2b082b082b, 0x2b2b2b2b082b2b08, 0x2b2b2b2b2b082b08, 0x2b2b2b2b2b2b2b2b, GGML_TABLE_END() GGML_TABLE_BEGIN(uint32_t, iq3xxs_grid, 256) 0x04040404, 0x04040414, 0x04040424, 0x04040c0c, 0x04040c1c, 0x04040c3e, 0x04041404, 0x04041414, 0x04041c0c, 0x04042414, 0x04043e1c, 0x04043e2c, 0x040c040c, 0x040c041c, 0x040c0c04, 0x040c0c14, 0x040c140c, 0x040c142c, 0x040c1c04, 0x040c1c14, 0x040c240c, 0x040c2c24, 0x040c3e04, 0x04140404, 0x04140414, 0x04140424, 0x04140c0c, 0x04141404, 0x04141414, 0x04141c0c, 0x04141c1c, 0x04141c3e, 0x04142c0c, 0x04142c3e, 0x04143e2c, 0x041c040c, 0x041c043e, 0x041c0c04, 0x041c0c14, 0x041c142c, 0x041c3e04, 0x04240c1c, 0x04241c3e, 0x04242424, 0x04242c3e, 0x04243e1c, 0x04243e2c, 0x042c040c, 0x042c043e, 0x042c1c14, 0x042c2c14, 0x04341c2c, 0x04343424, 0x043e0c04, 0x043e0c24, 0x043e0c34, 0x043e241c, 0x043e340c, 0x0c04040c, 0x0c04041c, 0x0c040c04, 0x0c040c14, 0x0c04140c, 0x0c04141c, 0x0c041c04, 0x0c041c14, 0x0c041c24, 0x0c04243e, 0x0c042c04, 0x0c0c0404, 0x0c0c0414, 0x0c0c0c0c, 0x0c0c1404, 0x0c0c1414, 0x0c14040c, 0x0c14041c, 0x0c140c04, 0x0c140c14, 0x0c14140c, 0x0c141c04, 0x0c143e14, 0x0c1c0404, 0x0c1c0414, 0x0c1c1404, 0x0c1c1c0c, 0x0c1c2434, 0x0c1c3434, 0x0c24040c, 0x0c24042c, 0x0c242c04, 0x0c2c1404, 0x0c2c1424, 0x0c2c2434, 0x0c2c3e0c, 0x0c34042c, 0x0c3e1414, 0x0c3e2404, 0x14040404, 0x14040414, 0x14040c0c, 0x14040c1c, 0x14041404, 0x14041414, 0x14041434, 0x14041c0c, 0x14042414, 0x140c040c, 0x140c041c, 0x140c042c, 0x140c0c04, 0x140c0c14, 0x140c140c, 0x140c1c04, 0x140c341c, 0x140c343e, 0x140c3e04, 0x14140404, 0x14140414, 0x14140c0c, 0x14140c3e, 0x14141404, 0x14141414, 0x14141c3e, 0x14142404, 0x14142c2c, 0x141c040c, 0x141c0c04, 0x141c0c24, 0x141c3e04, 0x141c3e24, 0x14241c2c, 0x14242c1c, 0x142c041c, 0x142c143e, 0x142c240c, 0x142c3e24, 0x143e040c, 0x143e041c, 0x143e0c34, 0x143e242c, 0x1c04040c, 0x1c040c04, 0x1c040c14, 0x1c04140c, 0x1c04141c, 0x1c042c04, 0x1c04342c, 0x1c043e14, 0x1c0c0404, 0x1c0c0414, 0x1c0c1404, 0x1c0c1c0c, 0x1c0c2424, 0x1c0c2434, 0x1c14040c, 0x1c14041c, 0x1c140c04, 0x1c14142c, 0x1c142c14, 0x1c143e14, 0x1c1c0c0c, 0x1c1c1c1c, 0x1c241c04, 0x1c24243e, 0x1c243e14, 0x1c2c0404, 0x1c2c0434, 0x1c2c1414, 0x1c2c2c2c, 0x1c340c24, 0x1c341c34, 0x1c34341c, 0x1c3e1c1c, 0x1c3e3404, 0x24040424, 0x24040c3e, 0x24041c2c, 0x24041c3e, 0x24042c1c, 0x24042c3e, 0x240c3e24, 0x24141404, 0x24141c3e, 0x24142404, 0x24143404, 0x24143434, 0x241c043e, 0x241c242c, 0x24240424, 0x24242c0c, 0x24243424, 0x242c142c, 0x242c241c, 0x242c3e04, 0x243e042c, 0x243e0c04, 0x243e0c14, 0x243e1c04, 0x2c040c14, 0x2c04240c, 0x2c043e04, 0x2c0c0404, 0x2c0c0434, 0x2c0c1434, 0x2c0c2c2c, 0x2c140c24, 0x2c141c14, 0x2c143e14, 0x2c1c0414, 0x2c1c2c1c, 0x2c240c04, 0x2c24141c, 0x2c24143e, 0x2c243e14, 0x2c2c0414, 0x2c2c1c0c, 0x2c342c04, 0x2c3e1424, 0x2c3e2414, 0x34041424, 0x34042424, 0x34042434, 0x34043424, 0x340c140c, 0x340c340c, 0x34140c3e, 0x34143424, 0x341c1c04, 0x341c1c34, 0x34242424, 0x342c042c, 0x342c2c14, 0x34341c1c, 0x343e041c, 0x343e140c, 0x3e04041c, 0x3e04042c, 0x3e04043e, 0x3e040c04, 0x3e041c14, 0x3e042c14, 0x3e0c1434, 0x3e0c2404, 0x3e140c14, 0x3e14242c, 0x3e142c14, 0x3e1c0404, 0x3e1c0c2c, 0x3e1c1c1c, 0x3e1c3404, 0x3e24140c, 0x3e24240c, 0x3e2c0404, 0x3e2c0414, 0x3e2c1424, 0x3e341c04, GGML_TABLE_END() GGML_TABLE_BEGIN(uint32_t, iq3s_grid, 512) 0x01010101, 0x01010103, 0x01010105, 0x0101010b, 0x0101010f, 0x01010301, 0x01010303, 0x01010305, 0x01010309, 0x0101030d, 0x01010501, 0x01010503, 0x0101050b, 0x01010707, 0x01010901, 0x01010905, 0x0101090b, 0x0101090f, 0x01010b03, 0x01010b07, 0x01010d01, 0x01010d05, 0x01010f03, 0x01010f09, 0x01010f0f, 0x01030101, 0x01030103, 0x01030105, 0x01030109, 0x01030301, 0x01030303, 0x0103030b, 0x01030501, 0x01030507, 0x0103050f, 0x01030703, 0x0103070b, 0x01030909, 0x01030d03, 0x01030d0b, 0x01030f05, 0x01050101, 0x01050103, 0x0105010b, 0x0105010f, 0x01050301, 0x01050307, 0x0105030d, 0x01050503, 0x0105050b, 0x01050701, 0x01050709, 0x01050905, 0x0105090b, 0x0105090f, 0x01050b03, 0x01050b07, 0x01050f01, 0x01050f07, 0x01070107, 0x01070303, 0x0107030b, 0x01070501, 0x01070505, 0x01070703, 0x01070707, 0x0107070d, 0x01070909, 0x01070b01, 0x01070b05, 0x01070d0f, 0x01070f03, 0x01070f0b, 0x01090101, 0x01090307, 0x0109030f, 0x01090503, 0x01090509, 0x01090705, 0x01090901, 0x01090907, 0x01090b03, 0x01090f01, 0x010b0105, 0x010b0109, 0x010b0501, 0x010b0505, 0x010b050d, 0x010b0707, 0x010b0903, 0x010b090b, 0x010b090f, 0x010b0d0d, 0x010b0f07, 0x010d010d, 0x010d0303, 0x010d0307, 0x010d0703, 0x010d0b05, 0x010d0f03, 0x010f0101, 0x010f0105, 0x010f0109, 0x010f0501, 0x010f0505, 0x010f050d, 0x010f0707, 0x010f0b01, 0x010f0b09, 0x03010101, 0x03010103, 0x03010105, 0x03010109, 0x03010301, 0x03010303, 0x03010307, 0x0301030b, 0x0301030f, 0x03010501, 0x03010505, 0x03010703, 0x03010709, 0x0301070d, 0x03010b09, 0x03010b0d, 0x03010d03, 0x03010f05, 0x03030101, 0x03030103, 0x03030107, 0x0303010d, 0x03030301, 0x03030309, 0x03030503, 0x03030701, 0x03030707, 0x03030903, 0x03030b01, 0x03030b05, 0x03030f01, 0x03030f0d, 0x03050101, 0x03050305, 0x0305030b, 0x0305030f, 0x03050501, 0x03050509, 0x03050705, 0x03050901, 0x03050907, 0x03050b0b, 0x03050d01, 0x03050f05, 0x03070103, 0x03070109, 0x0307010f, 0x03070301, 0x03070307, 0x03070503, 0x0307050f, 0x03070701, 0x03070709, 0x03070903, 0x03070d05, 0x03070f01, 0x03090107, 0x0309010b, 0x03090305, 0x03090309, 0x03090703, 0x03090707, 0x03090905, 0x0309090d, 0x03090b01, 0x03090b09, 0x030b0103, 0x030b0301, 0x030b0307, 0x030b0503, 0x030b0701, 0x030b0705, 0x030b0b03, 0x030d0501, 0x030d0509, 0x030d050f, 0x030d0909, 0x030d090d, 0x030f0103, 0x030f0107, 0x030f0301, 0x030f0305, 0x030f0503, 0x030f070b, 0x030f0903, 0x030f0d05, 0x030f0f01, 0x05010101, 0x05010103, 0x05010107, 0x0501010b, 0x0501010f, 0x05010301, 0x05010305, 0x05010309, 0x0501030d, 0x05010503, 0x05010507, 0x0501050f, 0x05010701, 0x05010705, 0x05010903, 0x05010907, 0x0501090b, 0x05010b01, 0x05010b05, 0x05010d0f, 0x05010f01, 0x05010f07, 0x05010f0b, 0x05030101, 0x05030105, 0x05030301, 0x05030307, 0x0503030f, 0x05030505, 0x0503050b, 0x05030703, 0x05030709, 0x05030905, 0x05030b03, 0x05050103, 0x05050109, 0x0505010f, 0x05050503, 0x05050507, 0x05050701, 0x0505070f, 0x05050903, 0x05050b07, 0x05050b0f, 0x05050f03, 0x05050f09, 0x05070101, 0x05070105, 0x0507010b, 0x05070303, 0x05070505, 0x05070509, 0x05070703, 0x05070707, 0x05070905, 0x05070b01, 0x05070d0d, 0x05090103, 0x0509010f, 0x05090501, 0x05090507, 0x05090705, 0x0509070b, 0x05090903, 0x05090f05, 0x05090f0b, 0x050b0109, 0x050b0303, 0x050b0505, 0x050b070f, 0x050b0901, 0x050b0b07, 0x050b0f01, 0x050d0101, 0x050d0105, 0x050d010f, 0x050d0503, 0x050d0b0b, 0x050d0d03, 0x050f010b, 0x050f0303, 0x050f050d, 0x050f0701, 0x050f0907, 0x050f0b01, 0x07010105, 0x07010303, 0x07010307, 0x0701030b, 0x0701030f, 0x07010505, 0x07010703, 0x07010707, 0x0701070b, 0x07010905, 0x07010909, 0x0701090f, 0x07010b03, 0x07010d07, 0x07010f03, 0x07030103, 0x07030107, 0x0703010b, 0x07030309, 0x07030503, 0x07030507, 0x07030901, 0x07030d01, 0x07030f05, 0x07030f0d, 0x07050101, 0x07050305, 0x07050501, 0x07050705, 0x07050709, 0x07050b01, 0x07070103, 0x07070301, 0x07070309, 0x07070503, 0x07070507, 0x0707050f, 0x07070701, 0x07070903, 0x07070907, 0x0707090f, 0x07070b0b, 0x07070f07, 0x07090107, 0x07090303, 0x0709030d, 0x07090505, 0x07090703, 0x07090b05, 0x07090d01, 0x07090d09, 0x070b0103, 0x070b0301, 0x070b0305, 0x070b050b, 0x070b0705, 0x070b0909, 0x070b0b0d, 0x070b0f07, 0x070d030d, 0x070d0903, 0x070f0103, 0x070f0107, 0x070f0501, 0x070f0505, 0x070f070b, 0x09010101, 0x09010109, 0x09010305, 0x09010501, 0x09010509, 0x0901050f, 0x09010705, 0x09010903, 0x09010b01, 0x09010f01, 0x09030105, 0x0903010f, 0x09030303, 0x09030307, 0x09030505, 0x09030701, 0x0903070b, 0x09030907, 0x09030b03, 0x09030b0b, 0x09050103, 0x09050107, 0x09050301, 0x0905030b, 0x09050503, 0x09050707, 0x09050901, 0x09050b0f, 0x09050d05, 0x09050f01, 0x09070109, 0x09070303, 0x09070307, 0x09070501, 0x09070505, 0x09070703, 0x0907070b, 0x09090101, 0x09090105, 0x09090509, 0x0909070f, 0x09090901, 0x09090f03, 0x090b010b, 0x090b010f, 0x090b0503, 0x090b0d05, 0x090d0307, 0x090d0709, 0x090d0d01, 0x090f0301, 0x090f030b, 0x090f0701, 0x090f0907, 0x090f0b03, 0x0b010105, 0x0b010301, 0x0b010309, 0x0b010505, 0x0b010901, 0x0b010909, 0x0b01090f, 0x0b010b05, 0x0b010d0d, 0x0b010f09, 0x0b030103, 0x0b030107, 0x0b03010b, 0x0b030305, 0x0b030503, 0x0b030705, 0x0b030f05, 0x0b050101, 0x0b050303, 0x0b050507, 0x0b050701, 0x0b05070d, 0x0b050b07, 0x0b070105, 0x0b07010f, 0x0b070301, 0x0b07050f, 0x0b070909, 0x0b070b03, 0x0b070d0b, 0x0b070f07, 0x0b090103, 0x0b090109, 0x0b090501, 0x0b090705, 0x0b09090d, 0x0b0b0305, 0x0b0b050d, 0x0b0b0b03, 0x0b0b0b07, 0x0b0d0905, 0x0b0f0105, 0x0b0f0109, 0x0b0f0505, 0x0d010303, 0x0d010307, 0x0d01030b, 0x0d010703, 0x0d010707, 0x0d010d01, 0x0d030101, 0x0d030501, 0x0d03050f, 0x0d030d09, 0x0d050305, 0x0d050709, 0x0d050905, 0x0d050b0b, 0x0d050d05, 0x0d050f01, 0x0d070101, 0x0d070309, 0x0d070503, 0x0d070901, 0x0d09050b, 0x0d090907, 0x0d090d05, 0x0d0b0101, 0x0d0b0107, 0x0d0b0709, 0x0d0b0d01, 0x0d0d010b, 0x0d0d0901, 0x0d0f0303, 0x0d0f0307, 0x0f010101, 0x0f010109, 0x0f01010f, 0x0f010501, 0x0f010505, 0x0f01070d, 0x0f010901, 0x0f010b09, 0x0f010d05, 0x0f030105, 0x0f030303, 0x0f030509, 0x0f030907, 0x0f03090b, 0x0f050103, 0x0f050109, 0x0f050301, 0x0f05030d, 0x0f050503, 0x0f050701, 0x0f050b03, 0x0f070105, 0x0f070705, 0x0f07070b, 0x0f070b07, 0x0f090103, 0x0f09010b, 0x0f090307, 0x0f090501, 0x0f090b01, 0x0f0b0505, 0x0f0b0905, 0x0f0d0105, 0x0f0d0703, 0x0f0f0101, GGML_TABLE_END() #define NGRID_IQ1S 2048 #define IQ1S_DELTA 0.125f #define IQ1M_DELTA 0.125f GGML_TABLE_BEGIN(uint32_t, iq1s_grid_gpu, NGRID_IQ1S) 0x00000000, 0x00000002, 0x00000101, 0x00000200, 0x00000202, 0x00010001, 0x00010101, 0x00020000, 0x00020002, 0x00020200, 0x00020202, 0x01000101, 0x01010001, 0x01010100, 0x01010102, 0x01020101, 0x02000000, 0x02000002, 0x02000200, 0x02000202, 0x02010101, 0x02020000, 0x02020002, 0x02020200, 0x02020202, 0x00000110, 0x00000111, 0x00010011, 0x00010110, 0x00010112, 0x00010211, 0x00010212, 0x00020111, 0x01000011, 0x01000112, 0x01000211, 0x01010012, 0x01010111, 0x01010212, 0x01020011, 0x01020110, 0x01020112, 0x01020210, 0x02000111, 0x02010011, 0x02010110, 0x02010112, 0x02020111, 0x00000020, 0x00000022, 0x00000220, 0x00000222, 0x00010121, 0x00020020, 0x00020022, 0x00020220, 0x00020222, 0x01000121, 0x01010021, 0x01010221, 0x01020120, 0x01020221, 0x02000020, 0x02000022, 0x02000220, 0x02000222, 0x02010021, 0x02010121, 0x02010221, 0x02020020, 0x02020022, 0x02020220, 0x02020222, 0x00011001, 0x00011100, 0x00011102, 0x00021101, 0x01001001, 0x01001201, 0x01011101, 0x01011202, 0x01021100, 0x01021101, 0x02011001, 0x02011201, 0x02021101, 0x00001011, 0x00001110, 0x00001111, 0x00001112, 0x00011111, 0x00011210, 0x00011212, 0x00021211, 0x01001010, 0x01001111, 0x01001212, 0x01011010, 0x01011011, 0x01011110, 0x01011111, 0x01011112, 0x01011211, 0x01021010, 0x01021012, 0x01021111, 0x01021210, 0x01021212, 0x02001011, 0x02011011, 0x02011111, 0x02011210, 0x02011212, 0x02021011, 0x02021110, 0x02021111, 0x02021112, 0x02021211, 0x00011120, 0x00011221, 0x01001021, 0x01001120, 0x01011020, 0x01011022, 0x01011121, 0x01011220, 0x01021020, 0x01021021, 0x01021122, 0x01021221, 0x02001121, 0x02011021, 0x02011120, 0x02011221, 0x00002000, 0x00002002, 0x00002200, 0x00002202, 0x00012101, 0x00022000, 0x00022002, 0x00022200, 0x00022202, 0x01002101, 0x01012001, 0x01012102, 0x01022101, 0x02002000, 0x02002002, 0x02002200, 0x02002202, 0x02012101, 0x02022000, 0x02022002, 0x02022200, 0x02022202, 0x00002111, 0x00012011, 0x00012110, 0x00012211, 0x00022110, 0x00022111, 0x01002011, 0x01012010, 0x01012011, 0x01012111, 0x01022011, 0x01022110, 0x01022211, 0x02012011, 0x02012110, 0x02012112, 0x02012211, 0x02022111, 0x00002020, 0x00002022, 0x00002220, 0x00002222, 0x00012121, 0x00022020, 0x00022022, 0x00022220, 0x00022222, 0x01002121, 0x01012021, 0x01012221, 0x01022021, 0x01022121, 0x02002020, 0x02002022, 0x02002121, 0x02002220, 0x02002222, 0x02012121, 0x02022020, 0x02022022, 0x02022220, 0x02022222, 0x00110000, 0x00110001, 0x00110100, 0x00110201, 0x00120100, 0x00120101, 0x01100001, 0x01100100, 0x01110000, 0x01110101, 0x01110200, 0x01120001, 0x01120100, 0x01120101, 0x01120201, 0x02110001, 0x02110100, 0x02110102, 0x02120001, 0x02120101, 0x00100011, 0x00100110, 0x00100112, 0x00100211, 0x00110010, 0x00110012, 0x00110111, 0x00110210, 0x00120011, 0x00120110, 0x00120211, 0x01100111, 0x01100212, 0x01110010, 0x01110011, 0x01110012, 0x01110110, 0x01110111, 0x01110112, 0x01110211, 0x01120010, 0x01120111, 0x02100110, 0x02110012, 0x02110111, 0x02120011, 0x02120110, 0x00110021, 0x00110120, 0x00110122, 0x00120121, 0x01100020, 0x01100122, 0x01100221, 0x01110022, 0x01110121, 0x01110220, 0x01110222, 0x01120120, 0x01120122, 0x02100121, 0x02110021, 0x02110120, 0x02110122, 0x02120121, 0x00101001, 0x00101102, 0x00101201, 0x00111100, 0x00111101, 0x00111200, 0x00111201, 0x00121001, 0x00121102, 0x01101001, 0x01101101, 0x01101102, 0x01101200, 0x01101202, 0x01111001, 0x01111100, 0x01111101, 0x01111102, 0x01111201, 0x01121002, 0x01121101, 0x01121200, 0x02101100, 0x02101201, 0x02111000, 0x02111100, 0x02111101, 0x02111200, 0x02111201, 0x02111202, 0x02121001, 0x02121100, 0x02121101, 0x02121201, 0x00101012, 0x00101111, 0x00101212, 0x00111011, 0x00111110, 0x00111111, 0x00111112, 0x00111211, 0x00121010, 0x00121012, 0x00121111, 0x00121210, 0x00121212, 0x01101011, 0x01101110, 0x01101111, 0x01101112, 0x01111011, 0x01111012, 0x01111110, 0x01111111, 0x01111112, 0x01111211, 0x01111212, 0x01121011, 0x01121110, 0x01121111, 0x01121112, 0x01121211, 0x02101010, 0x02101012, 0x02101110, 0x02101111, 0x02101210, 0x02101212, 0x02111010, 0x02111011, 0x02111110, 0x02111111, 0x02111112, 0x02111211, 0x02111212, 0x02121010, 0x02121012, 0x02121111, 0x00101021, 0x00101120, 0x00101121, 0x00101122, 0x00111121, 0x00111122, 0x00111220, 0x00111222, 0x00121021, 0x00121122, 0x01101020, 0x01101022, 0x01101120, 0x01101121, 0x01101220, 0x01101222, 0x01111021, 0x01111121, 0x01111122, 0x01111220, 0x01111221, 0x01121021, 0x01121120, 0x01121121, 0x01121220, 0x01121221, 0x01121222, 0x02101122, 0x02101222, 0x02111022, 0x02111121, 0x02121120, 0x02121221, 0x00112001, 0x00112102, 0x00122101, 0x01102001, 0x01102100, 0x01102102, 0x01102201, 0x01112000, 0x01112101, 0x01112200, 0x01112202, 0x01122000, 0x01122001, 0x01122100, 0x01122102, 0x01122201, 0x02102101, 0x02112001, 0x02112100, 0x02122101, 0x00112010, 0x00112012, 0x00112111, 0x00112212, 0x00122011, 0x00122111, 0x01102012, 0x01102110, 0x01102111, 0x01102210, 0x01112011, 0x01112110, 0x01112111, 0x01112112, 0x01112211, 0x01112212, 0x01122010, 0x01122111, 0x01122212, 0x02102211, 0x02112011, 0x02112012, 0x02112111, 0x02112210, 0x02122011, 0x02122112, 0x02122211, 0x00102221, 0x00112122, 0x00122120, 0x00122122, 0x01102120, 0x01102122, 0x01102221, 0x01112020, 0x01112022, 0x01112121, 0x01112220, 0x01122021, 0x01122122, 0x01122221, 0x02102121, 0x02112021, 0x02112122, 0x02112222, 0x00200000, 0x00200002, 0x00200200, 0x00200202, 0x00210101, 0x00220000, 0x00220002, 0x00220101, 0x00220200, 0x00220202, 0x01200101, 0x01210001, 0x01210201, 0x01220001, 0x01220101, 0x02200000, 0x02200002, 0x02200200, 0x02200202, 0x02210101, 0x02220000, 0x02220002, 0x02220101, 0x02220200, 0x02220202, 0x00200111, 0x00210011, 0x00210110, 0x00210211, 0x00220111, 0x01200012, 0x01200110, 0x01200211, 0x01210111, 0x01210210, 0x01210212, 0x01220011, 0x01220110, 0x01220111, 0x01220112, 0x02200111, 0x02210010, 0x02210112, 0x02210211, 0x02220111, 0x00200021, 0x00200220, 0x00200222, 0x00210021, 0x00210121, 0x00220020, 0x00220022, 0x00220220, 0x00220222, 0x01200121, 0x01210021, 0x01210122, 0x01210221, 0x01220121, 0x02200021, 0x02200220, 0x02200222, 0x02210021, 0x02210121, 0x02220020, 0x02220022, 0x02220220, 0x02220222, 0x00201101, 0x00211100, 0x00211102, 0x00211201, 0x00221101, 0x01201100, 0x01201101, 0x01201102, 0x01201201, 0x01211002, 0x01211101, 0x01211200, 0x01211202, 0x01221102, 0x02201101, 0x02211001, 0x02211100, 0x02211201, 0x02221001, 0x02221101, 0x00201211, 0x00211111, 0x00221011, 0x00221211, 0x01201010, 0x01201111, 0x01201210, 0x01211011, 0x01211110, 0x01211111, 0x01211211, 0x01221012, 0x01221111, 0x01221210, 0x02201211, 0x02211010, 0x02211110, 0x02211111, 0x02211210, 0x02211212, 0x02221011, 0x02221110, 0x02221112, 0x02221211, 0x00201121, 0x00211020, 0x00211022, 0x00211221, 0x00221121, 0x01201021, 0x01201221, 0x01211121, 0x01221020, 0x01221021, 0x01221221, 0x02201120, 0x02201122, 0x02211020, 0x02211222, 0x00202000, 0x00202002, 0x00202200, 0x00202202, 0x00212101, 0x00222000, 0x00222002, 0x00222200, 0x00222202, 0x01202101, 0x01212001, 0x01212100, 0x01222101, 0x02202000, 0x02202002, 0x02202200, 0x02202202, 0x02222000, 0x02222002, 0x02222200, 0x02222202, 0x00202211, 0x00212011, 0x00212110, 0x00212211, 0x00222111, 0x01202112, 0x01202211, 0x01212012, 0x01212111, 0x01222011, 0x01222110, 0x01222112, 0x01222211, 0x02202111, 0x02212010, 0x02212112, 0x02212211, 0x02222110, 0x02222111, 0x00202020, 0x00202022, 0x00202220, 0x00202222, 0x00222020, 0x00222022, 0x00222220, 0x00222222, 0x01202121, 0x01212021, 0x01212122, 0x01212221, 0x01222121, 0x02202020, 0x02202022, 0x02202220, 0x02202222, 0x02212121, 0x02222020, 0x02222022, 0x02222220, 0x02222222, 0x10000101, 0x10010001, 0x10010102, 0x10020101, 0x11000201, 0x11010002, 0x11010101, 0x11010200, 0x11010202, 0x11020001, 0x11020100, 0x11020102, 0x12010100, 0x12010201, 0x12020001, 0x12020102, 0x10000010, 0x10000011, 0x10000110, 0x10000112, 0x10000211, 0x10010012, 0x10010111, 0x10010112, 0x10010210, 0x10010212, 0x10020011, 0x10020112, 0x10020211, 0x11000111, 0x11000210, 0x11000212, 0x11010011, 0x11010110, 0x11010111, 0x11010112, 0x11010211, 0x11010212, 0x11020111, 0x11020210, 0x11020212, 0x12000011, 0x12000110, 0x12000112, 0x12010010, 0x12010012, 0x12010111, 0x12020010, 0x12020011, 0x12020012, 0x10000121, 0x10010021, 0x10010120, 0x10010122, 0x10020121, 0x11000021, 0x11010022, 0x11010121, 0x11010222, 0x11020120, 0x11020221, 0x12000221, 0x12010120, 0x12020121, 0x10001001, 0x10011101, 0x10011201, 0x10021201, 0x11001101, 0x11001200, 0x11001202, 0x11011001, 0x11011100, 0x11011101, 0x11011102, 0x11021001, 0x11021002, 0x11021101, 0x11021200, 0x11021202, 0x12001001, 0x12001102, 0x12001201, 0x12011000, 0x12011002, 0x12011101, 0x12021000, 0x12021001, 0x12021201, 0x10001011, 0x10001012, 0x10001111, 0x10001212, 0x10011011, 0x10011110, 0x10011111, 0x10011112, 0x10011211, 0x10021010, 0x10021111, 0x10021212, 0x11001011, 0x11001110, 0x11001111, 0x11001112, 0x11001211, 0x11011010, 0x11011011, 0x11011110, 0x11011111, 0x11011112, 0x11011210, 0x11011211, 0x11021011, 0x11021110, 0x11021111, 0x11021112, 0x11021211, 0x12001012, 0x12001110, 0x12001111, 0x12001210, 0x12011011, 0x12011110, 0x12011111, 0x12011112, 0x12011211, 0x12011212, 0x12021111, 0x12021210, 0x12021212, 0x10001021, 0x10001121, 0x10001221, 0x10011120, 0x10011121, 0x10011220, 0x10011222, 0x10021021, 0x10021120, 0x10021221, 0x11001020, 0x11001022, 0x11001121, 0x11001220, 0x11011020, 0x11011021, 0x11011022, 0x11011121, 0x11011122, 0x11011221, 0x11021022, 0x11021121, 0x11021220, 0x12001021, 0x12001121, 0x12001222, 0x12011120, 0x12011121, 0x12021021, 0x12021120, 0x12021122, 0x10002101, 0x10012001, 0x10012101, 0x10012202, 0x10022101, 0x11002002, 0x11002201, 0x11012000, 0x11012101, 0x11012200, 0x11022001, 0x11022100, 0x11022102, 0x11022201, 0x12002101, 0x12012001, 0x12012100, 0x12012102, 0x12012201, 0x12022101, 0x10002011, 0x10002111, 0x10002112, 0x10002212, 0x10012010, 0x10012110, 0x10012111, 0x10012210, 0x10022011, 0x10022110, 0x10022112, 0x11002010, 0x11002111, 0x11002212, 0x11012011, 0x11012012, 0x11012110, 0x11012111, 0x11012112, 0x11012211, 0x11022010, 0x11022012, 0x11022111, 0x11022112, 0x11022212, 0x12002112, 0x12002211, 0x12012012, 0x12012111, 0x12012112, 0x12012210, 0x12022011, 0x12022110, 0x12022112, 0x12022211, 0x10012122, 0x11002120, 0x11002122, 0x11002221, 0x11012121, 0x11012220, 0x11012222, 0x11022120, 0x11022221, 0x12012120, 0x12022121, 0x10100001, 0x10100100, 0x10100101, 0x10100102, 0x10100201, 0x10110002, 0x10110101, 0x10110202, 0x10120001, 0x10120100, 0x10120201, 0x11100000, 0x11100101, 0x11100200, 0x11110001, 0x11110100, 0x11110101, 0x11110102, 0x11110201, 0x11120101, 0x11120200, 0x12100102, 0x12100201, 0x12110101, 0x12110200, 0x12120000, 0x12120001, 0x12120102, 0x12120201, 0x10100111, 0x10100210, 0x10100211, 0x10100212, 0x10110011, 0x10110110, 0x10110111, 0x10110112, 0x10110210, 0x10110211, 0x10120010, 0x10120111, 0x10120112, 0x10120210, 0x10120212, 0x11100011, 0x11100110, 0x11100111, 0x11100112, 0x11100211, 0x11110010, 0x11110011, 0x11110012, 0x11110110, 0x11110111, 0x11110112, 0x11110210, 0x11110211, 0x11110212, 0x11120011, 0x11120110, 0x11120111, 0x11120112, 0x11120211, 0x12100012, 0x12100111, 0x12110011, 0x12110110, 0x12110111, 0x12110112, 0x12110211, 0x12120010, 0x12120111, 0x12120212, 0x10100021, 0x10100122, 0x10110022, 0x10110121, 0x10110222, 0x10120021, 0x10120120, 0x11100022, 0x11100121, 0x11100222, 0x11110021, 0x11110120, 0x11110121, 0x11110122, 0x11110221, 0x11120022, 0x11120121, 0x12100121, 0x12110020, 0x12110022, 0x12110121, 0x12110221, 0x12110222, 0x12120120, 0x10101100, 0x10101101, 0x10111001, 0x10111100, 0x10111101, 0x10111102, 0x10111200, 0x10111201, 0x10121001, 0x10121101, 0x10121200, 0x10121202, 0x11101001, 0x11101100, 0x11101101, 0x11101102, 0x11101201, 0x11101202, 0x11111000, 0x11111001, 0x11111100, 0x11111101, 0x11111102, 0x11111200, 0x11111201, 0x11111202, 0x11121001, 0x11121002, 0x11121100, 0x11121101, 0x11121102, 0x11121201, 0x12101000, 0x12101200, 0x12101202, 0x12111001, 0x12111100, 0x12111101, 0x12111102, 0x12111201, 0x12121001, 0x12121100, 0x12121101, 0x12121202, 0x10101011, 0x10101012, 0x10101110, 0x10101111, 0x10101112, 0x10101211, 0x10111010, 0x10111011, 0x10111012, 0x10111110, 0x10111111, 0x10111112, 0x10111211, 0x10111212, 0x10121011, 0x10121110, 0x10121111, 0x10121112, 0x10121211, 0x11101010, 0x11101011, 0x11101012, 0x11101110, 0x11101111, 0x11101112, 0x11101210, 0x11101211, 0x11111010, 0x11111011, 0x11111012, 0x11111110, 0x11111111, 0x11111112, 0x11111210, 0x11111211, 0x11111212, 0x11121010, 0x11121011, 0x11121110, 0x11121111, 0x11121112, 0x11121210, 0x11121211, 0x11121212, 0x12101011, 0x12101110, 0x12101111, 0x12101211, 0x12101212, 0x12111010, 0x12111011, 0x12111110, 0x12111111, 0x12111112, 0x12111210, 0x12111211, 0x12121011, 0x12121110, 0x12121111, 0x12121112, 0x12121211, 0x10101020, 0x10101021, 0x10101022, 0x10101120, 0x10101122, 0x10101220, 0x10101221, 0x10111021, 0x10111120, 0x10111121, 0x10111220, 0x10111221, 0x10121020, 0x10121021, 0x10121022, 0x10121120, 0x10121121, 0x10121122, 0x10121220, 0x10121221, 0x11101021, 0x11101121, 0x11101122, 0x11101220, 0x11101221, 0x11101222, 0x11111020, 0x11111021, 0x11111022, 0x11111120, 0x11111121, 0x11111122, 0x11111220, 0x11111221, 0x11111222, 0x11121021, 0x11121120, 0x11121121, 0x11121221, 0x12101022, 0x12101121, 0x12101122, 0x12101220, 0x12101221, 0x12101222, 0x12111021, 0x12111121, 0x12111222, 0x12121022, 0x12121121, 0x12121122, 0x12121220, 0x12121221, 0x10102100, 0x10102101, 0x10102102, 0x10102201, 0x10112000, 0x10112101, 0x10112200, 0x10122001, 0x10122202, 0x11102101, 0x11102200, 0x11102202, 0x11112001, 0x11112100, 0x11112101, 0x11112102, 0x11112200, 0x11112201, 0x11122000, 0x11122002, 0x11122100, 0x11122101, 0x12102002, 0x12102201, 0x12112000, 0x12112002, 0x12112101, 0x12112200, 0x12122001, 0x12122201, 0x10102011, 0x10102012, 0x10102111, 0x10102212, 0x10112011, 0x10112110, 0x10112111, 0x10112112, 0x10112211, 0x10122111, 0x11102011, 0x11102110, 0x11102111, 0x11102112, 0x11102211, 0x11112010, 0x11112011, 0x11112012, 0x11112110, 0x11112111, 0x11112112, 0x11112210, 0x11112211, 0x11112212, 0x11122011, 0x11122110, 0x11122111, 0x11122112, 0x11122211, 0x12102011, 0x12102111, 0x12102211, 0x12112011, 0x12112110, 0x12112111, 0x12112112, 0x12112210, 0x12112211, 0x12122111, 0x10102120, 0x10102220, 0x10112121, 0x10112222, 0x10122020, 0x10122121, 0x10122122, 0x10122221, 0x11102121, 0x11102220, 0x11102221, 0x11112021, 0x11112121, 0x11112122, 0x11112220, 0x11112221, 0x11122022, 0x11122121, 0x11122220, 0x11122222, 0x12102021, 0x12102222, 0x12112022, 0x12112121, 0x12112122, 0x12112220, 0x12112222, 0x12122021, 0x10200101, 0x10210100, 0x10210102, 0x10210201, 0x10220101, 0x11200100, 0x11210000, 0x11210101, 0x11210102, 0x11210200, 0x11210202, 0x11220001, 0x11220100, 0x11220102, 0x11220201, 0x12200001, 0x12210102, 0x12220101, 0x10200011, 0x10200110, 0x10200112, 0x10200211, 0x10210012, 0x10210111, 0x10220011, 0x10220012, 0x10220112, 0x10220211, 0x11200111, 0x11200211, 0x11210011, 0x11210111, 0x11210112, 0x11210211, 0x11220111, 0x11220112, 0x11220212, 0x12200110, 0x12200212, 0x12210012, 0x12210111, 0x12220011, 0x12220112, 0x12220211, 0x10210021, 0x10210122, 0x10210221, 0x11200020, 0x11200021, 0x11200122, 0x11210121, 0x11210122, 0x11210220, 0x11220020, 0x12200121, 0x12210021, 0x12210122, 0x12220121, 0x10211001, 0x10211002, 0x10211101, 0x10211102, 0x10211202, 0x10221001, 0x10221102, 0x10221201, 0x11201000, 0x11201002, 0x11201101, 0x11201200, 0x11201202, 0x11211001, 0x11211100, 0x11211101, 0x11211102, 0x11211201, 0x11211202, 0x11221000, 0x11221002, 0x11221101, 0x12201100, 0x12201101, 0x12201201, 0x12211000, 0x12211002, 0x12211100, 0x12211101, 0x12211102, 0x12211200, 0x12211202, 0x12221001, 0x12221100, 0x12221201, 0x10201111, 0x10201210, 0x10201212, 0x10211011, 0x10211111, 0x10211112, 0x10211211, 0x11201110, 0x11201111, 0x11201112, 0x11201211, 0x11211010, 0x11211011, 0x11211110, 0x11211111, 0x11211112, 0x11211211, 0x11221011, 0x11221110, 0x11221111, 0x11221112, 0x11221211, 0x12201112, 0x12201211, 0x12201212, 0x12211011, 0x12211111, 0x12211112, 0x12211211, 0x12211212, 0x12221012, 0x12221111, 0x12221112, 0x12221210, 0x10201022, 0x10201221, 0x10211121, 0x10221020, 0x10221122, 0x10221220, 0x10221221, 0x11201020, 0x11201121, 0x11201220, 0x11201222, 0x11211021, 0x11211120, 0x11211121, 0x11211122, 0x11211220, 0x11211222, 0x11221020, 0x11221121, 0x11221220, 0x12201020, 0x12201022, 0x12201121, 0x12201222, 0x12211120, 0x12211122, 0x12211220, 0x12211221, 0x12221020, 0x12221120, 0x12221122, 0x12221222, 0x10212102, 0x10212201, 0x10222101, 0x11202001, 0x11212002, 0x11212101, 0x11212202, 0x11222001, 0x11222201, 0x12202101, 0x12212001, 0x12212200, 0x12222102, 0x10202011, 0x10202110, 0x10212010, 0x10212111, 0x10222011, 0x10222110, 0x10222112, 0x10222211, 0x11202010, 0x11202011, 0x11202111, 0x11202112, 0x11202210, 0x11212011, 0x11212110, 0x11212111, 0x11212112, 0x11212211, 0x11222010, 0x11222111, 0x11222212, 0x12202012, 0x12202110, 0x12202212, 0x12212111, 0x12222011, 0x12222110, 0x12222111, 0x12222211, 0x10212021, 0x10212122, 0x10212220, 0x11202021, 0x11202120, 0x11202221, 0x11212020, 0x11212121, 0x11212220, 0x11212222, 0x11222120, 0x11222121, 0x11222221, 0x12202122, 0x12212120, 0x12212220, 0x12212222, 0x12222122, 0x20000000, 0x20000002, 0x20000200, 0x20000202, 0x20020000, 0x20020002, 0x20020200, 0x20020202, 0x21000101, 0x21010000, 0x21010001, 0x21010100, 0x21010102, 0x21010201, 0x21020101, 0x22000000, 0x22000002, 0x22000200, 0x22000202, 0x22010101, 0x22020000, 0x22020002, 0x22020200, 0x22020202, 0x20000111, 0x20010011, 0x20010110, 0x20010112, 0x20010211, 0x20020111, 0x21000011, 0x21000110, 0x21000211, 0x21010010, 0x21010012, 0x21010111, 0x21010112, 0x21010210, 0x21010211, 0x21020110, 0x21020112, 0x21020211, 0x22000111, 0x22000211, 0x22010110, 0x22010112, 0x22010211, 0x22020111, 0x20000020, 0x20000022, 0x20000220, 0x20000222, 0x20010121, 0x20020020, 0x20020022, 0x20020220, 0x20020222, 0x21010021, 0x21010120, 0x21010221, 0x21020121, 0x22000020, 0x22000022, 0x22000220, 0x22000222, 0x22010121, 0x22020020, 0x22020022, 0x22020220, 0x22020222, 0x20011100, 0x20011201, 0x21001001, 0x21001100, 0x21011001, 0x21011101, 0x21011202, 0x21021001, 0x21021100, 0x21021201, 0x22011100, 0x22011201, 0x20001011, 0x20001211, 0x20011012, 0x20011111, 0x20011212, 0x20021112, 0x20021211, 0x21001010, 0x21001011, 0x21001111, 0x21001210, 0x21011011, 0x21011110, 0x21011111, 0x21011112, 0x21011211, 0x21011212, 0x21021111, 0x21021112, 0x21021210, 0x21021212, 0x22001011, 0x22001110, 0x22001112, 0x22001211, 0x22011010, 0x22011012, 0x22011111, 0x22011210, 0x22021112, 0x20011021, 0x20011122, 0x20011221, 0x20021121, 0x21001021, 0x21001120, 0x21001221, 0x21001222, 0x21011020, 0x21011121, 0x21011221, 0x21011222, 0x21021021, 0x21021122, 0x21021222, 0x22001121, 0x22011021, 0x22011222, 0x22021120, 0x20002000, 0x20002002, 0x20002200, 0x20002202, 0x20012101, 0x20022000, 0x20022002, 0x20022200, 0x20022202, 0x21002001, 0x21002101, 0x21012001, 0x21012100, 0x21012201, 0x21022101, 0x21022201, 0x22002000, 0x22002002, 0x22002200, 0x22002202, 0x22012101, 0x22022000, 0x22022002, 0x22022200, 0x22022202, 0x20002111, 0x20002112, 0x20012011, 0x20012110, 0x20012112, 0x20022111, 0x21002011, 0x21002110, 0x21002112, 0x21002211, 0x21012010, 0x21012012, 0x21012111, 0x21012212, 0x21022011, 0x21022110, 0x22002111, 0x22012112, 0x22012211, 0x22022111, 0x20002020, 0x20002022, 0x20002220, 0x20002222, 0x20012121, 0x20022020, 0x20022022, 0x20022220, 0x20022222, 0x21002121, 0x21012021, 0x21012120, 0x21012122, 0x22002020, 0x22002022, 0x22002220, 0x22002222, 0x22012121, 0x22022020, 0x22022022, 0x22022220, 0x22022222, 0x20100101, 0x20110001, 0x20110102, 0x20110200, 0x20110201, 0x20120101, 0x21100001, 0x21100102, 0x21100201, 0x21110101, 0x21110200, 0x21110202, 0x21120201, 0x21120202, 0x22100101, 0x22110001, 0x22110100, 0x22110102, 0x22110201, 0x22120101, 0x20100011, 0x20100110, 0x20100112, 0x20100211, 0x20110010, 0x20110111, 0x20110210, 0x20110212, 0x20120011, 0x20120110, 0x20120112, 0x20120211, 0x21100010, 0x21100111, 0x21110010, 0x21110011, 0x21110110, 0x21110111, 0x21110112, 0x21110211, 0x21120012, 0x21120111, 0x22100110, 0x22100112, 0x22110012, 0x22110111, 0x22110210, 0x22120011, 0x22120110, 0x22120112, 0x22120211, 0x20100121, 0x20110021, 0x20110120, 0x20110221, 0x20120121, 0x21100120, 0x21100122, 0x21100221, 0x21110020, 0x21110022, 0x21110121, 0x21110220, 0x21120122, 0x21120221, 0x22100121, 0x22110120, 0x22110122, 0x22120221, 0x20101001, 0x20101100, 0x20101102, 0x20111000, 0x20111101, 0x20111200, 0x20121102, 0x21101000, 0x21101202, 0x21111001, 0x21111100, 0x21111101, 0x21111102, 0x21111200, 0x21111201, 0x21121000, 0x21121001, 0x21121002, 0x21121101, 0x22101100, 0x22101102, 0x22111002, 0x22111100, 0x22111101, 0x22111200, 0x22121001, 0x22121201, 0x20101010, 0x20101111, 0x20101210, 0x20101212, 0x20111010, 0x20111011, 0x20111110, 0x20111111, 0x20111112, 0x20111211, 0x20121011, 0x20121111, 0x20121211, 0x20121212, 0x21101011, 0x21101110, 0x21101111, 0x21101112, 0x21101211, 0x21111010, 0x21111011, 0x21111012, 0x21111110, 0x21111111, 0x21111112, 0x21111210, 0x21111211, 0x21111212, 0x21121011, 0x21121110, 0x21121111, 0x21121112, 0x21121211, 0x22101011, 0x22101111, 0x22101210, 0x22111011, 0x22111012, 0x22111110, 0x22111111, 0x22111112, 0x22111211, 0x22111212, 0x22121010, 0x22121012, 0x22121111, 0x22121210, 0x22121212, 0x20101021, 0x20101120, 0x20111020, 0x20111121, 0x20111221, 0x20121020, 0x20121122, 0x20121221, 0x21101121, 0x21101220, 0x21101221, 0x21111021, 0x21111022, 0x21111121, 0x21111122, 0x21111221, 0x21121121, 0x21121220, 0x22101022, 0x22101120, 0x22101221, 0x22101222, 0x22111022, 0x22111120, 0x22111121, 0x22121120, 0x22121122, 0x22121221, 0x20102101, 0x20112102, 0x20112201, 0x20122101, 0x21102001, 0x21102102, 0x21112000, 0x21112002, 0x21112101, 0x21112102, 0x21112202, 0x21122100, 0x21122101, 0x22102101, 0x22112001, 0x22112102, 0x22112201, 0x22122101, 0x20102110, 0x20102112, 0x20102211, 0x20112010, 0x20112012, 0x20112111, 0x20112210, 0x20112212, 0x20122010, 0x20122011, 0x20122110, 0x20122112, 0x21102010, 0x21102012, 0x21102111, 0x21102210, 0x21102212, 0x21112011, 0x21112110, 0x21112111, 0x21112112, 0x21112211, 0x21122012, 0x21122111, 0x21122112, 0x21122212, 0x22102011, 0x22102110, 0x22112010, 0x22112012, 0x22112111, 0x22112212, 0x22122011, 0x22122112, 0x20102121, 0x20112121, 0x20122121, 0x21102120, 0x21102122, 0x21102221, 0x21112020, 0x21112121, 0x21112220, 0x21122021, 0x22102121, 0x22112021, 0x22112120, 0x22112121, 0x22112122, 0x20200000, 0x20200002, 0x20200200, 0x20200202, 0x20210101, 0x20220000, 0x20220002, 0x20220200, 0x20220202, 0x21200101, 0x21210001, 0x21210100, 0x21210102, 0x21210201, 0x22200000, 0x22200002, 0x22200200, 0x22200202, 0x22210101, 0x22220000, 0x22220002, 0x22220200, 0x22220202, 0x20200111, 0x20200211, 0x20210011, 0x20210110, 0x20210112, 0x20210211, 0x20210212, 0x21200112, 0x21200211, 0x21210011, 0x21210111, 0x21210210, 0x21210212, 0x21220011, 0x21220110, 0x22200111, 0x22210010, 0x22210012, 0x22210112, 0x22210211, 0x20200022, 0x20200220, 0x20200222, 0x20210020, 0x20210221, 0x20220022, 0x20220220, 0x20220222, 0x21200121, 0x21210021, 0x21210122, 0x21210221, 0x21220121, 0x22200020, 0x22200022, 0x22200220, 0x22200222, 0x22210121, 0x22220020, 0x22220022, 0x22220220, 0x22220222, 0x20211201, 0x20221101, 0x21201001, 0x21201100, 0x21211000, 0x21211100, 0x21211101, 0x21211200, 0x21211202, 0x21221001, 0x21221101, 0x21221102, 0x21221200, 0x21221201, 0x22201101, 0x20201112, 0x20201211, 0x20211010, 0x20211012, 0x20211111, 0x20211210, 0x20221112, 0x20221211, 0x21201012, 0x21201111, 0x21211011, 0x21211110, 0x21211111, 0x21211112, 0x21211211, 0x21221111, 0x21221212, 0x22201011, 0x22201110, 0x22201111, 0x22201112, 0x22201211, 0x22211012, 0x22211111, 0x22211210, 0x20201121, 0x20211021, 0x20211122, 0x20211222, 0x20221021, 0x20221121, 0x21201120, 0x21201122, 0x21201222, 0x21211022, 0x21211121, 0x21211122, 0x21211220, 0x21221020, 0x21221022, 0x22201122, 0x22211020, 0x22211121, 0x22211122, 0x22211221, 0x22221021, 0x22221120, 0x22221122, 0x20202000, 0x20202002, 0x20202200, 0x20202202, 0x20222000, 0x20222002, 0x20222200, 0x20222202, 0x21212001, 0x21212100, 0x21212102, 0x21212201, 0x22202000, 0x22202002, 0x22202200, 0x22202202, 0x22212101, 0x22222000, 0x22222002, 0x22222200, 0x22222202, 0x20202111, 0x20212110, 0x20212211, 0x20222011, 0x20222111, 0x21202011, 0x21212010, 0x21212111, 0x21212212, 0x21222011, 0x21222112, 0x21222211, 0x22212010, 0x22212112, 0x20202020, 0x20202022, 0x20202220, 0x20202222, 0x20222020, 0x20222022, 0x20222220, 0x20222222, 0x21212021, 0x21212120, 0x21212122, 0x22202020, 0x22202022, 0x22202220, 0x22202222, 0x22212121, 0x22222020, 0x22222022, 0x22222220, 0x22222222, GGML_TABLE_END() enum ggml_sort_order { GGML_SORT_ORDER_ASC, GGML_SORT_ORDER_DESC, }; // general-purpose kernel for addition, subtraction, multiplication and division of two tensors // pros: works for non-contiguous tensors, supports broadcast across all dims // cons: not very efficient kernel void kernel_add( device const char * src0, device const char * src1, device char * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant int64_t & ne03, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant uint64_t & nb03, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant int64_t & ne13, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant uint64_t & nb13, constant int64_t & ne0, constant int64_t & ne1, constant int64_t & ne2, constant int64_t & ne3, constant uint64_t & nb0, constant uint64_t & nb1, constant uint64_t & nb2, constant uint64_t & nb3, constant int64_t & offs, uint3 tgpig[[threadgroup_position_in_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg[[threads_per_threadgroup]]) { const int64_t i03 = tgpig.z; const int64_t i02 = tgpig.y; const int64_t i01 = tgpig.x; const int64_t i13 = i03 % ne13; const int64_t i12 = i02 % ne12; const int64_t i11 = i01 % ne11; device const char * src0_ptr = src0 + i03*nb03 + i02*nb02 + i01*nb01 + offs; device const char * src1_ptr = src1 + i13*nb13 + i12*nb12 + i11*nb11; device char * dst_ptr = dst + i03*nb3 + i02*nb2 + i01*nb1 + offs; for (int i0 = tpitg.x; i0 < ne0; i0 += ntg.x) { const int i10 = i0 % ne10; *((device float *)(dst_ptr + i0*nb0)) = *((device float *)(src0_ptr + i0*nb00)) + *((device float *)(src1_ptr + i10*nb10)); } } kernel void kernel_sub( device const char * src0, device const char * src1, device char * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant int64_t & ne03, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant uint64_t & nb03, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant int64_t & ne13, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant uint64_t & nb13, constant int64_t & ne0, constant int64_t & ne1, constant int64_t & ne2, constant int64_t & ne3, constant uint64_t & nb0, constant uint64_t & nb1, constant uint64_t & nb2, constant uint64_t & nb3, constant int64_t & offs, uint3 tgpig[[threadgroup_position_in_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg[[threads_per_threadgroup]]) { const int64_t i03 = tgpig.z; const int64_t i02 = tgpig.y; const int64_t i01 = tgpig.x; const int64_t i13 = i03 % ne13; const int64_t i12 = i02 % ne12; const int64_t i11 = i01 % ne11; device const char * src0_ptr = src0 + i03*nb03 + i02*nb02 + i01*nb01 + offs; device const char * src1_ptr = src1 + i13*nb13 + i12*nb12 + i11*nb11; device char * dst_ptr = dst + i03*nb3 + i02*nb2 + i01*nb1 + offs; for (int i0 = tpitg.x; i0 < ne0; i0 += ntg.x) { const int i10 = i0 % ne10; *((device float *)(dst_ptr + i0*nb0)) = *((device float *)(src0_ptr + i0*nb00)) - *((device float *)(src1_ptr + i10*nb10)); } } kernel void kernel_mul( device const char * src0, device const char * src1, device char * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant int64_t & ne03, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant uint64_t & nb03, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant int64_t & ne13, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant uint64_t & nb13, constant int64_t & ne0, constant int64_t & ne1, constant int64_t & ne2, constant int64_t & ne3, constant uint64_t & nb0, constant uint64_t & nb1, constant uint64_t & nb2, constant uint64_t & nb3, uint3 tgpig[[threadgroup_position_in_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg[[threads_per_threadgroup]]) { const int64_t i03 = tgpig.z; const int64_t i02 = tgpig.y; const int64_t i01 = tgpig.x; const int64_t i13 = i03 % ne13; const int64_t i12 = i02 % ne12; const int64_t i11 = i01 % ne11; device const char * src0_ptr = src0 + i03*nb03 + i02*nb02 + i01*nb01; device const char * src1_ptr = src1 + i13*nb13 + i12*nb12 + i11*nb11; device char * dst_ptr = dst + i03*nb3 + i02*nb2 + i01*nb1; for (int i0 = tpitg.x; i0 < ne0; i0 += ntg.x) { const int i10 = i0 % ne10; *((device float *)(dst_ptr + i0*nb0)) = *((device float *)(src0_ptr + i0*nb00)) * *((device float *)(src1_ptr + i10*nb10)); } } kernel void kernel_div( device const char * src0, device const char * src1, device char * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant int64_t & ne03, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant uint64_t & nb03, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant int64_t & ne13, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant uint64_t & nb13, constant int64_t & ne0, constant int64_t & ne1, constant int64_t & ne2, constant int64_t & ne3, constant uint64_t & nb0, constant uint64_t & nb1, constant uint64_t & nb2, constant uint64_t & nb3, uint3 tgpig[[threadgroup_position_in_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg[[threads_per_threadgroup]]) { const int64_t i03 = tgpig.z; const int64_t i02 = tgpig.y; const int64_t i01 = tgpig.x; const int64_t i13 = i03 % ne13; const int64_t i12 = i02 % ne12; const int64_t i11 = i01 % ne11; device const char * src0_ptr = src0 + i03*nb03 + i02*nb02 + i01*nb01; device const char * src1_ptr = src1 + i13*nb13 + i12*nb12 + i11*nb11; device char * dst_ptr = dst + i03*nb3 + i02*nb2 + i01*nb1; for (int i0 = tpitg.x; i0 < ne0; i0 += ntg.x) { const int i10 = i0 % ne10; *((device float *)(dst_ptr + i0*nb0)) = *((device float *)(src0_ptr + i0*nb00)) / *((device float *)(src1_ptr + i10*nb10)); } } template<typename T> kernel void kernel_repeat( device const char * src0, device char * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant int64_t & ne03, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant uint64_t & nb03, constant int64_t & ne0, constant int64_t & ne1, constant int64_t & ne2, constant int64_t & ne3, constant uint64_t & nb0, constant uint64_t & nb1, constant uint64_t & nb2, constant uint64_t & nb3, uint3 tgpig[[threadgroup_position_in_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg[[threads_per_threadgroup]]) { const int64_t i3 = tgpig.z; const int64_t i2 = tgpig.y; const int64_t i1 = tgpig.x; const int64_t i03 = i3 % ne03; const int64_t i02 = i2 % ne02; const int64_t i01 = i1 % ne01; device const char * src0_ptr = src0 + i03*nb03 + i02*nb02 + i01*nb01; device char * dst_ptr = dst + i3*nb3 + i2*nb2 + i1*nb1 ; for (int i0 = tpitg.x; i0 < ne0; i0 += ntg.x) { const int i00 = i0 % ne00; *((device T *)(dst_ptr + i0*nb0)) = *((device T *)(src0_ptr + i00*nb00)); } } typedef decltype(kernel_repeat<float>) kernel_repeat_t; template [[host_name("kernel_repeat_f32")]] kernel kernel_repeat_t kernel_repeat<float>; template [[host_name("kernel_repeat_f16")]] kernel kernel_repeat_t kernel_repeat<half>; template [[host_name("kernel_repeat_i32")]] kernel kernel_repeat_t kernel_repeat<int>; template [[host_name("kernel_repeat_i16")]] kernel kernel_repeat_t kernel_repeat<short>; // assumption: src1 is a row // broadcast src1 into src0 kernel void kernel_add_row( device const float4 * src0, device const float4 * src1, device float4 * dst, constant uint64_t & nb [[buffer(28)]], uint tpig[[thread_position_in_grid]]) { dst[tpig] = src0[tpig] + src1[tpig % nb]; } kernel void kernel_sub_row( device const float4 * src0, device const float4 * src1, device float4 * dst, constant uint64_t & nb [[buffer(28)]], uint tpig[[thread_position_in_grid]]) { dst[tpig] = src0[tpig] - src1[tpig % nb]; } kernel void kernel_mul_row( device const float4 * src0, device const float4 * src1, device float4 * dst, constant uint64_t & nb [[buffer(28)]], uint tpig[[thread_position_in_grid]]) { dst[tpig] = src0[tpig] * src1[tpig % nb]; } kernel void kernel_div_row( device const float4 * src0, device const float4 * src1, device float4 * dst, constant uint64_t & nb [[buffer(28)]], uint tpig[[thread_position_in_grid]]) { dst[tpig] = src0[tpig] / src1[tpig % nb]; } kernel void kernel_scale( device const float * src0, device float * dst, constant float & scale, uint tpig[[thread_position_in_grid]]) { dst[tpig] = src0[tpig] * scale; } kernel void kernel_scale_4( device const float4 * src0, device float4 * dst, constant float & scale, uint tpig[[thread_position_in_grid]]) { dst[tpig] = src0[tpig] * scale; } kernel void kernel_clamp( device const float * src0, device float * dst, constant float & min, constant float & max, uint tpig[[thread_position_in_grid]]) { dst[tpig] = src0[tpig] < min ? min : (src0[tpig] > max ? max : src0[tpig]); } kernel void kernel_relu( device const float * src0, device float * dst, uint tpig[[thread_position_in_grid]]) { dst[tpig] = max(0.0f, src0[tpig]); } kernel void kernel_sigmoid( device const float * src0, device float * dst, uint tpig[[thread_position_in_grid]]) { dst[tpig] = 1.0f / (1.0f + exp(-src0[tpig])); } kernel void kernel_tanh( device const float * src0, device float * dst, uint tpig[[thread_position_in_grid]]) { device const float & x = src0[tpig]; dst[tpig] = precise::tanh(x); } constant float GELU_COEF_A = 0.044715f; constant float GELU_QUICK_COEF = -1.702f; constant float SQRT_2_OVER_PI = 0.79788456080286535587989211986876f; kernel void kernel_gelu( device const float * src0, device float * dst, uint tpig[[thread_position_in_grid]]) { device const float & x = src0[tpig]; dst[tpig] = 0.5f*x*(1.0f + precise::tanh(SQRT_2_OVER_PI*x*(1.0f + GELU_COEF_A*x*x))); } kernel void kernel_gelu_4( device const float4 * src0, device float4 * dst, uint tpig[[thread_position_in_grid]]) { device const float4 & x = src0[tpig]; // BEWARE !!! // Simply using "tanh" instead of "precise::tanh" will sometimes results in NaNs! // This was observed with Falcon 7B and 40B models // dst[tpig] = 0.5f*x*(1.0f + precise::tanh(SQRT_2_OVER_PI*x*(1.0f + GELU_COEF_A*x*x))); } kernel void kernel_gelu_quick( device const float * src0, device float * dst, uint tpig[[thread_position_in_grid]]) { device const float & x = src0[tpig]; dst[tpig] = x*(1.0f/(1.0f+exp(GELU_QUICK_COEF*x))); } kernel void kernel_gelu_quick_4( device const float4 * src0, device float4 * dst, uint tpig[[thread_position_in_grid]]) { device const float4 & x = src0[tpig]; dst[tpig] = x*(1.0f/(1.0f+exp(GELU_QUICK_COEF*x))); } kernel void kernel_silu( device const float * src0, device float * dst, uint tpig[[thread_position_in_grid]]) { device const float & x = src0[tpig]; dst[tpig] = x / (1.0f + exp(-x)); } kernel void kernel_silu_4( device const float4 * src0, device float4 * dst, uint tpig[[thread_position_in_grid]]) { device const float4 & x = src0[tpig]; dst[tpig] = x / (1.0f + exp(-x)); } kernel void kernel_sqr( device const float * src0, device float * dst, uint tpig[[thread_position_in_grid]]) { dst[tpig] = src0[tpig] * src0[tpig]; } kernel void kernel_sqrt( device const float * src0, device float * dst, uint tpig[[thread_position_in_grid]]) { dst[tpig] = sqrt(src0[tpig]); } kernel void kernel_sin( device const float * src0, device float * dst, uint tpig[[thread_position_in_grid]]) { dst[tpig] = sin(src0[tpig]); } kernel void kernel_cos( device const float * src0, device float * dst, uint tpig[[thread_position_in_grid]]) { dst[tpig] = cos(src0[tpig]); } kernel void kernel_sum_rows( device const float * src0, device float * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant int64_t & ne03, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant uint64_t & nb03, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant int64_t & ne13, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant uint64_t & nb13, constant int64_t & ne0, constant int64_t & ne1, constant int64_t & ne2, constant int64_t & ne3, constant uint64_t & nb0, constant uint64_t & nb1, constant uint64_t & nb2, constant uint64_t & nb3, uint3 tpig[[thread_position_in_grid]]) { int64_t i3 = tpig.z; int64_t i2 = tpig.y; int64_t i1 = tpig.x; if (i3 >= ne03 || i2 >= ne02 || i1 >= ne01) { return; } device const float * src_row = (device const float *) ((device const char *) src0 + i1*nb01 + i2*nb02 + i3*nb03); device float * dst_row = (device float *) ((device char *) dst + i1*nb1 + i2*nb2 + i3*nb3); float row_sum = 0; for (int64_t i0 = 0; i0 < ne00; i0++) { row_sum += src_row[i0]; } dst_row[0] = row_sum; } template<typename T> kernel void kernel_soft_max( device const char * src0, device const char * src1, device char * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant float & scale, constant float & max_bias, constant float & m0, constant float & m1, constant uint32_t & n_head_log2, threadgroup float * buf [[threadgroup(0)]], uint tgpig[[threadgroup_position_in_grid]], uint tpitg[[thread_position_in_threadgroup]], uint sgitg[[simdgroup_index_in_threadgroup]], uint tiisg[[thread_index_in_simdgroup]], uint ntg[[threads_per_threadgroup]]) { const int64_t i03 = (tgpig) / (ne02*ne01); const int64_t i02 = (tgpig - i03*ne02*ne01) / ne01; const int64_t i01 = (tgpig - i03*ne02*ne01 - i02*ne01); device const float * psrc0 = (device const float *) src0 + (i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00); device const T * pmask = src1 != src0 ? (device const T *) src1 + i01*ne00 : nullptr; device float * pdst = (device float *) dst + (i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00); float slope = 1.0f; // ALiBi if (max_bias > 0.0f) { const int64_t h = i02; const float base = h < n_head_log2 ? m0 : m1; const int exp = h < n_head_log2 ? h + 1 : 2*(h - n_head_log2) + 1; slope = pow(base, exp); } // parallel max float lmax = -INFINITY; for (int i00 = tpitg; i00 < ne00; i00 += ntg) { lmax = MAX(lmax, psrc0[i00]*scale + (pmask ? slope*pmask[i00] : 0.0f)); } // find the max value in the block float max_val = simd_max(lmax); if (ntg > N_SIMDWIDTH) { if (sgitg == 0) { buf[tiisg] = -INFINITY; } threadgroup_barrier(mem_flags::mem_threadgroup); if (tiisg == 0) { buf[sgitg] = max_val; } threadgroup_barrier(mem_flags::mem_threadgroup); max_val = buf[tiisg]; max_val = simd_max(max_val); } // parallel sum float lsum = 0.0f; for (int i00 = tpitg; i00 < ne00; i00 += ntg) { const float exp_psrc0 = exp((psrc0[i00]*scale + (pmask ? slope*pmask[i00] : 0.0f)) - max_val); lsum += exp_psrc0; pdst[i00] = exp_psrc0; } // This barrier fixes a failing test // ref: https://github.com/ggerganov/ggml/pull/621#discussion_r1425156335 threadgroup_barrier(mem_flags::mem_none); float sum = simd_sum(lsum); if (ntg > N_SIMDWIDTH) { if (sgitg == 0) { buf[tiisg] = 0.0f; } threadgroup_barrier(mem_flags::mem_threadgroup); if (tiisg == 0) { buf[sgitg] = sum; } threadgroup_barrier(mem_flags::mem_threadgroup); sum = buf[tiisg]; sum = simd_sum(sum); } const float inv_sum = 1.0f/sum; for (int i00 = tpitg; i00 < ne00; i00 += ntg) { pdst[i00] *= inv_sum; } } template<typename T> kernel void kernel_soft_max_4( device const char * src0, device const char * src1, device char * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant float & scale, constant float & max_bias, constant float & m0, constant float & m1, constant uint32_t & n_head_log2, threadgroup float * buf [[threadgroup(0)]], uint tgpig[[threadgroup_position_in_grid]], uint tpitg[[thread_position_in_threadgroup]], uint sgitg[[simdgroup_index_in_threadgroup]], uint tiisg[[thread_index_in_simdgroup]], uint ntg[[threads_per_threadgroup]]) { const int64_t i03 = (tgpig) / (ne02*ne01); const int64_t i02 = (tgpig - i03*ne02*ne01) / ne01; const int64_t i01 = (tgpig - i03*ne02*ne01 - i02*ne01); device const float4 * psrc4 = (device const float4 *) src0 + (i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00)/4; device const T * pmask = src1 != src0 ? (device const T *) src1 + i01*ne00/4 : nullptr; device float4 * pdst4 = (device float4 *) dst + (i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00)/4; float slope = 1.0f; if (max_bias > 0.0f) { const int64_t h = i02; const float base = h < n_head_log2 ? m0 : m1; const int exp = h < n_head_log2 ? h + 1 : 2*(h - n_head_log2) + 1; slope = pow(base, exp); } // parallel max float4 lmax4 = -INFINITY; for (int i00 = tpitg; i00 < ne00/4; i00 += ntg) { lmax4 = fmax(lmax4, psrc4[i00]*scale + (float4)((pmask ? slope*pmask[i00] : 0.0f))); } const float lmax = MAX(MAX(lmax4[0], lmax4[1]), MAX(lmax4[2], lmax4[3])); float max_val = simd_max(lmax); if (ntg > N_SIMDWIDTH) { if (sgitg == 0) { buf[tiisg] = -INFINITY; } threadgroup_barrier(mem_flags::mem_threadgroup); if (tiisg == 0) { buf[sgitg] = max_val; } threadgroup_barrier(mem_flags::mem_threadgroup); max_val = buf[tiisg]; max_val = simd_max(max_val); } // parallel sum float4 lsum4 = 0.0f; for (int i00 = tpitg; i00 < ne00/4; i00 += ntg) { const float4 exp_psrc4 = exp((psrc4[i00]*scale + (float4)((pmask ? slope*pmask[i00] : 0.0f))) - max_val); lsum4 += exp_psrc4; pdst4[i00] = exp_psrc4; } const float lsum = lsum4[0] + lsum4[1] + lsum4[2] + lsum4[3]; // This barrier fixes a failing test // ref: https://github.com/ggerganov/ggml/pull/621#discussion_r1425156335 threadgroup_barrier(mem_flags::mem_none); float sum = simd_sum(lsum); if (ntg > N_SIMDWIDTH) { if (sgitg == 0) { buf[tiisg] = 0.0f; } threadgroup_barrier(mem_flags::mem_threadgroup); if (tiisg == 0) { buf[sgitg] = sum; } threadgroup_barrier(mem_flags::mem_threadgroup); sum = buf[tiisg]; sum = simd_sum(sum); } const float inv_sum = 1.0f/sum; for (int i00 = tpitg; i00 < ne00/4; i00 += ntg) { pdst4[i00] *= inv_sum; } } typedef decltype(kernel_soft_max<float>) kernel_soft_max_t; typedef decltype(kernel_soft_max_4<float4>) kernel_soft_max_4_t; template [[host_name("kernel_soft_max_f16")]] kernel kernel_soft_max_t kernel_soft_max<half>; template [[host_name("kernel_soft_max_f32")]] kernel kernel_soft_max_t kernel_soft_max<float>; template [[host_name("kernel_soft_max_f16_4")]] kernel kernel_soft_max_4_t kernel_soft_max_4<half4>; template [[host_name("kernel_soft_max_f32_4")]] kernel kernel_soft_max_4_t kernel_soft_max_4<float4>; kernel void kernel_diag_mask_inf( device const float * src0, device float * dst, constant int64_t & ne00, constant int64_t & ne01, constant int & n_past, uint3 tpig[[thread_position_in_grid]]) { const int64_t i02 = tpig[2]; const int64_t i01 = tpig[1]; const int64_t i00 = tpig[0]; if (i00 > n_past + i01) { dst[i02*ne01*ne00 + i01*ne00 + i00] = -INFINITY; } else { dst[i02*ne01*ne00 + i01*ne00 + i00] = src0[i02*ne01*ne00 + i01*ne00 + i00]; } } kernel void kernel_diag_mask_inf_8( device const float4 * src0, device float4 * dst, constant int64_t & ne00, constant int64_t & ne01, constant int & n_past, uint3 tpig[[thread_position_in_grid]]) { const int64_t i = 2*tpig[0]; dst[i+0] = src0[i+0]; dst[i+1] = src0[i+1]; int64_t i4 = 4*i; const int64_t i02 = i4/(ne00*ne01); i4 -= i02*ne00*ne01; const int64_t i01 = i4/(ne00); i4 -= i01*ne00; const int64_t i00 = i4; for (int k = 3; k >= 0; --k) { if (i00 + 4 + k <= n_past + i01) { break; } dst[i+1][k] = -INFINITY; if (i00 + k > n_past + i01) { dst[i][k] = -INFINITY; } } } // ref: ggml.c:ggml_compute_forward_ssm_conv_f32 // TODO: optimize kernel void kernel_ssm_conv_f32( device const void * src0, device const void * src1, device float * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne10, constant int64_t & ne11, constant uint64_t & nb10, constant uint64_t & nb11, constant int64_t & ne0, constant int64_t & ne1, constant int64_t & ne2, constant uint64_t & nb0, constant uint64_t & nb1, constant uint64_t & nb2, uint3 tgpig[[threadgroup_position_in_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg[[threads_per_threadgroup]]) { const int64_t ir = tgpig.x; const int64_t i2 = tgpig.y; const int64_t i3 = tgpig.z; const int64_t nc = ne10; const int64_t ncs = ne00; const int64_t nr = ne01; const int64_t n_t = ne1; const int64_t n_s = ne2; device const float * s = (device const float *) ((device const char *) src0 + ir*nb01 + i2*nb00 + i3*nb02); device const float * c = (device const float *) ((device const char *) src1 + ir*nb11); device float * x = (device float *) ((device char *) dst + ir*nb0 + i2*nb1 + i3*nb2); float sumf = 0.0f; for (int64_t i0 = 0; i0 < nc; ++i0) { sumf += s[i0] * c[i0]; } x[0] = sumf; } // ref: ggml.c:ggml_compute_forward_ssm_scan_f32 // TODO: optimize kernel void kernel_ssm_scan_f32( device const void * src0, device const void * src1, device const void * src2, device const void * src3, device const void * src4, device const void * src5, device float * dst, constant int64_t & d_state, constant int64_t & d_inner, constant int64_t & n_seq_tokens, constant int64_t & n_seqs, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant uint64_t & nb13, constant uint64_t & nb20, constant uint64_t & nb21, constant uint64_t & nb22, constant uint64_t & nb30, constant uint64_t & nb31, constant uint64_t & nb40, constant uint64_t & nb41, constant uint64_t & nb42, constant uint64_t & nb50, constant uint64_t & nb51, constant uint64_t & nb52, uint3 tgpig[[threadgroup_position_in_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg[[threads_per_threadgroup]]) { const int64_t ir = tgpig.x; const int64_t i3 = tgpig.y; const int64_t nc = d_state; const int64_t nr = d_inner; const int64_t n_t = n_seq_tokens; const int64_t n_s = n_seqs; for (int64_t i2 = 0; i2 < n_t; ++i2) { device const float * s0 = (device const float *) ((device const char *) src0 + ir*nb01 + i3*nb02); device const float * x = (device const float *) ((device const char *) src1 + ir*nb10 + i2*nb11 + i3*nb12); device const float * dt = (device const float *) ((device const char *) src2 + ir*nb20 + i2*nb21 + i3*nb22); device const float * A = (device const float *) ((device const char *) src3 + ir*nb31); device const float * B = (device const float *) ((device const char *) src4 + i2*nb41 + i3*nb42); device const float * C = (device const float *) ((device const char *) src5 + i2*nb51 + i3*nb52); device float * y = (device float *) ((device char *) dst + ir*nb10 + i2*nb11 + i3*nb12); // TODO: do not use src1 strides device float * s = (device float *) ((device char *) dst + ir*nb01 + i3*nb02 + nb13); if (i2 > 0) { s0 = s; } // i1 == 0 float dt_soft_plus = dt[0] <= 20.0f ? log(1.0f + exp(dt[0])) : dt[0]; float x_dt = x[0] * dt_soft_plus; float sumf = 0.0f; for (int64_t i0 = 0; i0 < nc; ++i0) { int64_t i = i0; float state = (s0[i] * exp(dt_soft_plus * A[i])) + (B[i0] * x_dt); sumf += state * C[i0]; s[i] = state; } y[0] = sumf; } } kernel void kernel_norm( device const void * src0, device float * dst, constant int64_t & ne00, constant uint64_t & nb01, constant float & eps, threadgroup float * sum [[threadgroup(0)]], uint tgpig[[threadgroup_position_in_grid]], uint tpitg[[thread_position_in_threadgroup]], uint ntg[[threads_per_threadgroup]]) { device const float * x = (device const float *) ((device const char *) src0 + tgpig*nb01); // MEAN // parallel sum sum[tpitg] = 0.0f; for (int i00 = tpitg; i00 < ne00; i00 += ntg) { sum[tpitg] += x[i00]; } // reduce threadgroup_barrier(mem_flags::mem_threadgroup); for (uint i = ntg/2; i > 0; i /= 2) { if (tpitg < i) { sum[tpitg] += sum[tpitg + i]; } threadgroup_barrier(mem_flags::mem_threadgroup); } const float mean = sum[0] / ne00; // recenter and VARIANCE threadgroup_barrier(mem_flags::mem_threadgroup); device float * y = dst + tgpig*ne00; sum[tpitg] = 0.0f; for (int i00 = tpitg; i00 < ne00; i00 += ntg) { y[i00] = x[i00] - mean; sum[tpitg] += y[i00] * y[i00]; } // reduce threadgroup_barrier(mem_flags::mem_threadgroup); for (uint i = ntg/2; i > 0; i /= 2) { if (tpitg < i) { sum[tpitg] += sum[tpitg + i]; } threadgroup_barrier(mem_flags::mem_threadgroup); } const float variance = sum[0] / ne00; const float scale = 1.0f/sqrt(variance + eps); for (int i00 = tpitg; i00 < ne00; i00 += ntg) { y[i00] = y[i00] * scale; } } kernel void kernel_rms_norm( device const void * src0, device float * dst, constant int64_t & ne00, constant uint64_t & nb01, constant float & eps, threadgroup float * buf [[threadgroup(0)]], uint tgpig[[threadgroup_position_in_grid]], uint tpitg[[thread_position_in_threadgroup]], uint sgitg[[simdgroup_index_in_threadgroup]], uint tiisg[[thread_index_in_simdgroup]], uint ntg[[threads_per_threadgroup]]) { device const float4 * x = (device const float4 *) ((device const char *) src0 + tgpig*nb01); float4 sumf = 0; float all_sum = 0; // parallel sum for (int i00 = tpitg; i00 < ne00/4; i00 += ntg) { sumf += x[i00] * x[i00]; } all_sum = sumf[0] + sumf[1] + sumf[2] + sumf[3]; all_sum = simd_sum(all_sum); if (ntg > N_SIMDWIDTH) { if (sgitg == 0) { buf[tiisg] = 0.0f; } threadgroup_barrier(mem_flags::mem_threadgroup); if (tiisg == 0) { buf[sgitg] = all_sum; } threadgroup_barrier(mem_flags::mem_threadgroup); all_sum = buf[tiisg]; all_sum = simd_sum(all_sum); } const float mean = all_sum/ne00; const float scale = 1.0f/sqrt(mean + eps); device float4 * y = (device float4 *) (dst + tgpig*ne00); for (int i00 = tpitg; i00 < ne00/4; i00 += ntg) { y[i00] = x[i00] * scale; } } kernel void kernel_group_norm( device const float * src0, device float * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant int32_t & n_groups, constant float & eps, threadgroup float * buf [[threadgroup(0)]], uint tgpig[[threadgroup_position_in_grid]], uint tpitg[[thread_position_in_threadgroup]], uint sgitg[[simdgroup_index_in_threadgroup]], uint tiisg[[thread_index_in_simdgroup]], uint ntg[[threads_per_threadgroup]]) { const int64_t ne = ne00*ne01*ne02; const int64_t gs = ne00*ne01*((ne02 + n_groups - 1) / n_groups); int start = tgpig * gs; int end = start + gs; start += tpitg; if (end >= ne) { end = ne; } float tmp = 0.0f; // partial sum for thread in warp for (int j = start; j < end; j += ntg) { tmp += src0[j]; } threadgroup_barrier(mem_flags::mem_threadgroup); tmp = simd_sum(tmp); if (ntg > N_SIMDWIDTH) { if (sgitg == 0) { buf[tiisg] = 0.0f; } threadgroup_barrier(mem_flags::mem_threadgroup); if (tiisg == 0) { buf[sgitg] = tmp; } threadgroup_barrier(mem_flags::mem_threadgroup); tmp = buf[tiisg]; tmp = simd_sum(tmp); } const float mean = tmp / gs; tmp = 0.0f; for (int j = start; j < end; j += ntg) { float xi = src0[j] - mean; dst[j] = xi; tmp += xi * xi; } tmp = simd_sum(tmp); if (ntg > N_SIMDWIDTH) { if (sgitg == 0) { buf[tiisg] = 0.0f; } threadgroup_barrier(mem_flags::mem_threadgroup); if (tiisg == 0) { buf[sgitg] = tmp; } threadgroup_barrier(mem_flags::mem_threadgroup); tmp = buf[tiisg]; tmp = simd_sum(tmp); } const float variance = tmp / gs; const float scale = 1.0f/sqrt(variance + eps); for (int j = start; j < end; j += ntg) { dst[j] *= scale; } } // function for calculate inner product between half a q4_0 block and 16 floats (yl), sumy is SUM(yl[i]) // il indicates where the q4 quants begin (0 or QK4_0/4) // we assume that the yl's have been multiplied with the appropriate scale factor // that corresponds to the missing bit shifts (1, 1/16, 1/256, 1/4096) inline float block_q_n_dot_y(device const block_q4_0 * qb_curr, float sumy, thread float * yl, int il) { float d = qb_curr->d; float2 acc = 0.f; device const uint16_t * qs = ((device const uint16_t *)qb_curr + 1 + il/2); for (int i = 0; i < 8; i+=2) { acc[0] += yl[i + 0] * (qs[i / 2] & 0x000F) + yl[i + 1] * (qs[i / 2] & 0x0F00); acc[1] += yl[i + 8] * (qs[i / 2] & 0x00F0) + yl[i + 9] * (qs[i / 2] & 0xF000); } return d * (sumy * -8.f + acc[0] + acc[1]); } // function for calculate inner product between half a q4_1 block and 16 floats (yl), sumy is SUM(yl[i]) // il indicates where the q4 quants begin (0 or QK4_0/4) // we assume that the yl's have been multiplied with the appropriate scale factor // that corresponds to the missing bit shifts (1, 1/16, 1/256, 1/4096) inline float block_q_n_dot_y(device const block_q4_1 * qb_curr, float sumy, thread float * yl, int il) { float d = qb_curr->d; float m = qb_curr->m; float2 acc = 0.f; device const uint16_t * qs = ((device const uint16_t *)qb_curr + 2 + il/2); for (int i = 0; i < 8; i+=2) { acc[0] += yl[i + 0] * (qs[i / 2] & 0x000F) + yl[i + 1] * (qs[i / 2] & 0x0F00); acc[1] += yl[i + 8] * (qs[i / 2] & 0x00F0) + yl[i + 9] * (qs[i / 2] & 0xF000); } return d * (acc[0] + acc[1]) + sumy * m; } // function for calculate inner product between half a q5_0 block and 16 floats (yl), sumy is SUM(yl[i]) // il indicates where the q5 quants begin (0 or QK5_0/4) // we assume that the yl's have been multiplied with the appropriate scale factor // that corresponds to the missing bit shifts (1, 1/16, 1/256, 1/4096) inline float block_q_n_dot_y(device const block_q5_0 * qb_curr, float sumy, thread float * yl, int il) { float d = qb_curr->d; float2 acc = 0.f; device const uint16_t * qs = ((device const uint16_t *)qb_curr + 3 + il/2); const uint32_t qh = *((device const uint32_t *)qb_curr->qh); for (int i = 0; i < 8; i+=2) { acc[0] += yl[i + 0] * ((qs[i / 2] & 0x000F) | ((qh >> (i+0+il ) << 4 ) & 0x00010)) + yl[i + 1] * ((qs[i / 2] & 0x0F00) | ((qh >> (i+1+il ) << 12) & 0x01000)); acc[1] += yl[i + 8] * ((qs[i / 2] & 0x00F0) | ((qh >> (i+0+il+QK5_0/2) << 8 ) & 0x00100)) + yl[i + 9] * ((qs[i / 2] & 0xF000) | ((qh >> (i+1+il+QK5_0/2) << 16) & 0x10000)); } return d * (sumy * -16.f + acc[0] + acc[1]); } // function for calculate inner product between half a q5_1 block and 16 floats (yl), sumy is SUM(yl[i]) // il indicates where the q5 quants begin (0 or QK5_1/4) // we assume that the yl's have been multiplied with the appropriate scale factor // that corresponds to the missing bit shifts (1, 1/16, 1/256, 1/4096) inline float block_q_n_dot_y(device const block_q5_1 * qb_curr, float sumy, thread float * yl, int il) { float d = qb_curr->d; float m = qb_curr->m; float2 acc = 0.f; device const uint16_t * qs = ((device const uint16_t *)qb_curr + 4 + il/2); const uint32_t qh = *((device const uint32_t *)qb_curr->qh); for (int i = 0; i < 8; i+=2) { acc[0] += yl[i + 0] * ((qs[i / 2] & 0x000F) | ((qh >> (i+0+il ) << 4 ) & 0x00010)) + yl[i + 1] * ((qs[i / 2] & 0x0F00) | ((qh >> (i+1+il ) << 12) & 0x01000)); acc[1] += yl[i + 8] * ((qs[i / 2] & 0x00F0) | ((qh >> (i+0+il+QK5_0/2) << 8 ) & 0x00100)) + yl[i + 9] * ((qs[i / 2] & 0xF000) | ((qh >> (i+1+il+QK5_0/2) << 16) & 0x10000)); } return d * (acc[0] + acc[1]) + sumy * m; } // putting them in the kernel cause a significant performance penalty #define N_DST 4 // each SIMD group works on 4 rows #define N_SIMDGROUP 2 // number of SIMD groups in a thread group //Note: This is a template, but strictly speaking it only applies to // quantizations where the block size is 32. It also does not // guard against the number of rows not being divisible by // N_DST, so this is another explicit assumption of the implementation. template<typename block_q_type, int nr, int nsg, int nw> void mul_vec_q_n_f32_impl( device const void * src0, device const float * src1, device float * dst, int64_t ne00, int64_t ne01, int64_t ne02, int64_t ne10, int64_t ne12, int64_t ne0, int64_t ne1, uint r2, uint r3, threadgroup int8_t * shared_values, uint3 tgpig, uint tiisg, uint sgitg) { const int nb = ne00/QK4_0; const int r0 = tgpig.x; const int r1 = tgpig.y; const int im = tgpig.z; const int first_row = (r0 * nsg + sgitg) * nr; const uint i12 = im%ne12; const uint i13 = im/ne12; const uint offset0 = first_row * nb + (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02); device const block_q_type * x = (device const block_q_type *) src0 + offset0; device const float * y = (device const float *) src1 + r1*ne10 + im*ne00*ne1; float yl[16]; // src1 vector cache float sumf[nr] = {0.f}; const int ix = (tiisg/2); const int il = (tiisg%2)*8; device const float * yb = y + ix * QK4_0 + il; // each thread in a SIMD group deals with half a block. for (int ib = ix; ib < nb; ib += nw/2) { float sumy = 0; for (int i = 0; i < 8; i += 2) { sumy += yb[i] + yb[i+1]; yl[i+0] = yb[i+ 0]; yl[i+1] = yb[i+ 1]/256.f; sumy += yb[i+16] + yb[i+17]; yl[i+8] = yb[i+16]/16.f; yl[i+9] = yb[i+17]/4096.f; } for (int row = 0; row < nr; row++) { sumf[row] += block_q_n_dot_y(x+ib+row*nb, sumy, yl, il); } yb += QK4_0 * 16; } for (int row = 0; row < nr; ++row) { const float tot = simd_sum(sumf[row]); if (tiisg == 0 && first_row + row < ne01) { dst[im*ne0*ne1 + r1*ne0 + first_row + row] = tot; } } } kernel void kernel_mul_mv_q4_0_f32( device const void * src0, device const float * src1, device float * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant int64_t & ne0, constant int64_t & ne1, constant uint & r2, constant uint & r3, uint3 tgpig[[threadgroup_position_in_grid]], uint tiisg[[thread_index_in_simdgroup]], uint sgitg[[simdgroup_index_in_threadgroup]]) { mul_vec_q_n_f32_impl<block_q4_0, N_DST, N_SIMDGROUP, N_SIMDWIDTH>(src0,src1,dst,ne00,ne01,ne02,ne10,ne12,ne0,ne1,r2,r3,nullptr,tgpig,tiisg,sgitg); } kernel void kernel_mul_mv_q4_1_f32( device const void * src0, device const float * src1, device float * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant int64_t & ne0, constant int64_t & ne1, constant uint & r2, constant uint & r3, uint3 tgpig[[threadgroup_position_in_grid]], uint tiisg[[thread_index_in_simdgroup]], uint sgitg[[simdgroup_index_in_threadgroup]]) { mul_vec_q_n_f32_impl<block_q4_1, N_DST, N_SIMDGROUP, N_SIMDWIDTH>(src0,src1,dst,ne00,ne01,ne02,ne10,ne12,ne0,ne1,r2,r3,nullptr,tgpig,tiisg,sgitg); } kernel void kernel_mul_mv_q5_0_f32( device const void * src0, device const float * src1, device float * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant int64_t & ne0, constant int64_t & ne1, constant uint & r2, constant uint & r3, uint3 tgpig[[threadgroup_position_in_grid]], uint tiisg[[thread_index_in_simdgroup]], uint sgitg[[simdgroup_index_in_threadgroup]]) { mul_vec_q_n_f32_impl<block_q5_0, N_DST, N_SIMDGROUP, N_SIMDWIDTH>(src0,src1,dst,ne00,ne01,ne02,ne10,ne12,ne0,ne1,r2,r3,nullptr,tgpig,tiisg,sgitg); } kernel void kernel_mul_mv_q5_1_f32( device const void * src0, device const float * src1, device float * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant int64_t & ne0, constant int64_t & ne1, constant uint & r2, constant uint & r3, uint3 tgpig[[threadgroup_position_in_grid]], uint tiisg[[thread_index_in_simdgroup]], uint sgitg[[simdgroup_index_in_threadgroup]]) { mul_vec_q_n_f32_impl<block_q5_1, N_DST, N_SIMDGROUP, N_SIMDWIDTH>(src0,src1,dst,ne00,ne01,ne02,ne10,ne12,ne0,ne1,r2,r3,nullptr,tgpig,tiisg,sgitg); } #define NB_Q8_0 8 void kernel_mul_mv_q8_0_f32_impl( device const void * src0, device const float * src1, device float * dst, int64_t ne00, int64_t ne01, int64_t ne02, int64_t ne10, int64_t ne12, int64_t ne0, int64_t ne1, uint r2, uint r3, threadgroup int8_t * shared_values, uint3 tgpig, uint tiisg, uint sgitg) { const int nr = N_DST; const int nsg = N_SIMDGROUP; const int nw = N_SIMDWIDTH; const int nb = ne00/QK8_0; const int r0 = tgpig.x; const int r1 = tgpig.y; const int im = tgpig.z; const int first_row = (r0 * nsg + sgitg) * nr; const uint i12 = im%ne12; const uint i13 = im/ne12; const uint offset0 = first_row * nb + (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02); device const block_q8_0 * x = (device const block_q8_0 *) src0 + offset0; device const float * y = (device const float *) src1 + r1*ne10 + im*ne00*ne1; float yl[NB_Q8_0]; float sumf[nr]={0.f}; const int ix = tiisg/4; const int il = tiisg%4; device const float * yb = y + ix * QK8_0 + NB_Q8_0*il; // each thread in a SIMD group deals with NB_Q8_0 quants at a time for (int ib = ix; ib < nb; ib += nw/4) { for (int i = 0; i < NB_Q8_0; ++i) { yl[i] = yb[i]; } for (int row = 0; row < nr; row++) { device const int8_t * qs = x[ib+row*nb].qs + NB_Q8_0*il; float sumq = 0.f; for (int iq = 0; iq < NB_Q8_0; ++iq) { sumq += qs[iq] * yl[iq]; } sumf[row] += sumq*x[ib+row*nb].d; } yb += NB_Q8_0 * nw; } for (int row = 0; row < nr; ++row) { const float tot = simd_sum(sumf[row]); if (tiisg == 0 && first_row + row < ne01) { dst[r1*ne0 + im*ne0*ne1 + first_row + row] = tot; } } } [[host_name("kernel_mul_mv_q8_0_f32")]] kernel void kernel_mul_mv_q8_0_f32( device const void * src0, device const float * src1, device float * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant int64_t & ne0, constant int64_t & ne1, constant uint & r2, constant uint & r3, uint3 tgpig[[threadgroup_position_in_grid]], uint tiisg[[thread_index_in_simdgroup]], uint sgitg[[simdgroup_index_in_threadgroup]]) { kernel_mul_mv_q8_0_f32_impl(src0,src1,dst,ne00,ne01,ne02,ne10,ne12,ne0,ne1,r2,r3,nullptr,tgpig,tiisg,sgitg); } #define N_MV_T_T 4 template<typename T0, typename T04, typename T1, typename T14> void kernel_mul_mv_impl( device const char * src0, device const char * src1, device float * dst, int64_t ne00, int64_t ne01, int64_t ne02, uint64_t nb00, uint64_t nb01, uint64_t nb02, int64_t ne10, int64_t ne11, int64_t ne12, uint64_t nb10, uint64_t nb11, uint64_t nb12, int64_t ne0, int64_t ne1, uint r2, uint r3, uint3 tgpig, uint tiisg) { const int64_t r0 = tgpig.x; const int64_t rb = tgpig.y*N_MV_T_T; const int64_t im = tgpig.z; const uint i12 = im%ne12; const uint i13 = im/ne12; const uint offset0 = r0*nb01 + (i12/r2)*nb02 + (i13/r3)*nb02*ne02; device const T0 * x = (device const T0 *) (src0 + offset0); if (ne00 < 128) { for (int row = 0; row < N_MV_T_T; ++row) { int r1 = rb + row; if (r1 >= ne11) { break; } device const T1 * y = (device const T1 *) (src1 + r1*nb11 + im*nb12); float sumf = 0; for (int i = tiisg; i < ne00; i += 32) { sumf += (T0) x[i] * (T1) y[i]; } float all_sum = simd_sum(sumf); if (tiisg == 0) { dst[im*ne1*ne0 + r1*ne0 + r0] = all_sum; } } } else { device const T04 * x4 = (device const T04 *) x; for (int row = 0; row < N_MV_T_T; ++row) { int r1 = rb + row; if (r1 >= ne11) { break; } device const T1 * y = (device const T1 *) (src1 + r1*nb11 + im*nb12); device const T14 * y4 = (device const T14 *) y; float sumf = 0; for (int i = tiisg; i < ne00/4; i += 32) { for (int k = 0; k < 4; ++k) sumf += (float) (x4[i][k] * y4[i][k]); } float all_sum = simd_sum(sumf); if (tiisg == 0) { for (int i = 4*(ne00/4); i < ne00; ++i) all_sum += (float) (x[i] * y[i]); dst[im*ne1*ne0 + r1*ne0 + r0] = all_sum; } } } } template<typename T0, typename T04, typename T1, typename T14> kernel void kernel_mul_mv( device const char * src0, device const char * src1, device float * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant int64_t & ne0, constant int64_t & ne1, constant uint & r2, constant uint & r3, uint3 tgpig[[threadgroup_position_in_grid]], uint tiisg[[thread_index_in_simdgroup]]) { kernel_mul_mv_impl<T0, T04, T1, T14>( src0, src1, dst, ne00, ne01, ne02, nb00, nb01, nb02, ne10, ne11, ne12, nb10, nb11, nb12, ne0, ne1, r2, r3, tgpig, tiisg); } typedef decltype(kernel_mul_mv<half, half4, half, half4>) mul_mv_t; template [[host_name("kernel_mul_mv_f32_f32")]] kernel mul_mv_t kernel_mul_mv<float, float4, float, float4>; template [[host_name("kernel_mul_mv_f16_f32")]] kernel mul_mv_t kernel_mul_mv<half, half4, float, float4>; template [[host_name("kernel_mul_mv_f16_f16")]] kernel mul_mv_t kernel_mul_mv<half, half4, half, half4>; template<typename T, typename T4> kernel void kernel_mul_mv_1row( device const char * src0, device const char * src1, device float * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant int64_t & ne0, constant int64_t & ne1, constant uint & r2, constant uint & r3, uint3 tgpig[[threadgroup_position_in_grid]], uint tiisg[[thread_index_in_simdgroup]]) { const int64_t r0 = tgpig.x; const int64_t r1 = tgpig.y; const int64_t im = tgpig.z; const uint i12 = im%ne12; const uint i13 = im/ne12; const uint offset0 = r0*nb01 + (i12/r2)*nb02 + (i13/r3)*nb02*ne02; device const T * x = (device const T *) (src0 + offset0); device const float * y = (device const float *) (src1 + r1*nb11 + im*nb12); float sumf = 0; if (ne00 < 128) { for (int i = tiisg; i < ne00; i += 32) { sumf += (float) x[i] * (float) y[i]; } float all_sum = simd_sum(sumf); if (tiisg == 0) { dst[im*ne1*ne0 + r1*ne0 + r0] = all_sum; } } else { device const T4 * x4 = (device const T4 *) x; device const float4 * y4 = (device const float4 *) y; for (int i = tiisg; i < ne00/4; i += 32) { for (int k = 0; k < 4; ++k) sumf += (float) (x4[i][k] * y4[i][k]); } float all_sum = simd_sum(sumf); if (tiisg == 0) { for (int i = 4*(ne00/4); i < ne00; ++i) all_sum += (float) (x[i] * y[i]); dst[im*ne1*ne0 + r1*ne0 + r0] = all_sum; } } } typedef decltype(kernel_mul_mv_1row<half, half4>) mul_mv_1row_t; template [[host_name("kernel_mul_mv_f16_f32_1row")]] kernel mul_mv_1row_t kernel_mul_mv_1row<half, half4>; // Assumes row size (ne00) is a multiple of 4 template<typename T, typename T4> kernel void kernel_mul_mv_l4( device const char * src0, device const char * src1, device float * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant int64_t & ne0, constant int64_t & ne1, constant uint & r2, constant uint & r3, uint3 tgpig[[threadgroup_position_in_grid]], uint tiisg[[thread_index_in_simdgroup]]) { const int nrows = ne11; const int64_t r0 = tgpig.x; const int64_t im = tgpig.z; const uint i12 = im%ne12; const uint i13 = im/ne12; const uint offset0 = r0*nb01 + (i12/r2)*nb02 + (i13/r3)*nb02*ne02; device const T4 * x4 = (device const T4 *) (src0 + offset0); for (int r1 = 0; r1 < nrows; ++r1) { device const float4 * y4 = (device const float4 *) (src1 + r1*nb11 + im*nb12); float sumf = 0; for (int i = tiisg; i < ne00/4; i += 32) { for (int k = 0; k < 4; ++k) sumf += (float) (x4[i][k] * y4[i][k]); } float all_sum = simd_sum(sumf); if (tiisg == 0) { dst[im*ne1*ne0 + r1*ne0 + r0] = all_sum; } } } typedef decltype(kernel_mul_mv_l4<half, half4>) mul_mv_l4_t; template [[host_name("kernel_mul_mv_f16_f32_l4")]] kernel mul_mv_l4_t kernel_mul_mv_l4<half, half4>; static float rope_yarn_ramp(const float low, const float high, const int i0) { const float y = (i0 / 2 - low) / max(0.001f, high - low); return 1.0f - min(1.0f, max(0.0f, y)); } // YaRN algorithm based on LlamaYaRNScaledRotaryEmbedding.py from https://github.com/jquesnelle/yarn // MIT licensed. Copyright (c) 2023 Jeffrey Quesnelle and Bowen Peng. static void rope_yarn( float theta_extrap, float freq_scale, float corr_dims[2], int64_t i0, float ext_factor, float mscale, thread float * cos_theta, thread float * sin_theta) { // Get n-d rotational scaling corrected for extrapolation float theta_interp = freq_scale * theta_extrap; float theta = theta_interp; if (ext_factor != 0.0f) { float ramp_mix = rope_yarn_ramp(corr_dims[0], corr_dims[1], i0) * ext_factor; theta = theta_interp * (1 - ramp_mix) + theta_extrap * ramp_mix; // Get n-d magnitude scaling corrected for interpolation mscale *= 1.0f + 0.1f * log(1.0f / freq_scale); } *cos_theta = cos(theta) * mscale; *sin_theta = sin(theta) * mscale; } // Apparently solving `n_rot = 2pi * x * base^((2 * max_pos_emb) / n_dims)` for x, we get // `corr_fac(n_rot) = n_dims * log(max_pos_emb / (n_rot * 2pi)) / (2 * log(base))` static float rope_yarn_corr_factor(int n_dims, int n_ctx_orig, float n_rot, float base) { return n_dims * log(n_ctx_orig / (n_rot * 2 * M_PI_F)) / (2 * log(base)); } static void rope_yarn_corr_dims( int n_dims, int n_ctx_orig, float freq_base, float beta_fast, float beta_slow, float dims[2] ) { // start and end correction dims dims[0] = max(0.0f, floor(rope_yarn_corr_factor(n_dims, n_ctx_orig, beta_fast, freq_base))); dims[1] = min(n_dims - 1.0f, ceil(rope_yarn_corr_factor(n_dims, n_ctx_orig, beta_slow, freq_base))); } template<typename T> kernel void kernel_rope_norm( device const void * src0, device const int32_t * src1, device const float * src2, device float * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant int64_t & ne03, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant uint64_t & nb03, constant int64_t & ne0, constant int64_t & ne1, constant int64_t & ne2, constant int64_t & ne3, constant uint64_t & nb0, constant uint64_t & nb1, constant uint64_t & nb2, constant uint64_t & nb3, constant int & n_past, constant int & n_dims, constant int & n_ctx_orig, constant float & freq_base, constant float & freq_scale, constant float & ext_factor, constant float & attn_factor, constant float & beta_fast, constant float & beta_slow, uint tiitg[[thread_index_in_threadgroup]], uint3 tptg[[threads_per_threadgroup]], uint3 tgpig[[threadgroup_position_in_grid]]) { const int64_t i3 = tgpig[2]; const int64_t i2 = tgpig[1]; const int64_t i1 = tgpig[0]; float corr_dims[2]; rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims); device const int32_t * pos = src1; const float theta_base = (float) pos[i2]; const float inv_ndims = -1.f/n_dims; float cos_theta; float sin_theta; for (int64_t i0 = 2*tiitg; i0 < ne0; i0 += 2*tptg.x) { if (i0 < n_dims) { const int64_t ic = i0/2; const float theta = theta_base * pow(freq_base, inv_ndims*i0); const float freq_factor = src2 != src0 ? src2[ic] : 1.0f; rope_yarn(theta/freq_factor, freq_scale, corr_dims, i0, ext_factor, attn_factor, &cos_theta, &sin_theta); device const T * const src = (device T *)((device char *) src0 + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00); device T * dst_data = (device T *)((device char *) dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0); const float x0 = src[0]; const float x1 = src[1]; dst_data[0] = x0*cos_theta - x1*sin_theta; dst_data[1] = x0*sin_theta + x1*cos_theta; } else { device const T * const src = (device T *)((device char *) src0 + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00); device T * dst_data = (device T *)((device char *) dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0); dst_data[0] = src[0]; dst_data[1] = src[1]; } } } template<typename T> kernel void kernel_rope_neox( device const void * src0, device const int32_t * src1, device const float * src2, device float * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant int64_t & ne03, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant uint64_t & nb03, constant int64_t & ne0, constant int64_t & ne1, constant int64_t & ne2, constant int64_t & ne3, constant uint64_t & nb0, constant uint64_t & nb1, constant uint64_t & nb2, constant uint64_t & nb3, constant int & n_past, constant int & n_dims, constant int & n_ctx_orig, constant float & freq_base, constant float & freq_scale, constant float & ext_factor, constant float & attn_factor, constant float & beta_fast, constant float & beta_slow, uint tiitg[[thread_index_in_threadgroup]], uint3 tptg[[threads_per_threadgroup]], uint3 tgpig[[threadgroup_position_in_grid]]) { const int64_t i3 = tgpig[2]; const int64_t i2 = tgpig[1]; const int64_t i1 = tgpig[0]; float corr_dims[2]; rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims); device const int32_t * pos = src1; const float theta_base = (float) pos[i2]; const float inv_ndims = -1.f/n_dims; float cos_theta; float sin_theta; for (int64_t i0 = 2*tiitg; i0 < ne0; i0 += 2*tptg.x) { if (i0 < n_dims) { const int64_t ic = i0/2; const float theta = theta_base * pow(freq_base, inv_ndims*i0); const float freq_factor = src2 != src0 ? src2[ic] : 1.0f; rope_yarn(theta/freq_factor, freq_scale, corr_dims, i0, ext_factor, attn_factor, &cos_theta, &sin_theta); device const T * const src = (device T *)((device char *) src0 + i3*nb03 + i2*nb02 + i1*nb01 + ic*nb00); device T * dst_data = (device T *)((device char *) dst + i3*nb3 + i2*nb2 + i1*nb1 + ic*nb0); const float x0 = src[0]; const float x1 = src[n_dims/2]; dst_data[0] = x0*cos_theta - x1*sin_theta; dst_data[n_dims/2] = x0*sin_theta + x1*cos_theta; } else { device const T * const src = (device T *)((device char *) src0 + i3*nb03 + i2*nb02 + i1*nb01 + i0*nb00); device T * dst_data = (device T *)((device char *) dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0); dst_data[0] = src[0]; dst_data[1] = src[1]; } } } typedef decltype(kernel_rope_norm<float>) kernel_rope_norm_t; typedef decltype(kernel_rope_neox<float>) kernel_rope_neox_t; template [[host_name("kernel_rope_norm_f32")]] kernel kernel_rope_norm_t kernel_rope_norm<float>; template [[host_name("kernel_rope_norm_f16")]] kernel kernel_rope_norm_t kernel_rope_norm<half>; template [[host_name("kernel_rope_neox_f32")]] kernel kernel_rope_neox_t kernel_rope_neox<float>; template [[host_name("kernel_rope_neox_f16")]] kernel kernel_rope_neox_t kernel_rope_neox<half>; typedef void (im2col_t)( device const float * x, device char * dst, constant int32_t & ofs0, constant int32_t & ofs1, constant int32_t & IW, constant int32_t & IH, constant int32_t & CHW, constant int32_t & s0, constant int32_t & s1, constant int32_t & p0, constant int32_t & p1, constant int32_t & d0, constant int32_t & d1, uint3 tgpig[[threadgroup_position_in_grid]], uint3 tgpg[[threadgroups_per_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg[[threads_per_threadgroup]]); template <typename T> kernel void kernel_im2col( device const float * x, device char * dst, constant int32_t & ofs0, constant int32_t & ofs1, constant int32_t & IW, constant int32_t & IH, constant int32_t & CHW, constant int32_t & s0, constant int32_t & s1, constant int32_t & p0, constant int32_t & p1, constant int32_t & d0, constant int32_t & d1, uint3 tgpig[[threadgroup_position_in_grid]], uint3 tgpg[[threadgroups_per_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg[[threads_per_threadgroup]]) { const int32_t iiw = tgpig[2] * s0 + tpitg[2] * d0 - p0; const int32_t iih = tgpig[1] * s1 + tpitg[1] * d1 - p1; const int32_t offset_dst = (tpitg[0] * tgpg[1] * tgpg[2] + tgpig[1] * tgpg[2] + tgpig[2]) * CHW + (tgpig[0] * (ntg[1] * ntg[2]) + tpitg[1] * ntg[2] + tpitg[2]); device T * pdst = (device T *) (dst); if (iih < 0 || iih >= IH || iiw < 0 || iiw >= IW) { pdst[offset_dst] = 0.0f; } else { const int32_t offset_src = tpitg[0] * ofs0 + tgpig[0] * ofs1; pdst[offset_dst] = x[offset_src + iih * IW + iiw]; } } template [[host_name("kernel_im2col_f32")]] kernel im2col_t kernel_im2col<float>; template [[host_name("kernel_im2col_f16")]] kernel im2col_t kernel_im2col<half>; typedef void (im2col_ext_t)( device const float * x, device char * dst, constant int32_t & ofs0, constant int32_t & ofs1, constant int32_t & IW, constant int32_t & IH, constant int32_t & CHW, constant int32_t & s0, constant int32_t & s1, constant int32_t & p0, constant int32_t & p1, constant int32_t & d0, constant int32_t & d1, constant int32_t & N, constant int32_t & KH, constant int32_t & KW, uint3 tgpig[[threadgroup_position_in_grid]], uint3 tgpg[[threadgroups_per_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg[[threads_per_threadgroup]]); template <typename T> kernel void kernel_im2col_ext( device const float * x, device char * dst, constant int32_t & ofs0, constant int32_t & ofs1, constant int32_t & IW, constant int32_t & IH, constant int32_t & CHW, constant int32_t & s0, constant int32_t & s1, constant int32_t & p0, constant int32_t & p1, constant int32_t & d0, constant int32_t & d1, constant int32_t & N, constant int32_t & KH, constant int32_t & KW, uint3 tgpig[[threadgroup_position_in_grid]], uint3 tgpg[[threadgroups_per_grid]], // tgpg[0] = D x IC x KH x KW, CHW = IC x KH x KW uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg[[threads_per_threadgroup]]) { // [M, 1, 1] const int32_t KHW = KH * KW; // KHW == ntg[1] * ntg[2], KW == ntg[2] const int32_t d = tgpig[0] / CHW; const int32_t chw = tgpig[0] % CHW; const int32_t tgpig_0 = chw / KHW; // 0 ~ (IC - 1) const int32_t HW = tgpig[0] % KHW; const int32_t tpitg_0 = (d * ntg[0]) + tpitg[0]; if (tpitg_0 >= N) { return; } const int32_t tpitg_1 = HW / KW; const int32_t tpitg_2 = HW % KW; const int32_t iiw = tgpig[2] * s0 + tpitg_2 * d0 - p0; const int32_t iih = tgpig[1] * s1 + tpitg_1 * d1 - p1; const int32_t offset_dst = (tpitg_0 * tgpg[1] * tgpg[2] + tgpig[1] * tgpg[2] + tgpig[2]) * CHW + (tgpig_0 * KHW + tpitg_1 * KW + tpitg_2); device T * pdst = (device T *) (dst); if (iih < 0 || iih >= IH || iiw < 0 || iiw >= IW) { pdst[offset_dst] = 0.0f; } else { const int32_t offset_src = tpitg_0 * ofs0 + tgpig_0 * ofs1; pdst[offset_dst] = x[offset_src + iih * IW + iiw]; } } template [[host_name("kernel_im2col_ext_f32")]] kernel im2col_ext_t kernel_im2col_ext<float>; template [[host_name("kernel_im2col_ext_f16")]] kernel im2col_ext_t kernel_im2col_ext<half>; kernel void kernel_upscale_f32( device const char * src0, device char * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant int64_t & ne03, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant uint64_t & nb03, constant int64_t & ne0, constant int64_t & ne1, constant int64_t & ne2, constant int64_t & ne3, constant uint64_t & nb0, constant uint64_t & nb1, constant uint64_t & nb2, constant uint64_t & nb3, constant float & sf0, constant float & sf1, constant float & sf2, constant float & sf3, uint3 tgpig[[threadgroup_position_in_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg[[threads_per_threadgroup]]) { const int64_t i3 = tgpig.z; const int64_t i2 = tgpig.y; const int64_t i1 = tgpig.x; const int64_t i03 = i3/sf3; const int64_t i02 = i2/sf2; const int64_t i01 = i1/sf1; for (int i0 = tpitg.x; i0 < ne0; i0 += ntg.x) { const int64_t i00 = i0/sf0; device const float * src0_ptr = (device const float *) (src0 + i03*nb03 + i02*nb02 + i01*nb01 + i00*nb00); device float * dst_ptr = (device float *) (dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0); dst_ptr[0] = src0_ptr[0]; } } kernel void kernel_pad_f32( device const char * src0, device char * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant int64_t & ne03, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant uint64_t & nb03, constant int64_t & ne0, constant int64_t & ne1, constant int64_t & ne2, constant int64_t & ne3, constant uint64_t & nb0, constant uint64_t & nb1, constant uint64_t & nb2, constant uint64_t & nb3, uint3 tgpig[[threadgroup_position_in_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg[[threads_per_threadgroup]]) { const int64_t i3 = tgpig.z; const int64_t i2 = tgpig.y; const int64_t i1 = tgpig.x; const int64_t i03 = i3; const int64_t i02 = i2; const int64_t i01 = i1; device const float * src0_ptr = (device const float *) (src0 + i03*nb03 + i02*nb02 + i01*nb01); device float * dst_ptr = (device float *) (dst + i3*nb3 + i2*nb2 + i1*nb1); if (i1 < ne01 && i2 < ne02 && i3 < ne03) { for (int i0 = tpitg.x; i0 < ne0; i0 += ntg.x) { if (i0 < ne00) { dst_ptr[i0] = src0_ptr[i0]; } else { dst_ptr[i0] = 0.0f; } } return; } for (int i0 = tpitg.x; i0 < ne0; i0 += ntg.x) { dst_ptr[i0] = 0.0f; } } kernel void kernel_arange_f32( device char * dst, constant int64_t & ne0, constant float & start, constant float & step, uint3 tgpig[[threadgroup_position_in_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg[[threads_per_threadgroup]]) { device float * dst_ptr = (device float *) dst; for (int i0 = tpitg.x; i0 < ne0; i0 += ntg.x) { dst_ptr[i0] = start + step * i0; } } kernel void kernel_timestep_embedding_f32( device const char * src0, device char * dst, constant uint64_t & nb1, constant int & dim, constant int & max_period, uint3 tgpig[[threadgroup_position_in_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg[[threads_per_threadgroup]]) { int i = tgpig.x; device float * embed_data = (device float *)(dst + i*nb1); int half_ = dim / 2; for (int j = tpitg.x; j < half_; j += ntg.x) { float timestep = ((device float *)src0)[i]; float freq = (float)exp(-log((float)max_period) * j / half_); float arg = timestep * freq; embed_data[j ] = cos(arg); embed_data[j + half_] = sin(arg); } if (dim % 2 != 0 && tpitg.x == 0) { embed_data[dim] = 0.f; } } // bitonic sort implementation following the CUDA kernels as reference typedef void (argsort_t)( device const float * x, device int32_t * dst, constant int64_t & ncols, constant int64_t & ncols_pad, threadgroup int32_t * shared_values [[threadgroup(0)]], uint3 tgpig[[threadgroup_position_in_grid]], uint3 tpitg[[thread_position_in_threadgroup]]); template<ggml_sort_order order> kernel void kernel_argsort_f32_i32( device const float * x, device int32_t * dst, constant int64_t & ncols, constant int64_t & ncols_pad, threadgroup int32_t * shared_values [[threadgroup(0)]], uint3 tgpig[[threadgroup_position_in_grid]], uint3 tpitg[[thread_position_in_threadgroup]]) { // bitonic sort int col = tpitg[0]; int row = tgpig[1]; if (col >= ncols_pad) return; device const float * x_row = x + row * ncols; threadgroup int32_t * dst_row = shared_values; // initialize indices dst_row[col] = col; threadgroup_barrier(mem_flags::mem_threadgroup); for (int k = 2; k <= ncols_pad; k *= 2) { for (int j = k / 2; j > 0; j /= 2) { int ixj = col ^ j; if (ixj > col) { if ((col & k) == 0) { if (dst_row[col] >= ncols || (dst_row[ixj] < ncols && (order == GGML_SORT_ORDER_ASC ? x_row[dst_row[col]] > x_row[dst_row[ixj]] : x_row[dst_row[col]] < x_row[dst_row[ixj]])) ) { SWAP(dst_row[col], dst_row[ixj]); } } else { if (dst_row[ixj] >= ncols || (dst_row[col] < ncols && (order == GGML_SORT_ORDER_ASC ? x_row[dst_row[col]] < x_row[dst_row[ixj]] : x_row[dst_row[col]] > x_row[dst_row[ixj]])) ) { SWAP(dst_row[col], dst_row[ixj]); } } } threadgroup_barrier(mem_flags::mem_threadgroup); } } // copy the result to dst without the padding if (col < ncols) { dst[row * ncols + col] = dst_row[col]; } } template [[host_name("kernel_argsort_f32_i32_asc")]] kernel argsort_t kernel_argsort_f32_i32<GGML_SORT_ORDER_ASC>; template [[host_name("kernel_argsort_f32_i32_desc")]] kernel argsort_t kernel_argsort_f32_i32<GGML_SORT_ORDER_DESC>; kernel void kernel_leaky_relu_f32( device const float * src0, device float * dst, constant float & slope, uint tpig[[thread_position_in_grid]]) { dst[tpig] = src0[tpig] > 0.0f ? src0[tpig] : src0[tpig] * slope; } typedef void (flash_attn_ext_f16_t)( device const char * q, device const char * k, device const char * v, device const char * mask, device float * dst, constant int64_t & ne01, constant int64_t & ne02, constant int64_t & ne03, constant uint64_t & nb01, constant uint64_t & nb02, constant uint64_t & nb03, constant int64_t & ne11, constant int64_t & ne12, constant int64_t & ne13, constant uint64_t & nb11, constant uint64_t & nb12, constant uint64_t & nb13, constant uint64_t & nb21, constant uint64_t & nb22, constant uint64_t & nb23, constant uint64_t & nb31, constant int64_t & ne1, constant int64_t & ne2, constant float & scale, constant float & max_bias, constant float & m0, constant float & m1, constant uint32_t & n_head_log2, constant float & logit_softcap, threadgroup half * shared, uint3 tgpig[[threadgroup_position_in_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg[[threads_per_threadgroup]], ushort tiisg[[thread_index_in_simdgroup]], ushort sgitg[[simdgroup_index_in_threadgroup]]); // ref: https://arxiv.org/pdf/2307.08691.pdf template<int64_t D, int64_t Q = 8, int64_t C = 32> // head size, queries per threadgroup, cache items per threadgroup kernel void kernel_flash_attn_ext_f16( device const char * q, device const char * k, device const char * v, device const char * mask, device float * dst, constant int64_t & ne01, constant int64_t & ne02, constant int64_t & ne03, constant uint64_t & nb01, constant uint64_t & nb02, constant uint64_t & nb03, constant int64_t & ne11, constant int64_t & ne12, constant int64_t & ne13, constant uint64_t & nb11, constant uint64_t & nb12, constant uint64_t & nb13, constant uint64_t & nb21, constant uint64_t & nb22, constant uint64_t & nb23, constant uint64_t & nb31, constant int64_t & ne1, constant int64_t & ne2, constant float & scale, constant float & max_bias, constant float & m0, constant float & m1, constant uint32_t & n_head_log2, constant float & logit_softcap, threadgroup half * shared [[threadgroup(0)]], uint3 tgpig[[threadgroup_position_in_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg[[threads_per_threadgroup]], ushort tiisg[[thread_index_in_simdgroup]], ushort sgitg[[simdgroup_index_in_threadgroup]]) { const short nsg = ntg.y; // number of simdgroups const short iq3 = tgpig[2]; const short iq2 = tgpig[1]; const short iq1 = tgpig[0]*Q; const short D4 = D/4; const short D8 = D/8; //const short Q8 = Q/8; const short NW = N_SIMDWIDTH; const short SH = (C + Q); // shared memory per simdgroup in (half) const short T = D + 2*nsg*SH; // shared memory size per query in (half) const short TF = T/2; // shared memory size per query in (float) const short T4 = T/4; // shared memory size per query in (half4) threadgroup half * sq = (threadgroup half *) (shared + 0*D); // holds the query data threadgroup half4 * sq4 = (threadgroup half4 *) (shared + 0*D); // same as above but in half4 threadgroup float * ss = (threadgroup float *) (shared + 2*sgitg*SH + 1*D); // scratch buffer for attention and diagonal matrix // store the result for all queries in local memory in 8x8 matrices (the O matrix from the paper) simdgroup_half8x8 lo[D8]; // load heads from Q to shared memory for (short j = sgitg; j < Q; j += nsg) { device const float4 * q4 = (device const float4 *) ((device const char *) q + ((iq1 + j)*nb01 + iq2*nb02 + iq3*nb03)); for (short i = tiisg; i < D4; i += NW) { if (iq1 + j < ne01) { sq4[j*T4 + i] = (half4) q4[i]; } else { sq4[j*T4 + i] = 0.0h; } } } // zero out lo for (short i = 0; i < D8; ++i) { lo[i] = make_filled_simdgroup_matrix<half, 8>(0.0h); } // zero out shared memory SH for (short j = 0; j < Q; ++j) { for (short i = tiisg; i < SH; i += NW) { ss[j*TF + i] = 0.0f; } } threadgroup_barrier(mem_flags::mem_threadgroup); { float S[Q] = { [0 ... Q-1] = 0.0h }; float M[Q] = { [0 ... Q-1] = -FLT_MAX/2 }; // assume K and V are same shape const short ne22 = ne12; const short ne23 = ne13; // broadcast const short rk2 = ne02/ne12; const short rk3 = ne03/ne13; const short rv2 = ne02/ne22; const short rv3 = ne03/ne23; // k indices const short ik2 = iq2/rk2; const short ik3 = iq3/rk3; // v indices const short iv2 = iq2/rv2; const short iv3 = iq3/rv3; // load the queries from shared memory into local memory simdgroup_half8x8 mq[D8]; for (short i = 0; i < D8; ++i) { simdgroup_load(mq[i], sq + i*8, T); } // pointer to the mask device const half * mp = (device const half *) (mask + iq1*nb31); float slope = 1.0f; // ALiBi if (max_bias > 0.0f) { const uint32_t h = iq2; const float base = h < n_head_log2 ? m0 : m1; const int exph = h < n_head_log2 ? h + 1 : 2*(h - n_head_log2) + 1; slope = pow(base, exph); } // loop over the KV cache // each simdgroup handles blocks of Q rows and C columns for (int ic0 = 0; ic0 < ne11; ic0 += C*nsg) { const int ic = ic0 + C*sgitg; if (ic >= ne11) { break; } // Q*K^T { for (short cc = 0; cc < C/8; ++cc) { simdgroup_float8x8 mqk = make_filled_simdgroup_matrix<float, 8>(0.h); device const half * pk = (device const half *) ((device const char *) k + ((ic + 8*cc)*nb11 + ik2*nb12 + ik3*nb13)); for (short i = 0; i < D8; ++i) { simdgroup_half8x8 mk; simdgroup_load(mk, pk + i*8, nb11/sizeof(half), 0, true); // transpose simdgroup_multiply_accumulate(mqk, mq[i], mk, mqk); } simdgroup_store(mqk, ss + 8*cc, TF, 0, false); } } // used to detect blocks full of -INF float smax = -INFINITY; // online softmax { float ms[Q]; for (short j = 0; j < Q; ++j) { const float m = M[j]; // scale and apply the logitcap / mask float s = ss[j*TF + tiisg]*scale; if (logit_softcap != 0.0f) { s = logit_softcap*precise::tanh(s); } if (mask != q) { // mqk = mqk + mask*slope s += slope*mp[ic + j*nb31/sizeof(half) + tiisg]; } smax = simd_max(max(smax, s)); M[j] = simd_max(max(M[j], s)); ms[j] = exp(m - M[j]); const float vs = exp(s - M[j]); S[j] = S[j]*ms[j] + simd_sum(vs); // the P matrix from the paper (Q rows, C columns) ss[j*TF + tiisg] = vs; } // create a QxQ diagonal matrix for rescaling the output if (tiisg < Q) { ss[tiisg*TF + C + tiisg] = ms[tiisg]; } } // skip -INF blocks if (smax == -INFINITY) { continue; } // O = diag(ms)*O { simdgroup_float8x8 mm; simdgroup_load(mm, ss + C, TF, 0, false); for (short i = 0; i < D8; ++i) { simdgroup_multiply(lo[i], mm, lo[i]); } } // O = O + (Q*K^T)*V { for (short cc = 0; cc < C/8; ++cc) { device const half * pv = (device const half *) ((device const char *) v + ((ic + 8*cc)*nb21 + iv2*nb22 + iv3*nb23)); for (short i = 0; i < D8; ++i) { simdgroup_half8x8 mk; simdgroup_load(mk, pv + i*8, nb21/sizeof(half), 0, false); simdgroup_float8x8 mv; simdgroup_load(mv, ss + 8*cc, TF, 0, false); simdgroup_multiply_accumulate(lo[i], mv, mk, lo[i]); } } } } // these are needed for reducing the results from the simdgroups (reuse the ss buffer) for (short j = 0; j < Q; ++j) { if (tiisg == 0) { ss[j*TF + 0] = S[j]; ss[j*TF + 1] = M[j]; } } } // reduce the warps sequentially for (short sg = 1; sg < nsg; ++sg) { float S = { 0.0h }; float M = { -FLT_MAX/2 }; threadgroup_barrier(mem_flags::mem_threadgroup); // each simdgroup stores its output to shared memory, reusing sq if (sgitg == sg) { for (short i = 0; i < D8; ++i) { simdgroup_store(lo[i], sq + i*8, T, 0, false); } } threadgroup_barrier(mem_flags::mem_threadgroup); // the first simdgroup accumulates the results from the other simdgroups if (sgitg == 0) { for (short j = 0; j < Q; ++j) { const float S0 = ss[j*TF + 0]; const float S1 = ss[j*TF + sg*SH + 0]; const float M0 = ss[j*TF + 1]; const float M1 = ss[j*TF + sg*SH + 1]; M = max(M0, M1); const float ms0 = exp(M0 - M); const float ms1 = exp(M1 - M); S = S0*ms0 + S1*ms1; if (tiisg == 0) { ss[j*TF + 0] = S; ss[j*TF + 1] = M; ss[j*TF + C + j ] = ms0; ss[j*TF + C + j + sg*SH] = ms1; } } // O_0 = diag(ms0)*O_0 + diag(ms1)*O_1 { simdgroup_half8x8 t; simdgroup_float8x8 ms0; simdgroup_float8x8 ms1; simdgroup_load(ms0, ss + C, TF, 0, false); simdgroup_load(ms1, ss + C + sg*SH, TF, 0, false); for (short i = 0; i < D8; ++i) { simdgroup_load (t, sq + i*8, T, 0, false); simdgroup_multiply(t, ms1, t); simdgroup_multiply_accumulate(lo[i], ms0, lo[i], t); } } } } // store result to shared memory (reuse sq) if (sgitg == 0) { for (short i = 0; i < D8; ++i) { simdgroup_store(lo[i], sq + i*8, T, 0, false); } } device float4 * dst4 = (device float4 *) dst; // final rescale with 1/S and store to global memory if (sgitg == 0) { for (short j = 0; j < Q && iq1 + j < ne01; ++j) { const float S = ss[j*TF + 0]; for (short i = tiisg; i < D4; i += NW) { dst4[(iq3*ne2*ne1 + iq2 + (iq1 + j)*ne1)*D4 + i] = (float4) sq4[j*T4 + i]/S; } } } } template [[host_name("kernel_flash_attn_ext_f16_h64" )]] kernel flash_attn_ext_f16_t kernel_flash_attn_ext_f16<64>; template [[host_name("kernel_flash_attn_ext_f16_h80" )]] kernel flash_attn_ext_f16_t kernel_flash_attn_ext_f16<80>; template [[host_name("kernel_flash_attn_ext_f16_h96" )]] kernel flash_attn_ext_f16_t kernel_flash_attn_ext_f16<96>; template [[host_name("kernel_flash_attn_ext_f16_h112")]] kernel flash_attn_ext_f16_t kernel_flash_attn_ext_f16<112>; template [[host_name("kernel_flash_attn_ext_f16_h128")]] kernel flash_attn_ext_f16_t kernel_flash_attn_ext_f16<128>; //template [[host_name("kernel_flash_attn_ext_f16_h256")]] kernel flash_attn_ext_f16_t kernel_flash_attn_ext_f16<256>; template<int64_t D, int64_t Q = 1, int64_t C = 32> // head size, queries per threadgroup, cache items per threadgroup kernel void kernel_flash_attn_ext_vec_f16( device const char * q, device const char * k, device const char * v, device const char * mask, device float * dst, constant int64_t & ne01, constant int64_t & ne02, constant int64_t & ne03, constant uint64_t & nb01, constant uint64_t & nb02, constant uint64_t & nb03, constant int64_t & ne11, constant int64_t & ne12, constant int64_t & ne13, constant uint64_t & nb11, constant uint64_t & nb12, constant uint64_t & nb13, constant uint64_t & nb21, constant uint64_t & nb22, constant uint64_t & nb23, constant uint64_t & nb31, constant int64_t & ne1, constant int64_t & ne2, constant float & scale, constant float & max_bias, constant float & m0, constant float & m1, constant uint32_t & n_head_log2, constant float & logit_softcap, threadgroup half * shared [[threadgroup(0)]], uint3 tgpig[[threadgroup_position_in_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg[[threads_per_threadgroup]], ushort tiisg[[thread_index_in_simdgroup]], ushort sgitg[[simdgroup_index_in_threadgroup]]) { const short nsg = ntg.y; // number of simdgroups const short iq3 = tgpig[2]; const short iq2 = tgpig[1]; const short iq1 = tgpig[0]; const short D4 = D/4; const short NW = N_SIMDWIDTH; const short SH = (C + Q); // shared memory per simdgroup in (half) const short T = D + 2*nsg*SH; // shared memory size per query in (half) float slope = 1.0f; // ALiBi if (max_bias > 0.0f) { const uint32_t h = iq2; const float base = h < n_head_log2 ? m0 : m1; const int exp = h < n_head_log2 ? h + 1 : 2*(h - n_head_log2) + 1; slope = pow(base, exp); } //threadgroup half * sq = (threadgroup half *) (shared + 0*D); // holds the query data threadgroup half4 * sq4 = (threadgroup half4 *) (shared + 0*D); // same as above but in half4 threadgroup float * ss = (threadgroup float *) (shared + 2*sgitg*SH + 1*D); // scratch buffer for attention and diagonal matrix threadgroup float4 * ss4 = (threadgroup float4 *) (shared + 2*sgitg*SH + 1*D); // same as above but in half4 threadgroup half4 * sr4 = (threadgroup half4 *) (shared + sgitg*D + 1*T); // scratch buffer for the results // store the result for all queries in local memory in 8x8 matrices (the O matrix from the paper) half4 lo[D4/NW]; // load heads from Q to shared memory device const float4 * q4 = (device const float4 *) ((device const char *) q + (iq1*nb01 + iq2*nb02 + iq3*nb03)); for (short i = tiisg; i < D4; i += NW) { if (iq1 < ne01) { sq4[i] = (half4) q4[i]; } else { sq4[i] = 0.0h; } } // zero out lo for (short i = tiisg; i < D4; i += NW) { lo[i/NW] = 0.0h; } // zero out shared memory SH for (short i = tiisg; i < SH/4; i += NW) { ss4[i] = 0.0h; } threadgroup_barrier(mem_flags::mem_threadgroup); { float S = { 0.0h }; float M = { -FLT_MAX/2 }; // assume K and V are same shape const short ne22 = ne12; const short ne23 = ne13; // broadcast const short rk2 = ne02/ne12; const short rk3 = ne03/ne13; const short rv2 = ne02/ne22; const short rv3 = ne03/ne23; // k indices const short ik2 = iq2 / rk2; const short ik3 = iq3 / rk3; // v indices const short iv2 = iq2 / rv2; const short iv3 = iq3 / rv3; // load the queries from shared memory into local memory float4 mq[D4]; for (short ii = 0; ii < D4; ii += NW) { short i = ii + tiisg; mq[i] = (float4) sq4[i]; } // pointer to the mask device const half4 * mp4 = (device const half4 *) (mask + iq1*nb31); // loop over the KV cache // each simdgroup handles blocks of Q rows and C columns for (int ic0 = 0; ic0 < ne11; ic0 += C*nsg) { const int ic = ic0 + C*sgitg; if (ic >= ne11) { break; } // Q*K^T { #pragma unroll for (short cc = 0; cc < C/4; ++cc) { float4 mqk = { 0.0h }; device const half4 * pk4 = (device const half4 *) ((device const char *) k + ((ic + 4*cc)*nb11 + ik2*nb12 + ik3*nb13)); #pragma unroll for (short ii = 0; ii < D4; ii += NW) { const short i = ii + tiisg; float4x4 mk; mk[0] = (float4) pk4[i + 0*(nb11/8)]; mk[1] = (float4) pk4[i + 1*(nb11/8)]; mk[2] = (float4) pk4[i + 2*(nb11/8)]; mk[3] = (float4) pk4[i + 3*(nb11/8)]; mqk += (float4) (mq[i] * mk); } // reduce the results from the threads in the simdgroup mqk += simd_shuffle_down(mqk, 16); mqk += simd_shuffle_down(mqk, 8); mqk += simd_shuffle_down(mqk, 4); mqk += simd_shuffle_down(mqk, 2); mqk += simd_shuffle_down(mqk, 1); // mqk = mqk*scale + mask*slope if (tiisg == 0) { mqk *= scale; if (logit_softcap != 0.0f) { mqk = logit_softcap*precise::tanh(mqk); } mqk += (mask != q) ? ((float4) mp4[ic/4 + cc])*slope : (float4) 0.0f; ss4[cc] = mqk; } } } // online softmax { const short p = tiisg; const float m = M; const float s = ss[p]; M = simd_max(max(M, s)); const float ms = exp(m - M); const float vs = exp(s - M); S = S*ms + simd_sum(vs); // the P matrix from the paper (Q rows, C columns) ss[p] = vs; // O = diag(ms)*O #pragma unroll for (short ii = 0; ii < D4; ii += NW) { const short i = ii + tiisg; lo[i/NW] *= ms; } } // O = O + (Q*K^T)*V { #pragma unroll for (short cc = 0; cc < C/4; ++cc) { device const half4 * pv4 = (device const half4 *) ((device const char *) v + ((ic + 4*cc)*nb21 + iv2*nb22 + iv3*nb23)); #pragma unroll for (short ii = 0; ii < D4; ii += NW) { const short i = ii + tiisg; lo[i/NW] += pv4[i + 0*(nb21/8)] * ss[4*cc + 0]; lo[i/NW] += pv4[i + 1*(nb21/8)] * ss[4*cc + 1]; lo[i/NW] += pv4[i + 2*(nb21/8)] * ss[4*cc + 2]; lo[i/NW] += pv4[i + 3*(nb21/8)] * ss[4*cc + 3]; } } } } // these are needed for reducing the results from the simdgroups (reuse the ss buffer) if (tiisg == 0) { ss[0] = S; ss[1] = M; } } // store results to shared memory for (short ii = 0; ii < D4; ii += NW) { short i = ii + tiisg; sr4[i] = lo[ii/NW]; } threadgroup_barrier(mem_flags::mem_threadgroup); // parallel reduce for (short r = nsg/2; r > 0; r >>= 1) { if (sgitg < r) { const float S0 = ss[ 0]; const float S1 = ss[r*SH + 0]; const float M0 = ss[ 1]; const float M1 = ss[r*SH + 1]; const float M = max(M0, M1); const float ms0 = exp(M0 - M); const float ms1 = exp(M1 - M); const float S = S0*ms0 + S1*ms1; if (tiisg == 0) { ss[0] = S; ss[1] = M; } // O_0 = diag(ms0)*O_0 + diag(ms1)*O_1 for (short ii = 0; ii < D4; ii += NW) { short i = ii + tiisg; sr4[i] = sr4[i]*ms0 + sr4[i + r*D4]*ms1; } } threadgroup_barrier(mem_flags::mem_threadgroup); } device float4 * dst4 = (device float4 *) dst; // final rescale with 1/S and store to global memory if (sgitg == 0) { const float S = ss[0]; for (short ii = 0; ii < D4; ii += NW) { short i = ii + tiisg; dst4[(iq3*ne2*ne1 + iq2 + (iq1)*ne1)*D4 + i] = (float4) sr4[i]/S; } } } template [[host_name("kernel_flash_attn_ext_vec_f16_h128")]] kernel flash_attn_ext_f16_t kernel_flash_attn_ext_vec_f16<128>; //template [[host_name("kernel_flash_attn_ext_vec_f16_h256")]] kernel flash_attn_ext_f16_t kernel_flash_attn_ext_vec_f16<256>; template<typename T0, typename T1> kernel void kernel_cpy( device const void * src0, device void * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant int64_t & ne03, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant uint64_t & nb03, constant int64_t & ne0, constant int64_t & ne1, constant int64_t & ne2, constant int64_t & ne3, constant uint64_t & nb0, constant uint64_t & nb1, constant uint64_t & nb2, constant uint64_t & nb3, uint3 tgpig[[threadgroup_position_in_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg[[threads_per_threadgroup]]) { const int64_t i03 = tgpig[2]; const int64_t i02 = tgpig[1]; const int64_t i01 = tgpig[0]; const int64_t n = i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00; const int64_t i3 = n / (ne2*ne1*ne0); const int64_t i2 = (n - i3*ne2*ne1*ne0) / (ne1*ne0); const int64_t i1 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0) / ne0; const int64_t i0 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0 - i1*ne0); device T1 * dst_data = (device T1 *) ((device char *) dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0); for (int64_t i00 = tpitg.x; i00 < ne00; i00 += ntg.x) { device const T0 * src = (device T0 *)((device char *) src0 + i03*nb03 + i02*nb02 + i01*nb01 + i00*nb00); dst_data[i00] = (T1) src[0]; } } typedef decltype(kernel_cpy<float, float>) kernel_cpy_t; template [[host_name("kernel_cpy_f32_f32")]] kernel kernel_cpy_t kernel_cpy<float, float>; template [[host_name("kernel_cpy_f32_f16")]] kernel kernel_cpy_t kernel_cpy<float, half>; template [[host_name("kernel_cpy_f16_f16")]] kernel kernel_cpy_t kernel_cpy<half, half>; template [[host_name("kernel_cpy_f16_f32")]] kernel kernel_cpy_t kernel_cpy<half, float>; kernel void kernel_cpy_f32_q8_0( device const float * src0, device void * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant int64_t & ne03, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant uint64_t & nb03, constant int64_t & ne0, constant int64_t & ne1, constant int64_t & ne2, constant int64_t & ne3, constant uint64_t & nb0, constant uint64_t & nb1, constant uint64_t & nb2, constant uint64_t & nb3, uint3 tgpig[[threadgroup_position_in_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg[[threads_per_threadgroup]]) { const int64_t i03 = tgpig[2]; const int64_t i02 = tgpig[1]; const int64_t i01 = tgpig[0]; const int64_t n = i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00; const int64_t i3 = n / (ne2*ne1*ne0); const int64_t i2 = (n - i3*ne2*ne1*ne0) / (ne1*ne0); const int64_t i1 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0) / ne0; const int64_t i0 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0 - i1*ne0)/QK8_0; device block_q8_0 * dst_data = (device block_q8_0 *) ((device char *) dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0); for (int64_t i00 = tpitg.x*QK8_0; i00 < ne00; i00 += ntg.x*QK8_0) { device const float * src = (device float *)((device char *) src0 + i03*nb03 + i02*nb02 + i01*nb01 + i00*nb00); float amax = 0.0f; // absolute max for (int j = 0; j < QK8_0; j++) { const float v = src[j]; amax = MAX(amax, fabs(v)); } const float d = amax / ((1 << 7) - 1); const float id = d ? 1.0f/d : 0.0f; dst_data[i00/QK8_0].d = d; for (int j = 0; j < QK8_0; ++j) { const float x0 = src[j]*id; dst_data[i00/QK8_0].qs[j] = round(x0); } } } kernel void kernel_cpy_f32_q4_0( device const float * src0, device void * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant int64_t & ne03, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant uint64_t & nb03, constant int64_t & ne0, constant int64_t & ne1, constant int64_t & ne2, constant int64_t & ne3, constant uint64_t & nb0, constant uint64_t & nb1, constant uint64_t & nb2, constant uint64_t & nb3, uint3 tgpig[[threadgroup_position_in_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg[[threads_per_threadgroup]]) { const int64_t i03 = tgpig[2]; const int64_t i02 = tgpig[1]; const int64_t i01 = tgpig[0]; const int64_t n = i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00; const int64_t i3 = n / (ne2*ne1*ne0); const int64_t i2 = (n - i3*ne2*ne1*ne0) / (ne1*ne0); const int64_t i1 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0) / ne0; const int64_t i0 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0 - i1*ne0)/QK4_0; device block_q4_0 * dst_data = (device block_q4_0 *) ((device char *) dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0); for (int64_t i00 = tpitg.x*QK4_0; i00 < ne00; i00 += ntg.x*QK4_0) { device const float * src = (device float *)((device char *) src0 + i03*nb03 + i02*nb02 + i01*nb01 + i00*nb00); float amax = 0.0f; // absolute max float max = 0.0f; for (int j = 0; j < QK4_0; j++) { const float v = src[j]; if (amax < fabs(v)) { amax = fabs(v); max = v; } } const float d = max / -8; const float id = d ? 1.0f/d : 0.0f; dst_data[i00/QK4_0].d = d; for (int j = 0; j < QK4_0/2; ++j) { const float x0 = src[0 + j]*id; const float x1 = src[QK4_0/2 + j]*id; const uint8_t xi0 = MIN(15, (int8_t)(x0 + 8.5f)); const uint8_t xi1 = MIN(15, (int8_t)(x1 + 8.5f)); dst_data[i00/QK4_0].qs[j] = xi0; dst_data[i00/QK4_0].qs[j] |= xi1 << 4; } } } kernel void kernel_cpy_f32_q4_1( device const float * src0, device void * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant int64_t & ne03, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant uint64_t & nb03, constant int64_t & ne0, constant int64_t & ne1, constant int64_t & ne2, constant int64_t & ne3, constant uint64_t & nb0, constant uint64_t & nb1, constant uint64_t & nb2, constant uint64_t & nb3, uint3 tgpig[[threadgroup_position_in_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg[[threads_per_threadgroup]]) { const int64_t i03 = tgpig[2]; const int64_t i02 = tgpig[1]; const int64_t i01 = tgpig[0]; const int64_t n = i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00; const int64_t i3 = n / (ne2*ne1*ne0); const int64_t i2 = (n - i3*ne2*ne1*ne0) / (ne1*ne0); const int64_t i1 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0) / ne0; const int64_t i0 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0 - i1*ne0)/QK4_1; device block_q4_1 * dst_data = (device block_q4_1 *) ((device char *) dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0); for (int64_t i00 = tpitg.x*QK4_1; i00 < ne00; i00 += ntg.x*QK4_1) { device const float * src = (device float *)((device char *) src0 + i03*nb03 + i02*nb02 + i01*nb01 + i00*nb00); float min = FLT_MAX; float max = -FLT_MAX; for (int j = 0; j < QK4_1; j++) { const float v = src[j]; if (min > v) min = v; if (max < v) max = v; } const float d = (max - min) / ((1 << 4) - 1); const float id = d ? 1.0f/d : 0.0f; dst_data[i00/QK4_1].d = d; dst_data[i00/QK4_1].m = min; for (int j = 0; j < QK4_1/2; ++j) { const float x0 = (src[0 + j] - min)*id; const float x1 = (src[QK4_1/2 + j] - min)*id; const uint8_t xi0 = MIN(15, (int8_t)(x0 + 0.5f)); const uint8_t xi1 = MIN(15, (int8_t)(x1 + 0.5f)); dst_data[i00/QK4_1].qs[j] = xi0; dst_data[i00/QK4_1].qs[j] |= xi1 << 4; } } } kernel void kernel_cpy_f32_q5_0( device const float * src0, device void * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant int64_t & ne03, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant uint64_t & nb03, constant int64_t & ne0, constant int64_t & ne1, constant int64_t & ne2, constant int64_t & ne3, constant uint64_t & nb0, constant uint64_t & nb1, constant uint64_t & nb2, constant uint64_t & nb3, uint3 tgpig[[threadgroup_position_in_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg[[threads_per_threadgroup]]) { const int64_t i03 = tgpig[2]; const int64_t i02 = tgpig[1]; const int64_t i01 = tgpig[0]; const int64_t n = i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00; const int64_t i3 = n / (ne2*ne1*ne0); const int64_t i2 = (n - i3*ne2*ne1*ne0) / (ne1*ne0); const int64_t i1 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0) / ne0; const int64_t i0 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0 - i1*ne0)/QK5_0; device block_q5_0 * dst_data = (device block_q5_0 *) ((device char *) dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0); for (int64_t i00 = tpitg.x*QK5_0; i00 < ne00; i00 += ntg.x*QK5_0) { device const float * src = (device float *)((device char *) src0 + i03*nb03 + i02*nb02 + i01*nb01 + i00*nb00); float amax = 0.0f; // absolute max float max = 0.0f; for (int j = 0; j < QK5_0; j++) { const float v = src[j]; if (amax < fabs(v)) { amax = fabs(v); max = v; } } const float d = max / -16; const float id = d ? 1.0f/d : 0.0f; dst_data[i00/QK5_0].d = d; uint32_t qh = 0; for (int j = 0; j < QK5_0/2; ++j) { const float x0 = src[0 + j]*id; const float x1 = src[QK5_0/2 + j]*id; const uint8_t xi0 = MIN(31, (int8_t)(x0 + 16.5f)); const uint8_t xi1 = MIN(31, (int8_t)(x1 + 16.5f)); dst_data[i00/QK5_0].qs[j] = (xi0 & 0xf) | ((xi1 & 0xf) << 4); qh |= ((xi0 & 0x10u) >> 4) << (j + 0); qh |= ((xi1 & 0x10u) >> 4) << (j + QK5_0/2); } thread const uint8_t * qh8 = (thread const uint8_t *)&qh; for (int j = 0; j < 4; ++j) { dst_data[i00/QK5_0].qh[j] = qh8[j]; } } } kernel void kernel_cpy_f32_q5_1( device const float * src0, device void * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant int64_t & ne03, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant uint64_t & nb03, constant int64_t & ne0, constant int64_t & ne1, constant int64_t & ne2, constant int64_t & ne3, constant uint64_t & nb0, constant uint64_t & nb1, constant uint64_t & nb2, constant uint64_t & nb3, uint3 tgpig[[threadgroup_position_in_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg[[threads_per_threadgroup]]) { const int64_t i03 = tgpig[2]; const int64_t i02 = tgpig[1]; const int64_t i01 = tgpig[0]; const int64_t n = i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00; const int64_t i3 = n / (ne2*ne1*ne0); const int64_t i2 = (n - i3*ne2*ne1*ne0) / (ne1*ne0); const int64_t i1 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0) / ne0; const int64_t i0 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0 - i1*ne0)/QK5_1; device block_q5_1 * dst_data = (device block_q5_1 *) ((device char *) dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0); for (int64_t i00 = tpitg.x*QK5_1; i00 < ne00; i00 += ntg.x*QK5_1) { device const float * src = (device float *)((device char *) src0 + i03*nb03 + i02*nb02 + i01*nb01 + i00*nb00); float max = src[0]; float min = src[0]; for (int j = 1; j < QK5_1; j++) { const float v = src[j]; min = v < min ? v : min; max = v > max ? v : max; } const float d = (max - min) / 31; const float id = d ? 1.0f/d : 0.0f; dst_data[i00/QK5_1].d = d; dst_data[i00/QK5_1].m = min; uint32_t qh = 0; for (int j = 0; j < QK5_1/2; ++j) { const float x0 = (src[0 + j] - min)*id; const float x1 = (src[QK5_1/2 + j] - min)*id; const uint8_t xi0 = (uint8_t)(x0 + 0.5f); const uint8_t xi1 = (uint8_t)(x1 + 0.5f); dst_data[i00/QK5_1].qs[j] = (xi0 & 0xf) | ((xi1 & 0xf) << 4); qh |= ((xi0 & 0x10u) >> 4) << (j + 0); qh |= ((xi1 & 0x10u) >> 4) << (j + QK5_1/2); } thread const uint8_t * qh8 = (thread const uint8_t *)&qh; for (int j = 0; j < 4; ++j) { dst_data[i00/QK5_1].qh[j] = qh8[j]; } } } static inline int best_index_int8(int n, constant float * val, float x) { if (x <= val[0]) return 0; if (x >= val[n-1]) return n-1; int ml = 0, mu = n-1; while (mu-ml > 1) { int mav = (ml+mu)/2; if (x < val[mav]) mu = mav; else ml = mav; } return x - val[mu-1] < val[mu] - x ? mu-1 : mu; } constexpr constant static float kvalues_iq4nl_f[16] = { -127.f, -104.f, -83.f, -65.f, -49.f, -35.f, -22.f, -10.f, 1.f, 13.f, 25.f, 38.f, 53.f, 69.f, 89.f, 113.f }; kernel void kernel_cpy_f32_iq4_nl( device const float * src0, device void * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant int64_t & ne03, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant uint64_t & nb03, constant int64_t & ne0, constant int64_t & ne1, constant int64_t & ne2, constant int64_t & ne3, constant uint64_t & nb0, constant uint64_t & nb1, constant uint64_t & nb2, constant uint64_t & nb3, uint3 tgpig[[threadgroup_position_in_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg[[threads_per_threadgroup]]) { const int64_t i03 = tgpig[2]; const int64_t i02 = tgpig[1]; const int64_t i01 = tgpig[0]; const int64_t n = i03*ne02*ne01*ne00 + i02*ne01*ne00 + i01*ne00; const int64_t i3 = n / (ne2*ne1*ne0); const int64_t i2 = (n - i3*ne2*ne1*ne0) / (ne1*ne0); const int64_t i1 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0) / ne0; const int64_t i0 = (n - i3*ne2*ne1*ne0 - i2*ne1*ne0 - i1*ne0)/QK4_NL; device block_iq4_nl * dst_data = (device block_iq4_nl *) ((device char *) dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0); for (int64_t i00 = tpitg.x*QK4_NL; i00 < ne00; i00 += ntg.x*QK4_NL) { device const float * src = (device float *)((device char *) src0 + i03*nb03 + i02*nb02 + i01*nb01 + i00*nb00); float amax = 0.0f; // absolute max float max = 0.0f; for (int j = 0; j < QK4_0; j++) { const float v = src[j]; if (amax < fabs(v)) { amax = fabs(v); max = v; } } const float d = max / kvalues_iq4nl_f[0]; const float id = d ? 1.0f/d : 0.0f; float sumqx = 0, sumq2 = 0; for (int j = 0; j < QK4_NL/2; ++j) { const float x0 = src[0 + j]*id; const float x1 = src[QK4_NL/2 + j]*id; const uint8_t xi0 = best_index_int8(16, kvalues_iq4nl_f, x0); const uint8_t xi1 = best_index_int8(16, kvalues_iq4nl_f, x1); dst_data[i00/QK4_NL].qs[j] = xi0 | (xi1 << 4); const float v0 = kvalues_iq4nl_f[xi0]; const float v1 = kvalues_iq4nl_f[xi1]; const float w0 = src[0 + j]*src[0 + j]; const float w1 = src[QK4_NL/2 + j]*src[QK4_NL/2 + j]; sumqx += w0*v0*src[j] + w1*v1*src[QK4_NL/2 + j]; sumq2 += w0*v0*v0 + w1*v1*v1; } dst_data[i00/QK4_NL].d = sumq2 > 0 ? sumqx/sumq2 : d; } } kernel void kernel_concat( device const char * src0, device const char * src1, device char * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant int64_t & ne03, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant uint64_t & nb03, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant int64_t & ne13, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant uint64_t & nb13, constant int64_t & ne0, constant int64_t & ne1, constant int64_t & ne2, constant int64_t & ne3, constant uint64_t & nb0, constant uint64_t & nb1, constant uint64_t & nb2, constant uint64_t & nb3, constant int32_t & dim, uint3 tgpig[[threadgroup_position_in_grid]], uint3 tpitg[[thread_position_in_threadgroup]], uint3 ntg[[threads_per_threadgroup]]) { const int64_t i3 = tgpig.z; const int64_t i2 = tgpig.y; const int64_t i1 = tgpig.x; int64_t o[4] = {0, 0, 0, 0}; o[dim] = dim == 0 ? ne00 : (dim == 1 ? ne01 : (dim == 2 ? ne02 : ne03)); device const float * x; for (int i0 = tpitg.x; i0 < ne0; i0 += ntg.x) { if (i0 < ne00 && i1 < ne01 && i2 < ne02 && i3 < ne03) { x = (device const float *)(src0 + (i3 )*nb03 + (i2 )*nb02 + (i1 )*nb01 + (i0 )*nb00); } else { x = (device const float *)(src1 + (i3 - o[3])*nb13 + (i2 - o[2])*nb12 + (i1 - o[1])*nb11 + (i0 - o[0])*nb10); } device float * y = (device float *)(dst + i3*nb3 + i2*nb2 + i1*nb1 + i0*nb0); *y = *x; } } void kernel_mul_mv_q2_K_f32_impl( device const void * src0, device const float * src1, device float * dst, int64_t ne00, int64_t ne01, int64_t ne02, int64_t ne10, int64_t ne12, int64_t ne0, int64_t ne1, uint r2, uint r3, threadgroup int8_t * shared_values, uint3 tgpig, uint tiisg, uint sgitg) { const int nb = ne00/QK_K; const int r0 = tgpig.x; const int r1 = tgpig.y; const int im = tgpig.z; const int first_row = (r0 * N_SIMDGROUP + sgitg) * N_DST; const int ib_row = first_row * nb; const uint i12 = im%ne12; const uint i13 = im/ne12; const uint offset0 = (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02); device const block_q2_K * x = (device const block_q2_K *) src0 + ib_row + offset0; device const float * y = (device const float *) src1 + r1*ne10 + im*ne00*ne1; float yl[32]; float sumf[N_DST]={0.f}, all_sum; const int step = sizeof(block_q2_K) * nb; const int ix = tiisg/8; // 0...3 const int it = tiisg%8; // 0...7 const int iq = it/4; // 0 or 1 const int ir = it%4; // 0...3 const int is = (8*ir)/16;// 0 or 1 device const float * y4 = y + ix * QK_K + 128 * iq + 8 * ir; for (int ib = ix; ib < nb; ib += 4) { float4 sumy = {0.f, 0.f, 0.f, 0.f}; for (int i = 0; i < 8; ++i) { yl[i+ 0] = y4[i+ 0]; sumy[0] += yl[i+ 0]; yl[i+ 8] = y4[i+32]; sumy[1] += yl[i+ 8]; yl[i+16] = y4[i+64]; sumy[2] += yl[i+16]; yl[i+24] = y4[i+96]; sumy[3] += yl[i+24]; } device const uint8_t * sc = (device const uint8_t *)x[ib].scales + 8*iq + is; device const uint16_t * qs = (device const uint16_t *)x[ib].qs + 16 * iq + 4 * ir; device const half * dh = &x[ib].d; for (int row = 0; row < N_DST; row++) { float4 acc1 = {0.f, 0.f, 0.f, 0.f}; float4 acc2 = {0.f, 0.f, 0.f, 0.f}; for (int i = 0; i < 8; i += 2) { acc1[0] += yl[i+ 0] * (qs[i/2] & 0x0003); acc2[0] += yl[i+ 1] * (qs[i/2] & 0x0300); acc1[1] += yl[i+ 8] * (qs[i/2] & 0x000c); acc2[1] += yl[i+ 9] * (qs[i/2] & 0x0c00); acc1[2] += yl[i+16] * (qs[i/2] & 0x0030); acc2[2] += yl[i+17] * (qs[i/2] & 0x3000); acc1[3] += yl[i+24] * (qs[i/2] & 0x00c0); acc2[3] += yl[i+25] * (qs[i/2] & 0xc000); } float dall = dh[0]; float dmin = dh[1] * 1.f/16.f; sumf[row] += dall * ((acc1[0] + 1.f/256.f * acc2[0]) * (sc[0] & 0xF) * 1.f/ 1.f + (acc1[1] + 1.f/256.f * acc2[1]) * (sc[2] & 0xF) * 1.f/ 4.f + (acc1[2] + 1.f/256.f * acc2[2]) * (sc[4] & 0xF) * 1.f/16.f + (acc1[3] + 1.f/256.f * acc2[3]) * (sc[6] & 0xF) * 1.f/64.f) - dmin * (sumy[0] * (sc[0] & 0xF0) + sumy[1] * (sc[2] & 0xF0) + sumy[2] * (sc[4] & 0xF0) + sumy[3] * (sc[6] & 0xF0)); qs += step/2; sc += step; dh += step/2; } y4 += 4 * QK_K; } for (int row = 0; row < N_DST; ++row) { all_sum = simd_sum(sumf[row]); if (tiisg == 0) { dst[r1*ne0 + im*ne0*ne1 + first_row + row] = all_sum; } } } [[host_name("kernel_mul_mv_q2_K_f32")]] kernel void kernel_mul_mv_q2_K_f32( device const void * src0, device const float * src1, device float * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant int64_t & ne0, constant int64_t & ne1, constant uint & r2, constant uint & r3, uint3 tgpig[[threadgroup_position_in_grid]], uint tiisg[[thread_index_in_simdgroup]], uint sgitg[[simdgroup_index_in_threadgroup]]) { kernel_mul_mv_q2_K_f32_impl(src0, src1, dst, ne00, ne01, ne02, ne10, ne12, ne0, ne1, r2, r3, nullptr, tgpig, tiisg, sgitg); } void kernel_mul_mv_q3_K_f32_impl( device const void * src0, device const float * src1, device float * dst, int64_t ne00, int64_t ne01, int64_t ne02, int64_t ne10, int64_t ne12, int64_t ne0, int64_t ne1, uint r2, uint r3, threadgroup int8_t * shared_values, uint3 tgpig, uint tiisg, uint sgitg) { const int nb = ne00/QK_K; const int64_t r0 = tgpig.x; const int64_t r1 = tgpig.y; const int64_t im = tgpig.z; const int first_row = (r0 * N_SIMDGROUP + sgitg) * 2; const uint i12 = im%ne12; const uint i13 = im/ne12; const uint offset0 = (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02); device const block_q3_K * x = (device const block_q3_K *) src0 + first_row*nb + offset0; device const float * yy = (device const float *) src1 + r1*ne10 + im*ne00*ne1; float yl[32]; //const uint16_t kmask1 = 0x3030; //const uint16_t kmask2 = 0x0f0f; const int tid = tiisg/4; const int ix = tiisg%4; const int ip = tid/4; // 0 or 1 const int il = 2*((tid%4)/2); // 0 or 2 const int ir = tid%2; const int n = 8; const int l0 = n*ir; // One would think that the Metal compiler would figure out that ip and il can only have // 4 possible states, and optimize accordingly. Well, no. It needs help, and we do it // with these two tales. // // Possible masks for the high bit const ushort4 mm[4] = {{0x0001, 0x0100, 0x0002, 0x0200}, // ip = 0, il = 0 {0x0004, 0x0400, 0x0008, 0x0800}, // ip = 0, il = 2 {0x0010, 0x1000, 0x0020, 0x2000}, // ip = 1, il = 0 {0x0040, 0x4000, 0x0080, 0x8000}}; // ip = 1, il = 2 // Possible masks for the low 2 bits const int4 qm[2] = {{0x0003, 0x0300, 0x000c, 0x0c00}, {0x0030, 0x3000, 0x00c0, 0xc000}}; const ushort4 hm = mm[2*ip + il/2]; const int shift = 2*il; const float v1 = il == 0 ? 4.f : 64.f; const float v2 = 4.f * v1; const uint16_t s_shift1 = 4*ip; const uint16_t s_shift2 = s_shift1 + il; const int q_offset = 32*ip + l0; const int y_offset = 128*ip + 32*il + l0; const int step = sizeof(block_q3_K) * nb / 2; device const float * y1 = yy + ix*QK_K + y_offset; uint32_t scales32, aux32; thread uint16_t * scales16 = (thread uint16_t *)&scales32; thread const int8_t * scales = (thread const int8_t *)&scales32; float sumf1[2] = {0.f}; float sumf2[2] = {0.f}; for (int i = ix; i < nb; i += 4) { for (int l = 0; l < 8; ++l) { yl[l+ 0] = y1[l+ 0]; yl[l+ 8] = y1[l+16]; yl[l+16] = y1[l+32]; yl[l+24] = y1[l+48]; } device const uint16_t * q = (device const uint16_t *)(x[i].qs + q_offset); device const uint16_t * h = (device const uint16_t *)(x[i].hmask + l0); device const uint16_t * a = (device const uint16_t *)(x[i].scales); device const half * dh = &x[i].d; for (int row = 0; row < 2; ++row) { const float d_all = (float)dh[0]; scales16[0] = a[4]; scales16[1] = a[5]; aux32 = ((scales32 >> s_shift2) << 4) & 0x30303030; scales16[0] = a[il+0]; scales16[1] = a[il+1]; scales32 = ((scales32 >> s_shift1) & 0x0f0f0f0f) | aux32; float s1 = 0, s2 = 0, s3 = 0, s4 = 0, s5 = 0, s6 = 0; for (int l = 0; l < n; l += 2) { const int32_t qs = q[l/2]; s1 += yl[l+0] * (qs & qm[il/2][0]); s2 += yl[l+1] * (qs & qm[il/2][1]); s3 += ((h[l/2] & hm[0]) ? 0.f : yl[l+0]) + ((h[l/2] & hm[1]) ? 0.f : yl[l+1]); s4 += yl[l+16] * (qs & qm[il/2][2]); s5 += yl[l+17] * (qs & qm[il/2][3]); s6 += ((h[l/2] & hm[2]) ? 0.f : yl[l+16]) + ((h[l/2] & hm[3]) ? 0.f : yl[l+17]); } float d1 = d_all * (s1 + 1.f/256.f * s2 - s3*v1); float d2 = d_all * (s4 + 1.f/256.f * s5 - s6*v2); sumf1[row] += d1 * (scales[0] - 32); sumf2[row] += d2 * (scales[2] - 32); s1 = s2 = s3 = s4 = s5 = s6 = 0; for (int l = 0; l < n; l += 2) { const int32_t qs = q[l/2+8]; s1 += yl[l+8] * (qs & qm[il/2][0]); s2 += yl[l+9] * (qs & qm[il/2][1]); s3 += ((h[l/2+8] & hm[0]) ? 0.f : yl[l+8]) + ((h[l/2+8] & hm[1]) ? 0.f : yl[l+9]); s4 += yl[l+24] * (qs & qm[il/2][2]); s5 += yl[l+25] * (qs & qm[il/2][3]); s6 += ((h[l/2+8] & hm[2]) ? 0.f : yl[l+24]) + ((h[l/2+8] & hm[3]) ? 0.f : yl[l+25]); } d1 = d_all * (s1 + 1.f/256.f * s2 - s3*v1); d2 = d_all * (s4 + 1.f/256.f * s5 - s6*v2); sumf1[row] += d1 * (scales[1] - 32); sumf2[row] += d2 * (scales[3] - 32); q += step; h += step; a += step; dh += step; } y1 += 4 * QK_K; } for (int row = 0; row < 2; ++row) { const float sumf = (sumf1[row] + 0.25f * sumf2[row]) / (1 << shift); sumf1[row] = simd_sum(sumf); } if (tiisg == 0) { for (int row = 0; row < 2; ++row) { dst[r1*ne0 + im*ne0*ne1 + first_row + row] = sumf1[row]; } } } [[host_name("kernel_mul_mv_q3_K_f32")]] kernel void kernel_mul_mv_q3_K_f32( device const void * src0, device const float * src1, device float * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant int64_t & ne0, constant int64_t & ne1, constant uint & r2, constant uint & r3, uint3 tgpig[[threadgroup_position_in_grid]], uint tiisg[[thread_index_in_simdgroup]], uint sgitg[[simdgroup_index_in_threadgroup]]) { kernel_mul_mv_q3_K_f32_impl(src0, src1, dst, ne00, ne01, ne02, ne10, ne12, ne0, ne1, r2, r3, nullptr, tgpig, tiisg, sgitg); } void kernel_mul_mv_q4_K_f32_impl( device const void * src0, device const float * src1, device float * dst, int64_t ne00, int64_t ne01, int64_t ne02, int64_t ne10, int64_t ne12, int64_t ne0, int64_t ne1, uint r2, uint r3, threadgroup int8_t * shared_values, uint3 tgpig, uint tiisg, uint sgitg) { const uint16_t kmask1 = 0x3f3f; const uint16_t kmask2 = 0x0f0f; const uint16_t kmask3 = 0xc0c0; const int ix = tiisg/8; // 0...3 const int it = tiisg%8; // 0...7 const int iq = it/4; // 0 or 1 const int ir = it%4; // 0...3 const int nb = ne00/QK_K; const int r0 = tgpig.x; const int r1 = tgpig.y; const int im = tgpig.z; //const int first_row = (r0 * N_SIMDGROUP + sgitg) * N_DST; const int first_row = r0 * N_DST; const int ib_row = first_row * nb; const uint i12 = im%ne12; const uint i13 = im/ne12; const uint offset0 = (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02); device const block_q4_K * x = (device const block_q4_K *) src0 + ib_row + offset0; device const float * y = (device const float *) src1 + r1*ne10 + im*ne00*ne1; float yl[16]; float yh[16]; float sumf[N_DST]={0.f}, all_sum; const int step = sizeof(block_q4_K) * nb / 2; device const float * y4 = y + ix * QK_K + 64 * iq + 8 * ir; uint16_t sc16[4]; thread const uint8_t * sc8 = (thread const uint8_t *)sc16; for (int ib = ix; ib < nb; ib += 4) { float4 sumy = {0.f, 0.f, 0.f, 0.f}; for (int i = 0; i < 8; ++i) { yl[i+0] = y4[i+ 0]; sumy[0] += yl[i+0]; yl[i+8] = y4[i+ 32]; sumy[1] += yl[i+8]; yh[i+0] = y4[i+128]; sumy[2] += yh[i+0]; yh[i+8] = y4[i+160]; sumy[3] += yh[i+8]; } device const uint16_t * sc = (device const uint16_t *)x[ib].scales + iq; device const uint16_t * q1 = (device const uint16_t *)x[ib].qs + 16 * iq + 4 * ir; device const half * dh = &x[ib].d; for (int row = 0; row < N_DST; row++) { sc16[0] = sc[0] & kmask1; sc16[1] = sc[2] & kmask1; sc16[2] = ((sc[4] >> 0) & kmask2) | ((sc[0] & kmask3) >> 2); sc16[3] = ((sc[4] >> 4) & kmask2) | ((sc[2] & kmask3) >> 2); device const uint16_t * q2 = q1 + 32; float4 acc1 = {0.f, 0.f, 0.f, 0.f}; float4 acc2 = {0.f, 0.f, 0.f, 0.f}; for (int i = 0; i < 8; i += 2) { acc1[0] += yl[i+0] * (q1[i/2] & 0x000F); acc1[1] += yl[i+1] * (q1[i/2] & 0x0F00); acc1[2] += yl[i+8] * (q1[i/2] & 0x00F0); acc1[3] += yl[i+9] * (q1[i/2] & 0xF000); acc2[0] += yh[i+0] * (q2[i/2] & 0x000F); acc2[1] += yh[i+1] * (q2[i/2] & 0x0F00); acc2[2] += yh[i+8] * (q2[i/2] & 0x00F0); acc2[3] += yh[i+9] * (q2[i/2] & 0xF000); } float dall = dh[0]; float dmin = dh[1]; sumf[row] += dall * ((acc1[0] + 1.f/256.f * acc1[1]) * sc8[0] + (acc1[2] + 1.f/256.f * acc1[3]) * sc8[1] * 1.f/16.f + (acc2[0] + 1.f/256.f * acc2[1]) * sc8[4] + (acc2[2] + 1.f/256.f * acc2[3]) * sc8[5] * 1.f/16.f) - dmin * (sumy[0] * sc8[2] + sumy[1] * sc8[3] + sumy[2] * sc8[6] + sumy[3] * sc8[7]); q1 += step; sc += step; dh += step; } y4 += 4 * QK_K; } for (int row = 0; row < N_DST; ++row) { all_sum = simd_sum(sumf[row]); if (tiisg == 0) { dst[r1*ne0 + im*ne0*ne1 + first_row + row] = all_sum; } } } [[host_name("kernel_mul_mv_q4_K_f32")]] kernel void kernel_mul_mv_q4_K_f32( device const void * src0, device const float * src1, device float * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant int64_t & ne0, constant int64_t & ne1, constant uint & r2, constant uint & r3, uint3 tgpig[[threadgroup_position_in_grid]], uint tiisg[[thread_index_in_simdgroup]], uint sgitg[[simdgroup_index_in_threadgroup]]) { kernel_mul_mv_q4_K_f32_impl(src0, src1, dst, ne00, ne01, ne02, ne10, ne12, ne0, ne1, r2, r3, nullptr, tgpig, tiisg, sgitg); } void kernel_mul_mv_q5_K_f32_impl( device const void * src0, device const float * src1, device float * dst, int64_t ne00, int64_t ne01, int64_t ne02, int64_t ne10, int64_t ne12, int64_t ne0, int64_t ne1, uint r2, uint r3, threadgroup int8_t * shared_values, uint3 tgpig, uint tiisg, uint sgitg) { const int nb = ne00/QK_K; const int64_t r0 = tgpig.x; const int64_t r1 = tgpig.y; const int im = tgpig.z; const int first_row = (r0 * N_SIMDGROUP + sgitg) * 2; const uint i12 = im%ne12; const uint i13 = im/ne12; const uint offset0 = (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02); device const block_q5_K * x = (device const block_q5_K *) src0 + first_row*nb + offset0; device const float * yy = (device const float *) src1 + r1*ne10 + im*ne00*ne1; float sumf[2]={0.f}; const int step = sizeof(block_q5_K) * nb; float yl[16], yh[16]; const uint16_t kmask1 = 0x3f3f; const uint16_t kmask2 = 0x0f0f; const uint16_t kmask3 = 0xc0c0; const int tid = tiisg/4; const int ix = tiisg%4; const int iq = tid/4; const int ir = tid%4; const int n = 8; const int l0 = n*ir; const int q_offset = 32*iq + l0; const int y_offset = 64*iq + l0; const uint8_t hm1 = 1u << (2*iq); const uint8_t hm2 = hm1 << 1; const uint8_t hm3 = hm1 << 4; const uint8_t hm4 = hm2 << 4; uint16_t sc16[4]; thread const uint8_t * sc8 = (thread const uint8_t *)sc16; device const float * y1 = yy + ix*QK_K + y_offset; for (int i = ix; i < nb; i += 4) { device const uint8_t * q1 = x[i].qs + q_offset; device const uint8_t * qh = x[i].qh + l0; device const half * dh = &x[i].d; device const uint16_t * a = (device const uint16_t *)x[i].scales + iq; device const float * y2 = y1 + 128; float4 sumy = {0.f, 0.f, 0.f, 0.f}; for (int l = 0; l < 8; ++l) { yl[l+0] = y1[l+ 0]; sumy[0] += yl[l+0]; yl[l+8] = y1[l+32]; sumy[1] += yl[l+8]; yh[l+0] = y2[l+ 0]; sumy[2] += yh[l+0]; yh[l+8] = y2[l+32]; sumy[3] += yh[l+8]; } for (int row = 0; row < 2; ++row) { device const uint8_t * q2 = q1 + 64; sc16[0] = a[0] & kmask1; sc16[1] = a[2] & kmask1; sc16[2] = ((a[4] >> 0) & kmask2) | ((a[0] & kmask3) >> 2); sc16[3] = ((a[4] >> 4) & kmask2) | ((a[2] & kmask3) >> 2); float4 acc1 = {0.f}; float4 acc2 = {0.f}; for (int l = 0; l < n; ++l) { uint8_t h = qh[l]; acc1[0] += yl[l+0] * (q1[l] & 0x0F); acc1[1] += yl[l+8] * (q1[l] & 0xF0); acc1[2] += yh[l+0] * (q2[l] & 0x0F); acc1[3] += yh[l+8] * (q2[l] & 0xF0); acc2[0] += h & hm1 ? yl[l+0] : 0.f; acc2[1] += h & hm2 ? yl[l+8] : 0.f; acc2[2] += h & hm3 ? yh[l+0] : 0.f; acc2[3] += h & hm4 ? yh[l+8] : 0.f; } const float dall = dh[0]; const float dmin = dh[1]; sumf[row] += dall * (sc8[0] * (acc1[0] + 16.f*acc2[0]) + sc8[1] * (acc1[1]/16.f + 16.f*acc2[1]) + sc8[4] * (acc1[2] + 16.f*acc2[2]) + sc8[5] * (acc1[3]/16.f + 16.f*acc2[3])) - dmin * (sumy[0] * sc8[2] + sumy[1] * sc8[3] + sumy[2] * sc8[6] + sumy[3] * sc8[7]); q1 += step; qh += step; dh += step/2; a += step/2; } y1 += 4 * QK_K; } for (int row = 0; row < 2; ++row) { const float tot = simd_sum(sumf[row]); if (tiisg == 0) { dst[r1*ne0 + im*ne0*ne1 + first_row + row] = tot; } } } [[host_name("kernel_mul_mv_q5_K_f32")]] kernel void kernel_mul_mv_q5_K_f32( device const void * src0, device const float * src1, device float * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant int64_t & ne0, constant int64_t & ne1, constant uint & r2, constant uint & r3, uint3 tgpig[[threadgroup_position_in_grid]], uint tiisg[[thread_index_in_simdgroup]], uint sgitg[[simdgroup_index_in_threadgroup]]) { kernel_mul_mv_q5_K_f32_impl(src0, src1, dst, ne00, ne01, ne02, ne10, ne12, ne0, ne1, r2, r3, nullptr, tgpig, tiisg, sgitg); } void kernel_mul_mv_q6_K_f32_impl( device const void * src0, device const float * src1, device float * dst, int64_t ne00, int64_t ne01, int64_t ne02, int64_t ne10, int64_t ne12, int64_t ne0, int64_t ne1, uint r2, uint r3, threadgroup int8_t * shared_values, uint3 tgpig, uint tiisg, uint sgitg) { const uint8_t kmask1 = 0x03; const uint8_t kmask2 = 0x0C; const uint8_t kmask3 = 0x30; const uint8_t kmask4 = 0xC0; const int nb = ne00/QK_K; const int64_t r0 = tgpig.x; const int64_t r1 = tgpig.y; const int im = tgpig.z; const int row = 2 * r0 + sgitg; const uint i12 = im%ne12; const uint i13 = im/ne12; const uint offset0 = (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02); device const block_q6_K * x = (device const block_q6_K *) src0 + row * nb + offset0; device const float * yy = (device const float *) src1 + r1*ne10 + im*ne00*ne1; float sumf = 0; const int tid = tiisg/2; const int ix = tiisg%2; const int ip = tid/8; // 0 or 1 const int il = tid%8; const int n = 4; const int l0 = n*il; const int is = 8*ip + l0/16; const int y_offset = 128*ip + l0; const int q_offset_l = 64*ip + l0; const int q_offset_h = 32*ip + l0; for (int i = ix; i < nb; i += 2) { device const uint8_t * q1 = x[i].ql + q_offset_l; device const uint8_t * q2 = q1 + 32; device const uint8_t * qh = x[i].qh + q_offset_h; device const int8_t * sc = x[i].scales + is; device const float * y = yy + i * QK_K + y_offset; const float dall = x[i].d; float4 sums = {0.f, 0.f, 0.f, 0.f}; for (int l = 0; l < n; ++l) { sums[0] += y[l+ 0] * ((int8_t)((q1[l] & 0xF) | ((qh[l] & kmask1) << 4)) - 32); sums[1] += y[l+32] * ((int8_t)((q2[l] & 0xF) | ((qh[l] & kmask2) << 2)) - 32); sums[2] += y[l+64] * ((int8_t)((q1[l] >> 4) | ((qh[l] & kmask3) << 0)) - 32); sums[3] += y[l+96] * ((int8_t)((q2[l] >> 4) | ((qh[l] & kmask4) >> 2)) - 32); } sumf += dall * (sums[0] * sc[0] + sums[1] * sc[2] + sums[2] * sc[4] + sums[3] * sc[6]); } const float tot = simd_sum(sumf); if (tiisg == 0) { dst[r1*ne0 + im*ne0*ne1 + row] = tot; } } [[host_name("kernel_mul_mv_q6_K_f32")]] kernel void kernel_mul_mv_q6_K_f32( device const void * src0, device const float * src1, device float * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant int64_t & ne0, constant int64_t & ne1, constant uint & r2, constant uint & r3, uint3 tgpig[[threadgroup_position_in_grid]], uint tiisg[[thread_index_in_simdgroup]], uint sgitg[[simdgroup_index_in_threadgroup]]) { kernel_mul_mv_q6_K_f32_impl(src0, src1, dst, ne00, ne01, ne02, ne10, ne12, ne0, ne1, r2, r3, nullptr, tgpig, tiisg, sgitg); } // ======================= "True" 2-bit void kernel_mul_mv_iq2_xxs_f32_impl( device const void * src0, device const float * src1, device float * dst, int64_t ne00, int64_t ne01, int64_t ne02, int64_t ne10, int64_t ne12, int64_t ne0, int64_t ne1, uint r2, uint r3, threadgroup int8_t * shared_values, uint3 tgpig, uint tiisg, uint sgitg) { const int nb = ne00/QK_K; const int r0 = tgpig.x; const int r1 = tgpig.y; const int im = tgpig.z; const int first_row = (r0 * N_SIMDGROUP + sgitg) * N_DST; const int ib_row = first_row * nb; const uint i12 = im%ne12; const uint i13 = im/ne12; const uint offset0 = (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02); device const block_iq2_xxs * x = (device const block_iq2_xxs *) src0 + ib_row + offset0; device const float * y = (device const float *) src1 + r1*ne10 + im*ne00*ne1; float yl[32]; float sumf[N_DST]={0.f}, all_sum; const int nb32 = nb * (QK_K / 32); threadgroup uint64_t * values = (threadgroup uint64_t *)shared_values; threadgroup uint8_t * shared_signs = (threadgroup uint8_t *)(values + 256); { int nval = 4; int pos = (32*sgitg + tiisg)*nval; for (int i = 0; i < nval; ++i) values[pos + i] = iq2xxs_grid[pos + i]; nval = 2; pos = (32*sgitg + tiisg)*nval; for (int i = 0; i < nval; ++i) shared_signs[pos+i] = ksigns_iq2xs[pos+i]; threadgroup_barrier(mem_flags::mem_threadgroup); } const int ix = tiisg; device const float * y4 = y + 32 * ix; for (int ib32 = ix; ib32 < nb32; ib32 += 32) { for (int i = 0; i < 32; ++i) { yl[i] = y4[i]; } const int ibl = ib32 / (QK_K / 32); const int ib = ib32 % (QK_K / 32); device const block_iq2_xxs * xr = x + ibl; device const uint16_t * q2 = xr->qs + 4 * ib; device const half * dh = &xr->d; for (int row = 0; row < N_DST; row++) { const float db = dh[0]; device const uint8_t * aux8 = (device const uint8_t *)q2; const uint32_t aux32 = q2[2] | (q2[3] << 16); const float d = db * (0.5f + (aux32 >> 28)); float sum = 0; for (int l = 0; l < 4; ++l) { const threadgroup uint8_t * grid = (const threadgroup uint8_t *)(values + aux8[l]); const uint8_t signs = shared_signs[(aux32 >> 7*l) & 127]; for (int j = 0; j < 8; ++j) { sum += yl[8*l + j] * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f); } } sumf[row] += d * sum; dh += nb*sizeof(block_iq2_xxs)/2; q2 += nb*sizeof(block_iq2_xxs)/2; } y4 += 32 * 32; } for (int row = 0; row < N_DST; ++row) { all_sum = simd_sum(sumf[row]); if (tiisg == 0) { dst[r1*ne0 + im*ne0*ne1 + first_row + row] = all_sum * 0.25f; } } } [[host_name("kernel_mul_mv_iq2_xxs_f32")]] kernel void kernel_mul_mv_iq2_xxs_f32( device const void * src0, device const float * src1, device float * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant int64_t & ne0, constant int64_t & ne1, constant uint & r2, constant uint & r3, threadgroup int8_t * shared_values [[threadgroup(0)]], uint3 tgpig[[threadgroup_position_in_grid]], uint tiisg[[thread_index_in_simdgroup]], uint sgitg[[simdgroup_index_in_threadgroup]]) { kernel_mul_mv_iq2_xxs_f32_impl(src0, src1, dst, ne00, ne01, ne02, ne10, ne12, ne0, ne1, r2, r3, shared_values, tgpig, tiisg, sgitg); } void kernel_mul_mv_iq2_xs_f32_impl( device const void * src0, device const float * src1, device float * dst, int64_t ne00, int64_t ne01, int64_t ne02, int64_t ne10, int64_t ne12, int64_t ne0, int64_t ne1, uint r2, uint r3, threadgroup int8_t * shared_values, uint3 tgpig, uint tiisg, uint sgitg) { const int nb = ne00/QK_K; const int r0 = tgpig.x; const int r1 = tgpig.y; const int im = tgpig.z; const int first_row = (r0 * N_SIMDGROUP + sgitg) * N_DST; const int ib_row = first_row * nb; const uint i12 = im%ne12; const uint i13 = im/ne12; const uint offset0 = (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02); device const block_iq2_xs * x = (device const block_iq2_xs *) src0 + ib_row + offset0; device const float * y = (device const float *) src1 + r1*ne10 + im*ne00*ne1; float yl[32]; float sumf[N_DST]={0.f}, all_sum; const int nb32 = nb * (QK_K / 32); threadgroup uint64_t * values = (threadgroup uint64_t *)shared_values; threadgroup uint8_t * shared_signs = (threadgroup uint8_t *)(values + 512); { int nval = 8; int pos = (32*sgitg + tiisg)*nval; for (int i = 0; i < nval; ++i) values[pos + i] = iq2xs_grid[pos + i]; nval = 2; pos = (32*sgitg + tiisg)*nval; for (int i = 0; i < nval; ++i) shared_signs[pos+i] = ksigns_iq2xs[pos+i]; threadgroup_barrier(mem_flags::mem_threadgroup); } const int ix = tiisg; device const float * y4 = y + 32 * ix; for (int ib32 = ix; ib32 < nb32; ib32 += 32) { for (int i = 0; i < 32; ++i) { yl[i] = y4[i]; } const int ibl = ib32 / (QK_K / 32); const int ib = ib32 % (QK_K / 32); device const block_iq2_xs * xr = x + ibl; device const uint16_t * q2 = xr->qs + 4 * ib; device const uint8_t * sc = xr->scales + ib; device const half * dh = &xr->d; for (int row = 0; row < N_DST; row++) { const float db = dh[0]; const uint8_t ls1 = sc[0] & 0xf; const uint8_t ls2 = sc[0] >> 4; const float d1 = db * (0.5f + ls1); const float d2 = db * (0.5f + ls2); float sum1 = 0, sum2 = 0; for (int l = 0; l < 2; ++l) { const threadgroup uint8_t * grid = (const threadgroup uint8_t *)(values + (q2[l] & 511)); const uint8_t signs = shared_signs[(q2[l] >> 9)]; for (int j = 0; j < 8; ++j) { sum1 += yl[8*l + j] * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f); } } for (int l = 2; l < 4; ++l) { const threadgroup uint8_t * grid = (const threadgroup uint8_t *)(values + (q2[l] & 511)); const uint8_t signs = shared_signs[(q2[l] >> 9)]; for (int j = 0; j < 8; ++j) { sum2 += yl[8*l + j] * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f); } } sumf[row] += d1 * sum1 + d2 * sum2; dh += nb*sizeof(block_iq2_xs)/2; q2 += nb*sizeof(block_iq2_xs)/2; sc += nb*sizeof(block_iq2_xs); } y4 += 32 * 32; } for (int row = 0; row < N_DST; ++row) { all_sum = simd_sum(sumf[row]); if (tiisg == 0) { dst[r1*ne0 + im*ne0*ne1 + first_row + row] = all_sum * 0.25f; } } } [[host_name("kernel_mul_mv_iq2_xs_f32")]] kernel void kernel_mul_mv_iq2_xs_f32( device const void * src0, device const float * src1, device float * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant int64_t & ne0, constant int64_t & ne1, constant uint & r2, constant uint & r3, threadgroup int8_t * shared_values [[threadgroup(0)]], uint3 tgpig[[threadgroup_position_in_grid]], uint tiisg[[thread_index_in_simdgroup]], uint sgitg[[simdgroup_index_in_threadgroup]]) { kernel_mul_mv_iq2_xs_f32_impl(src0, src1, dst, ne00, ne01, ne02, ne10, ne12, ne0, ne1, r2, r3, shared_values, tgpig, tiisg, sgitg); } void kernel_mul_mv_iq3_xxs_f32_impl( device const void * src0, device const float * src1, device float * dst, int64_t ne00, int64_t ne01, int64_t ne02, int64_t ne10, int64_t ne12, int64_t ne0, int64_t ne1, uint r2, uint r3, threadgroup int8_t * shared_values, uint3 tgpig, uint tiisg, uint sgitg) { const int nb = ne00/QK_K; const int r0 = tgpig.x; const int r1 = tgpig.y; const int im = tgpig.z; const int first_row = (r0 * N_SIMDGROUP + sgitg) * N_DST; const int ib_row = first_row * nb; const uint i12 = im%ne12; const uint i13 = im/ne12; const uint offset0 = (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02); device const block_iq3_xxs * x = (device const block_iq3_xxs *) src0 + ib_row + offset0; device const float * y = (device const float *) src1 + r1*ne10 + im*ne00*ne1; float yl[32]; float sumf[N_DST]={0.f}, all_sum; const int nb32 = nb * (QK_K / 32); threadgroup uint32_t * values = (threadgroup uint32_t *)shared_values; threadgroup uint8_t * shared_signs = (threadgroup uint8_t *)(values + 256); { int nval = 4; int pos = (32*sgitg + tiisg)*nval; for (int i = 0; i < nval; ++i) values[pos + i] = iq3xxs_grid[pos + i]; nval = 2; pos = (32*sgitg + tiisg)*nval; for (int i = 0; i < nval; ++i) shared_signs[pos+i] = ksigns_iq2xs[pos+i]; threadgroup_barrier(mem_flags::mem_threadgroup); } const int ix = tiisg; device const float * y4 = y + 32 * ix; for (int ib32 = ix; ib32 < nb32; ib32 += 32) { for (int i = 0; i < 32; ++i) { yl[i] = y4[i]; } const int ibl = ib32 / (QK_K / 32); const int ib = ib32 % (QK_K / 32); device const block_iq3_xxs * xr = x + ibl; device const uint8_t * q3 = xr->qs + 8 * ib; device const uint16_t * gas = (device const uint16_t *)(xr->qs + QK_K/4) + 2 * ib; device const half * dh = &xr->d; for (int row = 0; row < N_DST; row++) { const float db = dh[0]; const uint32_t aux32 = gas[0] | (gas[1] << 16); const float d = db * (0.5f + (aux32 >> 28)); float2 sum = {0}; for (int l = 0; l < 4; ++l) { const threadgroup uint8_t * grid1 = (const threadgroup uint8_t *)(values + q3[2*l+0]); const threadgroup uint8_t * grid2 = (const threadgroup uint8_t *)(values + q3[2*l+1]); const uint8_t signs = shared_signs[(aux32 >> 7*l) & 127]; for (int j = 0; j < 4; ++j) { sum[0] += yl[8*l + j + 0] * grid1[j] * (signs & kmask_iq2xs[j+0] ? -1.f : 1.f); sum[1] += yl[8*l + j + 4] * grid2[j] * (signs & kmask_iq2xs[j+4] ? -1.f : 1.f); } } sumf[row] += d * (sum[0] + sum[1]); dh += nb*sizeof(block_iq3_xxs)/2; q3 += nb*sizeof(block_iq3_xxs); gas += nb*sizeof(block_iq3_xxs)/2; } y4 += 32 * 32; } for (int row = 0; row < N_DST; ++row) { all_sum = simd_sum(sumf[row]); if (tiisg == 0) { dst[r1*ne0 + im*ne0*ne1 + first_row + row] = all_sum * 0.5f; } } } [[host_name("kernel_mul_mv_iq3_xxs_f32")]] kernel void kernel_mul_mv_iq3_xxs_f32( device const void * src0, device const float * src1, device float * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant int64_t & ne0, constant int64_t & ne1, constant uint & r2, constant uint & r3, threadgroup int8_t * shared_values [[threadgroup(0)]], uint3 tgpig[[threadgroup_position_in_grid]], uint tiisg[[thread_index_in_simdgroup]], uint sgitg[[simdgroup_index_in_threadgroup]]) { kernel_mul_mv_iq3_xxs_f32_impl(src0, src1, dst, ne00, ne01, ne02, ne10, ne12, ne0, ne1, r2, r3, shared_values, tgpig, tiisg, sgitg); } void kernel_mul_mv_iq3_s_f32_impl( device const void * src0, device const float * src1, device float * dst, int64_t ne00, int64_t ne01, int64_t ne02, int64_t ne10, int64_t ne12, int64_t ne0, int64_t ne1, uint r2, uint r3, threadgroup int8_t * shared_values, uint3 tgpig, uint tiisg, uint sgitg) { const int nb = ne00/QK_K; const int r0 = tgpig.x; const int r1 = tgpig.y; const int im = tgpig.z; const int first_row = (r0 * N_SIMDGROUP + sgitg) * N_DST; const int ib_row = first_row * nb; const uint i12 = im%ne12; const uint i13 = im/ne12; const uint offset0 = (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02); device const block_iq3_s * x = (device const block_iq3_s *) src0 + ib_row + offset0; device const float * y = (device const float *) src1 + r1*ne10 + im*ne00*ne1; float yl[32]; float sumf[N_DST]={0.f}, all_sum; const int nb32 = nb * (QK_K / 32); threadgroup uint32_t * values = (threadgroup uint32_t *)shared_values; { int nval = 8; int pos = (32*sgitg + tiisg)*nval; for (int i = 0; i < nval; ++i) values[pos + i] = iq3s_grid[pos + i]; threadgroup_barrier(mem_flags::mem_threadgroup); } const int ix = tiisg; device const float * y4 = y + 32 * ix; for (int ib32 = ix; ib32 < nb32; ib32 += 32) { for (int i = 0; i < 32; ++i) { yl[i] = y4[i]; } const int ibl = ib32 / (QK_K / 32); const int ib = ib32 % (QK_K / 32); device const block_iq3_s * xr = x + ibl; device const uint8_t * qs = xr->qs + 8 * ib; device const uint8_t * qh = xr->qh + ib; device const uint8_t * sc = xr->scales + (ib/2); device const uint8_t * signs = xr->signs + 4 * ib; device const half * dh = &xr->d; for (int row = 0; row < N_DST; row++) { const float db = dh[0]; const float d = db * (1 + 2*((sc[0] >> 4*(ib%2)) & 0xf)); float2 sum = {0}; for (int l = 0; l < 4; ++l) { const threadgroup uint32_t * table1 = qh[0] & kmask_iq2xs[2*l+0] ? values + 256 : values; const threadgroup uint32_t * table2 = qh[0] & kmask_iq2xs[2*l+1] ? values + 256 : values; const threadgroup uint8_t * grid1 = (const threadgroup uint8_t *)(table1 + qs[2*l+0]); const threadgroup uint8_t * grid2 = (const threadgroup uint8_t *)(table2 + qs[2*l+1]); for (int j = 0; j < 4; ++j) { sum[0] += yl[8*l + j + 0] * grid1[j] * select(1, -1, signs[l] & kmask_iq2xs[j+0]); sum[1] += yl[8*l + j + 4] * grid2[j] * select(1, -1, signs[l] & kmask_iq2xs[j+4]); } } sumf[row] += d * (sum[0] + sum[1]); dh += nb*sizeof(block_iq3_s)/2; qs += nb*sizeof(block_iq3_s); qh += nb*sizeof(block_iq3_s); sc += nb*sizeof(block_iq3_s); signs += nb*sizeof(block_iq3_s); } y4 += 32 * 32; } for (int row = 0; row < N_DST; ++row) { all_sum = simd_sum(sumf[row]); if (tiisg == 0) { dst[r1*ne0 + im*ne0*ne1 + first_row + row] = all_sum; } } } [[host_name("kernel_mul_mv_iq3_s_f32")]] kernel void kernel_mul_mv_iq3_s_f32( device const void * src0, device const float * src1, device float * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant int64_t & ne0, constant int64_t & ne1, constant uint & r2, constant uint & r3, threadgroup int8_t * shared_values [[threadgroup(0)]], uint3 tgpig[[threadgroup_position_in_grid]], uint tiisg[[thread_index_in_simdgroup]], uint sgitg[[simdgroup_index_in_threadgroup]]) { kernel_mul_mv_iq3_s_f32_impl(src0, src1, dst, ne00, ne01, ne02, ne10, ne12, ne0, ne1, r2, r3, shared_values, tgpig, tiisg, sgitg); } void kernel_mul_mv_iq2_s_f32_impl( device const void * src0, device const float * src1, device float * dst, int64_t ne00, int64_t ne01, int64_t ne02, int64_t ne10, int64_t ne12, int64_t ne0, int64_t ne1, uint r2, uint r3, threadgroup int8_t * shared_values, uint3 tgpig, uint tiisg, uint sgitg) { const int nb = ne00/QK_K; const int r0 = tgpig.x; const int r1 = tgpig.y; const int im = tgpig.z; const int first_row = (r0 * N_SIMDGROUP + sgitg) * N_DST; const int ib_row = first_row * nb; const uint i12 = im%ne12; const uint i13 = im/ne12; const uint offset0 = (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02); device const block_iq2_s * x = (device const block_iq2_s *) src0 + ib_row + offset0; device const float * y = (device const float *) src1 + r1*ne10 + im*ne00*ne1; float yl[32]; float sumf[N_DST]={0.f}, all_sum; const int nb32 = nb * (QK_K / 32); //threadgroup uint64_t * values = (threadgroup uint64_t *)shared_values; //{ // int nval = 32; // int pos = (32*sgitg + tiisg)*nval; // for (int i = 0; i < nval; ++i) values[pos + i] = iq2s_grid[pos + i]; // threadgroup_barrier(mem_flags::mem_threadgroup); //} const int ix = tiisg; device const float * y4 = y + 32 * ix; for (int ib32 = ix; ib32 < nb32; ib32 += 32) { for (int i = 0; i < 32; ++i) { yl[i] = y4[i]; } const int ibl = ib32 / (QK_K / 32); const int ib = ib32 % (QK_K / 32); device const block_iq2_s * xr = x + ibl; device const uint8_t * qs = xr->qs + 4 * ib; device const uint8_t * qh = xr->qh + ib; device const uint8_t * sc = xr->scales + ib; device const uint8_t * signs = qs + QK_K/8; device const half * dh = &xr->d; for (int row = 0; row < N_DST; row++) { const float db = dh[0]; const float d1 = db * (0.5f + (sc[0] & 0xf)); const float d2 = db * (0.5f + (sc[0] >> 4)); float2 sum = {0}; for (int l = 0; l < 2; ++l) { //const threadgroup uint8_t * grid1 = (const threadgroup uint8_t *)(values + (qs[l+0] | ((qh[0] << (8-2*l)) & 0x300))); //const threadgroup uint8_t * grid2 = (const threadgroup uint8_t *)(values + (qs[l+2] | ((qh[0] << (4-2*l)) & 0x300))); constant uint8_t * grid1 = (constant uint8_t *)(iq2s_grid + (qs[l+0] | ((qh[0] << (8-2*l)) & 0x300))); constant uint8_t * grid2 = (constant uint8_t *)(iq2s_grid + (qs[l+2] | ((qh[0] << (4-2*l)) & 0x300))); for (int j = 0; j < 8; ++j) { sum[0] += yl[8*l + j + 0] * grid1[j] * select(1, -1, signs[l+0] & kmask_iq2xs[j]); sum[1] += yl[8*l + j + 16] * grid2[j] * select(1, -1, signs[l+2] & kmask_iq2xs[j]); } } sumf[row] += d1 * sum[0] + d2 * sum[1]; dh += nb*sizeof(block_iq2_s)/2; qs += nb*sizeof(block_iq2_s); qh += nb*sizeof(block_iq2_s); sc += nb*sizeof(block_iq2_s); signs += nb*sizeof(block_iq2_s); } y4 += 32 * 32; } for (int row = 0; row < N_DST; ++row) { all_sum = simd_sum(sumf[row]); if (tiisg == 0) { dst[r1*ne0 + im*ne0*ne1 + first_row + row] = all_sum * 0.25f; } } } [[host_name("kernel_mul_mv_iq2_s_f32")]] kernel void kernel_mul_mv_iq2_s_f32( device const void * src0, device const float * src1, device float * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant int64_t & ne0, constant int64_t & ne1, constant uint & r2, constant uint & r3, threadgroup int8_t * shared_values [[threadgroup(0)]], uint3 tgpig[[threadgroup_position_in_grid]], uint tiisg[[thread_index_in_simdgroup]], uint sgitg[[simdgroup_index_in_threadgroup]]) { kernel_mul_mv_iq2_s_f32_impl(src0, src1, dst, ne00, ne01, ne02, ne10, ne12, ne0, ne1, r2, r3, shared_values, tgpig, tiisg, sgitg); } void kernel_mul_mv_iq1_s_f32_impl( device const void * src0, device const float * src1, device float * dst, int64_t ne00, int64_t ne01, int64_t ne02, int64_t ne10, int64_t ne12, int64_t ne0, int64_t ne1, uint r2, uint r3, threadgroup int8_t * shared_value, uint3 tgpig, uint tiisg, uint sgitg) { const int nb = ne00/QK_K; const int r0 = tgpig.x; const int r1 = tgpig.y; const int im = tgpig.z; const int first_row = (r0 * N_SIMDGROUP + sgitg) * N_DST; const int ib_row = first_row * nb; const uint i12 = im%ne12; const uint i13 = im/ne12; const uint offset0 = (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02); device const block_iq1_s * x = (device const block_iq1_s *) src0 + ib_row + offset0; device const float * y = (device const float *) src1 + r1*ne10 + im*ne00*ne1; float yl[32]; float sumf[N_DST]={0.f}, all_sum; const int nb32 = nb * (QK_K / 32); const int ix = tiisg; device const float * y4 = y + 32 * ix; for (int ib32 = ix; ib32 < nb32; ib32 += 32) { float sumy = 0; for (int i = 0; i < 32; ++i) { yl[i] = y4[i]; sumy += yl[i]; } const int ibl = ib32 / (QK_K / 32); const int ib = ib32 % (QK_K / 32); device const block_iq1_s * xr = x + ibl; device const uint8_t * qs = xr->qs + 4 * ib; device const uint16_t * qh = xr->qh + ib; device const half * dh = &xr->d; for (int row = 0; row < N_DST; row++) { constant uint8_t * grid1 = (constant uint8_t *)(iq1s_grid_gpu + (qs[0] | ((qh[0] << 8) & 0x700))); constant uint8_t * grid2 = (constant uint8_t *)(iq1s_grid_gpu + (qs[1] | ((qh[0] << 5) & 0x700))); constant uint8_t * grid3 = (constant uint8_t *)(iq1s_grid_gpu + (qs[2] | ((qh[0] << 2) & 0x700))); constant uint8_t * grid4 = (constant uint8_t *)(iq1s_grid_gpu + (qs[3] | ((qh[0] >> 1) & 0x700))); float sum = 0; for (int j = 0; j < 4; ++j) { sum += yl[j+ 0] * (grid1[j] & 0xf) + yl[j+ 4] * (grid1[j] >> 4) + yl[j+ 8] * (grid2[j] & 0xf) + yl[j+12] * (grid2[j] >> 4) + yl[j+16] * (grid3[j] & 0xf) + yl[j+20] * (grid3[j] >> 4) + yl[j+24] * (grid4[j] & 0xf) + yl[j+28] * (grid4[j] >> 4); } sumf[row] += (float)dh[0] * (sum + sumy * (qh[0] & 0x8000 ? -1 - IQ1S_DELTA : -1 + IQ1S_DELTA)) * (2*((qh[0] >> 12) & 7) + 1); dh += nb*sizeof(block_iq1_s)/2; qs += nb*sizeof(block_iq1_s); qh += nb*sizeof(block_iq1_s)/2; } y4 += 32 * 32; } for (int row = 0; row < N_DST; ++row) { all_sum = simd_sum(sumf[row]); if (tiisg == 0) { dst[r1*ne0 + im*ne0*ne1 + first_row + row] = all_sum; } } } void kernel_mul_mv_iq1_m_f32_impl( device const void * src0, device const float * src1, device float * dst, int64_t ne00, int64_t ne01, int64_t ne02, int64_t ne10, int64_t ne12, int64_t ne0, int64_t ne1, uint r2, uint r3, threadgroup int8_t * shared_value, uint3 tgpig, uint tiisg, uint sgitg) { const int nb = ne00/QK_K; const int r0 = tgpig.x; const int r1 = tgpig.y; const int im = tgpig.z; const int first_row = (r0 * N_SIMDGROUP + sgitg) * N_DST; const int ib_row = first_row * nb; const uint i12 = im%ne12; const uint i13 = im/ne12; const uint offset0 = (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02); device const block_iq1_m * x = (device const block_iq1_m *) src0 + ib_row + offset0; device const float * y = (device const float *) src1 + r1*ne10 + im*ne00*ne1; float yl[32]; float sumf[N_DST]={0.f}, all_sum; const int nb32 = nb * (QK_K / 32); const int ix = tiisg; device const float * y4 = y + 32 * ix; iq1m_scale_t scale; for (int ib32 = ix; ib32 < nb32; ib32 += 32) { float4 sumy = {0.f}; for (int i = 0; i < 8; ++i) { yl[i+ 0] = y4[i+ 0]; sumy[0] += yl[i+ 0]; yl[i+ 8] = y4[i+ 8]; sumy[1] += yl[i+ 8]; yl[i+16] = y4[i+16]; sumy[2] += yl[i+16]; yl[i+24] = y4[i+24]; sumy[3] += yl[i+24]; } const int ibl = ib32 / (QK_K / 32); const int ib = ib32 % (QK_K / 32); device const block_iq1_m * xr = x + ibl; device const uint8_t * qs = xr->qs + 4 * ib; device const uint8_t * qh = xr->qh + 2 * ib; device const uint16_t * sc = (device const uint16_t *)xr->scales; for (int row = 0; row < N_DST; row++) { scale.u16 = (sc[0] >> 12) | ((sc[1] >> 8) & 0x00f0) | ((sc[2] >> 4) & 0x0f00) | (sc[3] & 0xf000); constant uint8_t * grid1 = (constant uint8_t *)(iq1s_grid_gpu + (qs[0] | ((qh[0] << 8) & 0x700))); constant uint8_t * grid2 = (constant uint8_t *)(iq1s_grid_gpu + (qs[1] | ((qh[0] << 4) & 0x700))); constant uint8_t * grid3 = (constant uint8_t *)(iq1s_grid_gpu + (qs[2] | ((qh[1] << 8) & 0x700))); constant uint8_t * grid4 = (constant uint8_t *)(iq1s_grid_gpu + (qs[3] | ((qh[1] << 4) & 0x700))); float2 sum = {0.f}; for (int j = 0; j < 4; ++j) { sum[0] += yl[j+ 0] * (grid1[j] & 0xf) + yl[j+ 4] * (grid1[j] >> 4) + yl[j+ 8] * (grid2[j] & 0xf) + yl[j+12] * (grid2[j] >> 4); sum[1] += yl[j+16] * (grid3[j] & 0xf) + yl[j+20] * (grid3[j] >> 4) + yl[j+24] * (grid4[j] & 0xf) + yl[j+28] * (grid4[j] >> 4); } const float delta1 = sumy[0] * (qh[0] & 0x08 ? -1 - IQ1M_DELTA : -1 + IQ1M_DELTA) + sumy[1] * (qh[0] & 0x80 ? -1 - IQ1M_DELTA : -1 + IQ1M_DELTA); const float delta2 = sumy[2] * (qh[1] & 0x08 ? -1 - IQ1M_DELTA : -1 + IQ1M_DELTA) + sumy[3] * (qh[1] & 0x80 ? -1 - IQ1M_DELTA : -1 + IQ1M_DELTA); sumf[row] += (float)scale.f16 * ((sum[0] + delta1) * (2*((sc[ib/2] >> (6*(ib%2)+0)) & 7) + 1) + (sum[1] + delta2) * (2*((sc[ib/2] >> (6*(ib%2)+3)) & 7) + 1)); sc += nb*sizeof(block_iq1_m)/2; qs += nb*sizeof(block_iq1_m); qh += nb*sizeof(block_iq1_m); } y4 += 32 * 32; } for (int row = 0; row < N_DST; ++row) { all_sum = simd_sum(sumf[row]); if (tiisg == 0) { dst[r1*ne0 + im*ne0*ne1 + first_row + row] = all_sum; } } } void kernel_mul_mv_iq4_nl_f32_impl( device const void * src0, device const float * src1, device float * dst, int64_t ne00, int64_t ne01, int64_t ne02, int64_t ne10, int64_t ne12, int64_t ne0, int64_t ne1, uint r2, uint r3, threadgroup int8_t * shared_values_i8, uint3 tgpig, uint tiisg, uint sgitg) { threadgroup float * shared_values = (threadgroup float *)shared_values_i8; const int nb = ne00/QK4_NL; const int r0 = tgpig.x; const int r1 = tgpig.y; const int im = tgpig.z; const int first_row = (r0 * 2 + sgitg) * 2; const int ib_row = first_row * nb; const uint i12 = im%ne12; const uint i13 = im/ne12; const uint offset0 = (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02); device const block_iq4_nl * x = (device const block_iq4_nl *) src0 + ib_row + offset0; device const float * y = (device const float *) src1 + r1*ne10 + im*ne00*ne1; const int ix = tiisg/2; // 0...15 const int it = tiisg%2; // 0 or 1 shared_values[tiisg] = kvalues_iq4nl_f[tiisg%16]; threadgroup_barrier(mem_flags::mem_threadgroup); float4 yl[4]; float sumf[2]={0.f}, all_sum; device const float * yb = y + ix * QK4_NL + it * 8; uint32_t aux32[2]; thread const uint8_t * q8 = (thread const uint8_t *)aux32; float4 qf1, qf2; for (int ib = ix; ib < nb; ib += 16) { device const float4 * y4 = (device const float4 *)yb; yl[0] = y4[0]; yl[1] = y4[4]; yl[2] = y4[1]; yl[3] = y4[5]; for (int row = 0; row < 2 && first_row + row < ne01; ++row) { device const block_iq4_nl & xb = x[row*nb + ib]; device const uint16_t * q4 = (device const uint16_t *)(xb.qs + 8*it); float4 acc1 = {0.f}, acc2 = {0.f}; aux32[0] = q4[0] | (q4[1] << 16); aux32[1] = (aux32[0] >> 4) & 0x0f0f0f0f; aux32[0] &= 0x0f0f0f0f; qf1 = {shared_values[q8[0]], shared_values[q8[1]], shared_values[q8[2]], shared_values[q8[3]]}; qf2 = {shared_values[q8[4]], shared_values[q8[5]], shared_values[q8[6]], shared_values[q8[7]]}; acc1 += yl[0] * qf1; acc2 += yl[1] * qf2; aux32[0] = q4[2] | (q4[3] << 16); aux32[1] = (aux32[0] >> 4) & 0x0f0f0f0f; aux32[0] &= 0x0f0f0f0f; qf1 = {shared_values[q8[0]], shared_values[q8[1]], shared_values[q8[2]], shared_values[q8[3]]}; qf2 = {shared_values[q8[4]], shared_values[q8[5]], shared_values[q8[6]], shared_values[q8[7]]}; acc1 += yl[2] * qf1; acc2 += yl[3] * qf2; acc1 += acc2; sumf[row] += (float)xb.d * (acc1[0] + acc1[1] + acc1[2] + acc1[3]); } yb += 16 * QK4_NL; } for (int row = 0; row < 2 && first_row + row < ne01; ++row) { all_sum = simd_sum(sumf[row]); if (tiisg == 0) { dst[r1*ne0 + im*ne0*ne1 + first_row + row] = all_sum; } } } void kernel_mul_mv_iq4_xs_f32_impl( device const void * src0, device const float * src1, device float * dst, int64_t ne00, int64_t ne01, int64_t ne02, int64_t ne10, int64_t ne12, int64_t ne0, int64_t ne1, uint r2, uint r3, threadgroup int8_t * shared_values_i8, uint3 tgpig, uint tiisg, uint sgitg) { threadgroup float * shared_values = (threadgroup float *)shared_values_i8; const int nb = ne00/QK_K; const int r0 = tgpig.x; const int r1 = tgpig.y; const int im = tgpig.z; const int first_row = (r0 * 2 + sgitg) * 2; const int ib_row = first_row * nb; const uint i12 = im%ne12; const uint i13 = im/ne12; const uint offset0 = (i12/r2)*(nb*ne01) + (i13/r3)*(nb*ne01*ne02); device const block_iq4_xs * x = (device const block_iq4_xs *) src0 + ib_row + offset0; device const float * y = (device const float *) src1 + r1*ne10 + im*ne00*ne1; const int ix = tiisg/16; // 0 or 1 const int it = tiisg%16; // 0...15 const int ib = it/2; const int il = it%2; shared_values[tiisg] = kvalues_iq4nl_f[tiisg%16]; threadgroup_barrier(mem_flags::mem_threadgroup); float4 yl[4]; float sumf[2]={0.f}, all_sum; device const float * yb = y + ix * QK_K + ib * 32 + il * 8; uint32_t aux32[2]; thread const uint8_t * q8 = (thread const uint8_t *)aux32; float4 qf1, qf2; for (int ibl = ix; ibl < nb; ibl += 2) { device const float4 * y4 = (device const float4 *)yb; yl[0] = y4[0]; yl[1] = y4[4]; yl[2] = y4[1]; yl[3] = y4[5]; for (int row = 0; row < 2; ++row) { device const block_iq4_xs & xb = x[row*nb + ibl]; device const uint32_t * q4 = (device const uint32_t *)(xb.qs + 16*ib + 8*il); float4 acc1 = {0.f}, acc2 = {0.f}; aux32[0] = q4[0] & 0x0f0f0f0f; aux32[1] = (q4[0] >> 4) & 0x0f0f0f0f; qf1 = {shared_values[q8[0]], shared_values[q8[1]], shared_values[q8[2]], shared_values[q8[3]]}; qf2 = {shared_values[q8[4]], shared_values[q8[5]], shared_values[q8[6]], shared_values[q8[7]]}; acc1 += yl[0] * qf1; acc2 += yl[1] * qf2; aux32[0] = q4[1] & 0x0f0f0f0f; aux32[1] = (q4[1] >> 4) & 0x0f0f0f0f; qf1 = {shared_values[q8[0]], shared_values[q8[1]], shared_values[q8[2]], shared_values[q8[3]]}; qf2 = {shared_values[q8[4]], shared_values[q8[5]], shared_values[q8[6]], shared_values[q8[7]]}; acc1 += yl[2] * qf1; acc2 += yl[3] * qf2; acc1 += acc2; const int ls = (((xb.scales_l[ib/2] >> 4*(ib%2)) & 0xf) | (((xb.scales_h >> 2*ib) & 3) << 4)) - 32; sumf[row] += (float)xb.d * ls * (acc1[0] + acc1[1] + acc1[2] + acc1[3]); } yb += 2 * QK_K; } for (int row = 0; row < 2; ++row) { all_sum = simd_sum(sumf[row]); if (tiisg == 0) { dst[r1*ne0 + im*ne0*ne1 + first_row + row] = all_sum; } } } [[host_name("kernel_mul_mv_iq1_s_f32")]] kernel void kernel_mul_mv_iq1_s_f32( device const void * src0, device const float * src1, device float * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant int64_t & ne0, constant int64_t & ne1, constant uint & r2, constant uint & r3, uint3 tgpig[[threadgroup_position_in_grid]], uint tiisg[[thread_index_in_simdgroup]], uint sgitg[[simdgroup_index_in_threadgroup]]) { kernel_mul_mv_iq1_s_f32_impl(src0, src1, dst, ne00, ne01, ne02, ne10, ne12, ne0, ne1, r2, r3, nullptr, tgpig, tiisg, sgitg); } [[host_name("kernel_mul_mv_iq1_m_f32")]] kernel void kernel_mul_mv_iq1_m_f32( device const void * src0, device const float * src1, device float * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant int64_t & ne0, constant int64_t & ne1, constant uint & r2, constant uint & r3, uint3 tgpig[[threadgroup_position_in_grid]], uint tiisg[[thread_index_in_simdgroup]], uint sgitg[[simdgroup_index_in_threadgroup]]) { kernel_mul_mv_iq1_m_f32_impl(src0, src1, dst, ne00, ne01, ne02, ne10, ne12, ne0, ne1, r2, r3, nullptr, tgpig, tiisg, sgitg); } [[host_name("kernel_mul_mv_iq4_nl_f32")]] kernel void kernel_mul_mv_iq4_nl_f32( device const void * src0, device const float * src1, device float * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant int64_t & ne0, constant int64_t & ne1, constant uint & r2, constant uint & r3, threadgroup int8_t * shared_values [[threadgroup(0)]], uint3 tgpig[[threadgroup_position_in_grid]], uint tiisg[[thread_index_in_simdgroup]], uint sgitg[[simdgroup_index_in_threadgroup]]) { kernel_mul_mv_iq4_nl_f32_impl(src0, src1, dst, ne00, ne01, ne02, ne10, ne12, ne0, ne1, r2, r3, shared_values, tgpig, tiisg, sgitg); } [[host_name("kernel_mul_mv_iq4_xs_f32")]] kernel void kernel_mul_mv_iq4_xs_f32( device const void * src0, device const float * src1, device float * dst, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant int64_t & ne0, constant int64_t & ne1, constant uint & r2, constant uint & r3, threadgroup int8_t * shared_values [[threadgroup(0)]], uint3 tgpig[[threadgroup_position_in_grid]], uint tiisg[[thread_index_in_simdgroup]], uint sgitg[[simdgroup_index_in_threadgroup]]) { kernel_mul_mv_iq4_xs_f32_impl(src0, src1, dst, ne00, ne01, ne02, ne10, ne12, ne0, ne1, r2, r3, shared_values, tgpig, tiisg, sgitg); } //============================= templates and their specializations ============================= // NOTE: this is not dequantizing - we are simply fitting the template template <typename type4x4> void dequantize_f32(device const float4x4 * src, short il, thread type4x4 & reg) { float4x4 temp = *(((device float4x4 *)src)); for (int i = 0; i < 16; i++){ reg[i/4][i%4] = temp[i/4][i%4]; } } template <typename type4x4> void dequantize_f16(device const half4x4 * src, short il, thread type4x4 & reg) { half4x4 temp = *(((device half4x4 *)src)); for (int i = 0; i < 16; i++){ reg[i/4][i%4] = temp[i/4][i%4]; } } #if defined(__HAVE_BFLOAT__) template <typename type4x4> void dequantize_bf16(device const bfloat4x4 * src, short il, thread type4x4 & reg) { reg = (type4x4)(*src); } #endif template <typename type4x4> void dequantize_q4_0(device const block_q4_0 *xb, short il, thread type4x4 & reg) { device const uint16_t * qs = ((device const uint16_t *)xb + 1); const float d1 = il ? (xb->d / 16.h) : xb->d; const float d2 = d1 / 256.f; const float md = -8.h * xb->d; const ushort mask0 = il ? 0x00F0 : 0x000F; const ushort mask1 = mask0 << 8; for (int i=0;i<8;i++) { reg[i/2][2*(i%2)+0] = d1 * (qs[i] & mask0) + md; reg[i/2][2*(i%2)+1] = d2 * (qs[i] & mask1) + md; } } template <typename type4x4> void dequantize_q4_1(device const block_q4_1 *xb, short il, thread type4x4 & reg) { device const uint16_t * qs = ((device const uint16_t *)xb + 2); const float d1 = il ? (xb->d / 16.h) : xb->d; const float d2 = d1 / 256.f; const float m = xb->m; const ushort mask0 = il ? 0x00F0 : 0x000F; const ushort mask1 = mask0 << 8; for (int i=0;i<8;i++) { reg[i/2][2*(i%2)+0] = ((qs[i] & mask0) * d1) + m; reg[i/2][2*(i%2)+1] = ((qs[i] & mask1) * d2) + m; } } template <typename type4x4> void dequantize_q5_0(device const block_q5_0 *xb, short il, thread type4x4 & reg) { device const uint16_t * qs = ((device const uint16_t *)xb + 3); const float d = xb->d; const float md = -16.h * xb->d; const ushort mask = il ? 0x00F0 : 0x000F; const uint32_t qh = *((device const uint32_t *)xb->qh); const int x_mv = il ? 4 : 0; const int gh_mv = il ? 12 : 0; const int gh_bk = il ? 0 : 4; for (int i = 0; i < 8; i++) { // extract the 5-th bits for x0 and x1 const uint8_t xh_0 = ((qh >> (gh_mv + 2*i )) << gh_bk) & 0x10; const uint8_t xh_1 = ((qh >> (gh_mv + 2*i+1)) << gh_bk) & 0x10; // combine the 4-bits from qs with the 5th bit const int32_t x0 = ((((qs[i] ) & mask) >> x_mv) | xh_0); const int32_t x1 = ((((qs[i] >> 8) & mask) >> x_mv) | xh_1); reg[i/2][2*(i%2)+0] = d * x0 + md; reg[i/2][2*(i%2)+1] = d * x1 + md; } } template <typename type4x4> void dequantize_q5_1(device const block_q5_1 *xb, short il, thread type4x4 & reg) { device const uint16_t * qs = ((device const uint16_t *)xb + 4); const float d = xb->d; const float m = xb->m; const ushort mask = il ? 0x00F0 : 0x000F; const uint32_t qh = *((device const uint32_t *)xb->qh); const int x_mv = il ? 4 : 0; const int gh_mv = il ? 12 : 0; const int gh_bk = il ? 0 : 4; for (int i = 0; i < 8; i++) { // extract the 5-th bits for x0 and x1 const uint8_t xh_0 = ((qh >> (gh_mv + 2*i )) << gh_bk) & 0x10; const uint8_t xh_1 = ((qh >> (gh_mv + 2*i+1)) << gh_bk) & 0x10; // combine the 4-bits from qs with the 5th bit const int32_t x0 = ((((qs[i] ) & mask) >> x_mv) | xh_0); const int32_t x1 = ((((qs[i] >> 8) & mask) >> x_mv) | xh_1); reg[i/2][2*(i%2)+0] = d * x0 + m; reg[i/2][2*(i%2)+1] = d * x1 + m; } } template <typename type4x4> void dequantize_q8_0(device const block_q8_0 *xb, short il, thread type4x4 & reg) { device const int8_t * qs = ((device const int8_t *)xb->qs); const half d = xb->d; for (int i = 0; i < 16; i++) { reg[i/4][i%4] = (qs[i + 16*il] * d); } } template <typename type4x4> void dequantize_q2_K(device const block_q2_K *xb, short il, thread type4x4 & reg) { const float d = xb->d; const float min = xb->dmin; device const uint8_t * q = (device const uint8_t *)xb->qs; float dl, ml; uint8_t sc = xb->scales[il]; q = q + 32*(il/8) + 16*(il&1); il = (il/2)%4; half coef = il>1 ? (il>2 ? 1/64.h : 1/16.h) : (il>0 ? 1/4.h : 1.h); uchar mask = il>1 ? (il>2 ? 192 : 48) : (il>0 ? 12 : 3); dl = d * (sc & 0xF) * coef, ml = min * (sc >> 4); for (int i = 0; i < 16; ++i) { reg[i/4][i%4] = dl * (q[i] & mask) - ml; } } template <typename type4x4> void dequantize_q3_K(device const block_q3_K *xb, short il, thread type4x4 & reg) { const half d_all = xb->d; device const uint8_t * q = (device const uint8_t *)xb->qs; device const uint8_t * h = (device const uint8_t *)xb->hmask; device const int8_t * scales = (device const int8_t *)xb->scales; q = q + 32 * (il/8) + 16 * (il&1); h = h + 16 * (il&1); uint8_t m = 1 << (il/2); uint16_t kmask1 = (il/4)>1 ? ((il/4)>2 ? 192 : 48) : \ ((il/4)>0 ? 12 : 3); uint16_t kmask2 = il/8 ? 0xF0 : 0x0F; uint16_t scale_2 = scales[il%8], scale_1 = scales[8 + il%4]; int16_t dl_int = (il/4)&1 ? (scale_2&kmask2) | ((scale_1&kmask1) << 2) : (scale_2&kmask2) | ((scale_1&kmask1) << 4); float dl = il<8 ? d_all * (dl_int - 32.f) : d_all * (dl_int / 16.f - 32.f); const float ml = 4.f * dl; il = (il/2) & 3; const half coef = il>1 ? (il>2 ? 1/64.h : 1/16.h) : (il>0 ? 1/4.h : 1.h); const uint8_t mask = il>1 ? (il>2 ? 192 : 48) : (il>0 ? 12 : 3); dl *= coef; for (int i = 0; i < 16; ++i) { reg[i/4][i%4] = dl * (q[i] & mask) - (h[i] & m ? 0 : ml); } } static inline uchar2 get_scale_min_k4_just2(int j, int k, device const uchar * q) { return j < 4 ? uchar2{uchar(q[j+0+k] & 63), uchar(q[j+4+k] & 63)} : uchar2{uchar((q[j+4+k] & 0xF) | ((q[j-4+k] & 0xc0) >> 2)), uchar((q[j+4+k] >> 4) | ((q[j-0+k] & 0xc0) >> 2))}; } template <typename type4x4> void dequantize_q4_K(device const block_q4_K *xb, short il, thread type4x4 & reg) { device const uchar * q = xb->qs; short is = (il/4) * 2; q = q + (il/4) * 32 + 16 * (il&1); il = il & 3; const uchar2 sc = get_scale_min_k4_just2(is, il/2, xb->scales); const float d = il < 2 ? xb->d : xb->d / 16.h; const float min = xb->dmin; const float dl = d * sc[0]; const float ml = min * sc[1]; const ushort mask = il<2 ? 0x0F : 0xF0; for (int i = 0; i < 16; ++i) { reg[i/4][i%4] = dl * (q[i] & mask) - ml; } } template <typename type4x4> void dequantize_q5_K(device const block_q5_K *xb, short il, thread type4x4 & reg) { device const uint8_t * q = xb->qs; device const uint8_t * qh = xb->qh; short is = (il/4) * 2; q = q + 32 * (il/4) + 16 * (il&1); qh = qh + 16 * (il&1); uint8_t ul = 1 << (il/2); il = il & 3; const uchar2 sc = get_scale_min_k4_just2(is, il/2, xb->scales); const float d = il < 2 ? xb->d : xb->d / 16.f; const float min = xb->dmin; const float dl = d * sc[0]; const float ml = min * sc[1]; const ushort mask = il<2 ? 0x0F : 0xF0; const float qh_val = il<2 ? 16.f : 256.f; for (int i = 0; i < 16; ++i) { reg[i/4][i%4] = dl * ((q[i] & mask) + (qh[i] & ul ? qh_val : 0)) - ml; } } template <typename type4x4> void dequantize_q6_K(device const block_q6_K *xb, short il, thread type4x4 & reg) { const half d_all = xb->d; device const uint8_t * ql = (device const uint8_t *)xb->ql; device const uint8_t * qh = (device const uint8_t *)xb->qh; device const int8_t * scales = (device const int8_t *)xb->scales; ql = ql + 64*(il/8) + 32*((il/2)&1) + 16*(il&1); qh = qh + 32*(il/8) + 16*(il&1); float sc = scales[(il%2) + 2 * ((il/2))]; il = (il/2) & 3; const uint16_t kmask1 = il>1 ? (il>2 ? 192 : 48) : (il>0 ? 12 : 3); const uint16_t kmask2 = il>1 ? 0xF0 : 0x0F; const float coef = il>1 ? 1.f/16.f : 1.f; const float ml = d_all * sc * 32.f; const float dl = d_all * sc * coef; for (int i = 0; i < 16; ++i) { const half q = il&1 ? ((ql[i] & kmask2) | ((qh[i] & kmask1) << 2)) : ((ql[i] & kmask2) | ((qh[i] & kmask1) << 4)); reg[i/4][i%4] = dl * q - ml; } } template <typename type4x4> void dequantize_iq2_xxs(device const block_iq2_xxs * xb, short il, thread type4x4 & reg) { // il is 0...15 for QK_K = 256 => index of block of 32 is il/2 const float d = xb->d; const int ib32 = il/2; il = il%2; // il = 0 or 1. il = 0 processes the first 16 quants in a block of 32, il = 1 the second 16 // each block of 32 needs 2 uint32_t's for the quants & scale, so 4 uint16_t's. device const uint16_t * q2 = xb->qs + 4*ib32; const uint32_t aux32_g = q2[0] | (q2[1] << 16); const uint32_t aux32_s = q2[2] | (q2[3] << 16); thread const uint8_t * aux8 = (thread const uint8_t *)&aux32_g; const float dl = d * (0.5f + (aux32_s >> 28)) * 0.25f; constant uint8_t * grid = (constant uint8_t *)(iq2xxs_grid + aux8[2*il+0]); uint8_t signs = ksigns_iq2xs[(aux32_s >> 14*il) & 127]; for (int i = 0; i < 8; ++i) { reg[i/4][i%4] = dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f); } grid = (constant uint8_t *)(iq2xxs_grid + aux8[2*il+1]); signs = ksigns_iq2xs[(aux32_s >> (14*il+7)) & 127]; for (int i = 0; i < 8; ++i) { reg[2+i/4][i%4] = dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f); } } template <typename type4x4> void dequantize_iq2_xs(device const block_iq2_xs * xb, short il, thread type4x4 & reg) { // il is 0...15 for QK_K = 256 => index of block of 32 is il/2 const float d = xb->d; const int ib32 = il/2; il = il%2; // il = 0 or 1. il = 0 processes the first 16 quants in a block of 32, il = 1 the second 16 device const uint16_t * q2 = xb->qs + 4*ib32; const float dl = d * (0.5f + ((xb->scales[ib32] >> 4*il) & 0xf)) * 0.25f; constant uint8_t * grid = (constant uint8_t *)(iq2xs_grid + (q2[2*il+0] & 511)); uint8_t signs = ksigns_iq2xs[q2[2*il+0] >> 9]; for (int i = 0; i < 8; ++i) { reg[i/4][i%4] = dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f); } grid = (constant uint8_t *)(iq2xs_grid + (q2[2*il+1] & 511)); signs = ksigns_iq2xs[q2[2*il+1] >> 9]; for (int i = 0; i < 8; ++i) { reg[2+i/4][i%4] = dl * grid[i] * (signs & kmask_iq2xs[i] ? -1.f : 1.f); } } template <typename type4x4> void dequantize_iq3_xxs(device const block_iq3_xxs * xb, short il, thread type4x4 & reg) { // il is 0...15 for QK_K = 256 => index of block of 32 is il/2 const float d = xb->d; const int ib32 = il/2; il = il%2; // il = 0 or 1. il = 0 processes the first 16 quants in a block of 32, il = 1 the second 16 device const uint8_t * q3 = xb->qs + 8*ib32; device const uint16_t * gas = (device const uint16_t *)(xb->qs + QK_K/4) + 2*ib32; const uint32_t aux32 = gas[0] | (gas[1] << 16); const float dl = d * (0.5f + (aux32 >> 28)) * 0.5f; constant uint8_t * grid1 = (constant uint8_t *)(iq3xxs_grid + q3[4*il+0]); constant uint8_t * grid2 = (constant uint8_t *)(iq3xxs_grid + q3[4*il+1]); uint8_t signs = ksigns_iq2xs[(aux32 >> 14*il) & 127]; for (int i = 0; i < 4; ++i) { reg[0][i] = dl * grid1[i] * (signs & kmask_iq2xs[i+0] ? -1.f : 1.f); reg[1][i] = dl * grid2[i] * (signs & kmask_iq2xs[i+4] ? -1.f : 1.f); } grid1 = (constant uint8_t *)(iq3xxs_grid + q3[4*il+2]); grid2 = (constant uint8_t *)(iq3xxs_grid + q3[4*il+3]); signs = ksigns_iq2xs[(aux32 >> (14*il+7)) & 127]; for (int i = 0; i < 4; ++i) { reg[2][i] = dl * grid1[i] * (signs & kmask_iq2xs[i+0] ? -1.f : 1.f); reg[3][i] = dl * grid2[i] * (signs & kmask_iq2xs[i+4] ? -1.f : 1.f); } } template <typename type4x4> void dequantize_iq3_s(device const block_iq3_s * xb, short il, thread type4x4 & reg) { // il is 0...15 for QK_K = 256 => index of block of 32 is il/2 const float d = xb->d; const int ib32 = il/2; il = il%2; // il = 0 or 1. il = 0 processes the first 16 quants in a block of 32, il = 1 the second 16 device const uint8_t * qs = xb->qs + 8*ib32; device const uint8_t * signs = xb->signs + 4*ib32 + 2*il; const uint8_t qh = xb->qh[ib32] >> 4*il; const float dl = d * (1 + 2*((xb->scales[ib32/2] >> 4*(ib32%2)) & 0xf)); constant uint8_t * grid1 = (constant uint8_t *)(iq3s_grid + (qs[4*il+0] | ((qh << 8) & 256))); constant uint8_t * grid2 = (constant uint8_t *)(iq3s_grid + (qs[4*il+1] | ((qh << 7) & 256))); for (int i = 0; i < 4; ++i) { reg[0][i] = dl * grid1[i] * select(1, -1, signs[0] & kmask_iq2xs[i+0]); reg[1][i] = dl * grid2[i] * select(1, -1, signs[0] & kmask_iq2xs[i+4]); } grid1 = (constant uint8_t *)(iq3s_grid + (qs[4*il+2] | ((qh << 6) & 256))); grid2 = (constant uint8_t *)(iq3s_grid + (qs[4*il+3] | ((qh << 5) & 256))); for (int i = 0; i < 4; ++i) { reg[2][i] = dl * grid1[i] * select(1, -1, signs[1] & kmask_iq2xs[i+0]); reg[3][i] = dl * grid2[i] * select(1, -1, signs[1] & kmask_iq2xs[i+4]); } } template <typename type4x4> void dequantize_iq2_s(device const block_iq2_s * xb, short il, thread type4x4 & reg) { // il is 0...15 for QK_K = 256 => index of block of 32 is il/2 const float d = xb->d; const int ib32 = il/2; il = il%2; // il = 0 or 1. il = 0 processes the first 16 quants in a block of 32, il = 1 the second 16 device const uint8_t * qs = xb->qs + 4*ib32 + 2*il; device const uint8_t * signs = qs + QK_K/8; const uint8_t qh = xb->qh[ib32] >> 4*il; const float dl = d * (0.5f + ((xb->scales[ib32] >> 4*il) & 0xf)) * 0.25f; constant uint8_t * grid1 = (constant uint8_t *)(iq2s_grid + (qs[0] | ((qh << 8) & 0x300))); constant uint8_t * grid2 = (constant uint8_t *)(iq2s_grid + (qs[1] | ((qh << 6) & 0x300))); for (int i = 0; i < 8; ++i) { reg[i/4+0][i%4] = dl * grid1[i] * select(1, -1, signs[0] & kmask_iq2xs[i]); reg[i/4+2][i%4] = dl * grid2[i] * select(1, -1, signs[1] & kmask_iq2xs[i]); } } template <typename type4x4> void dequantize_iq1_s(device const block_iq1_s * xb, short il, thread type4x4 & reg) { // il is 0...15 for QK_K = 256 => index of block of 32 is il/2 const int ib32 = il/2; il = il%2; const float d = xb->d; device const uint8_t * qs = xb->qs + 4*ib32 + 2*il; device const uint16_t * qh = xb->qh; const float dl = d * (2*((qh[ib32] >> 12) & 7) + 1); const float ml = dl * (qh[ib32] & 0x8000 ? -1 - IQ1S_DELTA : -1 + IQ1S_DELTA); const uint16_t h = qh[ib32] >> 6*il; constant uint8_t * grid1 = (constant uint8_t *)(iq1s_grid_gpu + (qs[0] | ((h << 8) & 0x700))); constant uint8_t * grid2 = (constant uint8_t *)(iq1s_grid_gpu + (qs[1] | ((h << 5) & 0x700))); for (int i = 0; i < 4; ++i) { reg[0][i] = dl * (grid1[i] & 0xf) + ml; reg[1][i] = dl * (grid1[i] >> 4) + ml; reg[2][i] = dl * (grid2[i] & 0xf) + ml; reg[3][i] = dl * (grid2[i] >> 4) + ml; } } template <typename type4x4> void dequantize_iq1_m(device const block_iq1_m * xb, short il, thread type4x4 & reg) { // il is 0...15 for QK_K = 256 => index of block of 32 is il/2 const int ib32 = il/2; il = il%2; device const uint16_t * sc = (device const uint16_t *)xb->scales; iq1m_scale_t scale; scale.u16 = (sc[0] >> 12) | ((sc[1] >> 8) & 0x00f0) | ((sc[2] >> 4) & 0x0f00) | (sc[3] & 0xf000); const float d = scale.f16; device const uint8_t * qs = xb->qs + 4*ib32 + 2*il; device const uint8_t * qh = xb->qh + 2*ib32 + il; const float dl = d * (2*((sc[ib32/2] >> (6*(ib32%2)+3*il)) & 7) + 1); const float ml1 = dl * (qh[0] & 0x08 ? -1 - IQ1M_DELTA : -1 + IQ1M_DELTA); const float ml2 = dl * (qh[0] & 0x80 ? -1 - IQ1M_DELTA : -1 + IQ1M_DELTA); constant uint8_t * grid1 = (constant uint8_t *)(iq1s_grid_gpu + (qs[0] | ((qh[0] << 8) & 0x700))); constant uint8_t * grid2 = (constant uint8_t *)(iq1s_grid_gpu + (qs[1] | ((qh[0] << 4) & 0x700))); for (int i = 0; i < 4; ++i) { reg[0][i] = dl * (grid1[i] & 0xf) + ml1; reg[1][i] = dl * (grid1[i] >> 4) + ml1; reg[2][i] = dl * (grid2[i] & 0xf) + ml2; reg[3][i] = dl * (grid2[i] >> 4) + ml2; } } template <typename type4x4> void dequantize_iq4_nl(device const block_iq4_nl * xb, short il, thread type4x4 & reg) { device const uint16_t * q4 = (device const uint16_t *)xb->qs; const float d = xb->d; uint32_t aux32; thread const uint8_t * q8 = (thread const uint8_t *)&aux32; for (int i = 0; i < 4; ++i) { aux32 = ((q4[2*i] | (q4[2*i+1] << 16)) >> 4*il) & 0x0f0f0f0f; reg[i][0] = d * kvalues_iq4nl_f[q8[0]]; reg[i][1] = d * kvalues_iq4nl_f[q8[1]]; reg[i][2] = d * kvalues_iq4nl_f[q8[2]]; reg[i][3] = d * kvalues_iq4nl_f[q8[3]]; } } template <typename type4x4> void dequantize_iq4_xs(device const block_iq4_xs * xb, short il, thread type4x4 & reg) { // il is 0...15 for QK_K = 256 => index of block of 32 is il/2 const int ib32 = il/2; il = il%2; // il = 0 or 1. il = 0 processes the first 16 quants in a block of 32, il = 1 the second 16 device const uint32_t * q4 = (device const uint32_t *)xb->qs + 4*ib32; const int ls = ((xb->scales_l[ib32/2] >> 4*(ib32%2)) & 0xf) | (((xb->scales_h >> 2*ib32) & 3) << 4); const float d = (float)xb->d * (ls - 32); uint32_t aux32; thread const uint8_t * q8 = (thread const uint8_t *)&aux32; for (int i = 0; i < 4; ++i) { aux32 = (q4[i] >> 4*il) & 0x0f0f0f0f; reg[i][0] = d * kvalues_iq4nl_f[q8[0]]; reg[i][1] = d * kvalues_iq4nl_f[q8[1]]; reg[i][2] = d * kvalues_iq4nl_f[q8[2]]; reg[i][3] = d * kvalues_iq4nl_f[q8[3]]; } } template<typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread float4x4 &)> kernel void kernel_get_rows_q( device const void * src0, device const void * src1, device float * dst, constant int64_t & ne00, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne10, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb1, constant uint64_t & nb2, uint3 tgpig[[threadgroup_position_in_grid]], uint tiitg[[thread_index_in_threadgroup]], uint3 tptg [[threads_per_threadgroup]]) { const int64_t i10 = tgpig.x; const int64_t i11 = tgpig.y; const int64_t r = ((const device int32_t *) ((const device char *) src1 + i11*nb11 + i10*nb10))[0]; const int64_t i02 = i11; for (int64_t ind = tiitg; ind < ne00/16; ind += tptg.x) { float4x4 temp; dequantize_func(((device const block_q *) ((const device char *) src0 + r*nb01 + i02*nb02)) + ind/nl, ind%nl, temp); *(((device float4x4 *) ((device char *) dst + i11*nb2 + i10*nb1)) + ind) = temp; } } template<typename T> kernel void kernel_get_rows_f( device const void * src0, device const void * src1, device float * dst, constant int64_t & ne00, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne10, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb1, constant uint64_t & nb2, uint3 tgpig[[threadgroup_position_in_grid]], uint tiitg[[thread_index_in_threadgroup]], uint3 tptg [[threads_per_threadgroup]]) { const int64_t i10 = tgpig.x; const int64_t i11 = tgpig.y; const int64_t r = ((const device int32_t *) ((const device char *) src1 + i11*nb11 + i10*nb10))[0]; const int64_t i02 = i11; for (int ind = tiitg; ind < ne00; ind += tptg.x) { (( device float *) (( device char *) dst + i11*nb2 + i10*nb1))[ind] = ((const device T *) ((const device char *) src0 + i02*nb02 + r*nb01))[ind]; } } kernel void kernel_get_rows_i32( device const void * src0, device const void * src1, device int32_t * dst, constant int64_t & ne00, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne10, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb1, constant uint64_t & nb2, uint3 tgpig[[threadgroup_position_in_grid]], uint tiitg[[thread_index_in_threadgroup]], uint3 tptg [[threads_per_threadgroup]]) { const int64_t i10 = tgpig.x; const int64_t i11 = tgpig.y; const int64_t r = ((const device int32_t *) ((const device char *) src1 + i11*nb11 + i10*nb10))[0]; const int64_t i02 = i11; for (int ind = tiitg; ind < ne00; ind += tptg.x) { (( device int32_t *) (( device char *) dst + i11*nb2 + i10*nb1))[ind] = ((const device int32_t *) ((const device char *) src0 + i02*nb02 + r*nb01))[ind]; } } #define BLOCK_SIZE_M 64 // 8 simdgroup matrices from matrix A #define BLOCK_SIZE_N 32 // 4 simdgroup matrices from matrix B #define BLOCK_SIZE_K 32 #define THREAD_MAT_M 4 // each thread take 4 simdgroup matrices from matrix A #define THREAD_MAT_N 2 // each thread take 2 simdgroup matrices from matrix B #define THREAD_PER_BLOCK 128 #define THREAD_PER_ROW 2 // 2 thread for each row in matrix A to load numbers #define THREAD_PER_COL 4 // 4 thread for each row in matrix B to load numbers #define SG_MAT_SIZE 64 // simdgroup matrix is of shape 8x8 #define SG_MAT_ROW 8 // each block_q contains 16*nl weights template<typename T, typename T4x4, typename simdgroup_T8x8, typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread T4x4 &)> kernel void kernel_mul_mm(device const uchar * src0, device const uchar * src1, device float * dst, constant int64_t & ne00, constant int64_t & ne02, constant uint64_t & nb01, constant uint64_t & nb02, constant uint64_t & nb03, constant int64_t & ne12, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant uint64_t & nb13, constant int64_t & ne0, constant int64_t & ne1, constant uint & r2, constant uint & r3, threadgroup uchar * shared_memory [[threadgroup(0)]], uint3 tgpig[[threadgroup_position_in_grid]], uint tiitg[[thread_index_in_threadgroup]], uint sgitg[[simdgroup_index_in_threadgroup]]) { threadgroup T * sa = (threadgroup T *)(shared_memory); threadgroup float * sb = (threadgroup float *)(shared_memory + 4096); const uint r0 = tgpig.y; const uint r1 = tgpig.x; const uint im = tgpig.z; // if this block is of 64x32 shape or smaller short n_rows = (ne0 - r0*BLOCK_SIZE_M < BLOCK_SIZE_M) ? (ne0 - r0*BLOCK_SIZE_M) : BLOCK_SIZE_M; short n_cols = (ne1 - r1*BLOCK_SIZE_N < BLOCK_SIZE_N) ? (ne1 - r1*BLOCK_SIZE_N) : BLOCK_SIZE_N; // a thread shouldn't load data outside of the matrix short thread_row = ((short)tiitg/THREAD_PER_ROW) < n_rows ? ((short)tiitg/THREAD_PER_ROW) : n_rows - 1; short thread_col = ((short)tiitg/THREAD_PER_COL) < n_cols ? ((short)tiitg/THREAD_PER_COL) : n_cols - 1; simdgroup_T8x8 ma[4]; simdgroup_float8x8 mb[2]; simdgroup_float8x8 mc[8]; for (short i = 0; i < 8; i++){ mc[i] = make_filled_simdgroup_matrix<float, 8>(0.f); } short il = (tiitg % THREAD_PER_ROW); const uint i12 = im%ne12; const uint i13 = im/ne12; uint offset0 = (i12/r2)*nb02 + (i13/r3)*nb03; ushort offset1 = il/nl; device const block_q * x = (device const block_q *)(src0 + (r0*BLOCK_SIZE_M + thread_row)*nb01 + offset0) + offset1; device const float * y = (device const float *)(src1 + nb13 * i13 + nb12 * i12 + nb11 * (r1 * BLOCK_SIZE_N + thread_col) + nb10 * (BLOCK_SIZE_K / THREAD_PER_COL * (tiitg % THREAD_PER_COL))); for (int loop_k = 0; loop_k < ne00; loop_k += BLOCK_SIZE_K) { // load data and store to threadgroup memory T4x4 temp_a; dequantize_func(x, il, temp_a); threadgroup_barrier(mem_flags::mem_threadgroup); #pragma unroll(16) for (short i = 0; i < 16; i++) { *(sa + SG_MAT_SIZE * ((tiitg/THREAD_PER_ROW/8) \ + (tiitg%THREAD_PER_ROW)*16 + (i/8)*8) \ + (tiitg/THREAD_PER_ROW)%8 + (i&7)*8) = temp_a[i/4][i%4]; } *(threadgroup float2x4 *)(sb + (tiitg % THREAD_PER_COL)*8*32 + 8*(tiitg/THREAD_PER_COL)) = *((device float2x4 *) y); il = (il + 2 < nl) ? il + 2 : il % 2; x = (il < 2) ? x + (2+nl-1)/nl : x; y += BLOCK_SIZE_K; threadgroup_barrier(mem_flags::mem_threadgroup); // load matrices from threadgroup memory and conduct outer products threadgroup T * lsma = (sa + THREAD_MAT_M*SG_MAT_SIZE*(sgitg%2)); threadgroup float * lsmb = (sb + THREAD_MAT_N*SG_MAT_SIZE*(sgitg/2)); #pragma unroll(4) for (short ik = 0; ik < BLOCK_SIZE_K / 8; ik++) { #pragma unroll(4) for (short i = 0; i < 4; i++) { simdgroup_load(ma[i], lsma + SG_MAT_SIZE * i); } simdgroup_barrier(mem_flags::mem_none); #pragma unroll(2) for (short i = 0; i < 2; i++) { simdgroup_load(mb[i], lsmb + SG_MAT_SIZE * i); } lsma += BLOCK_SIZE_M/SG_MAT_ROW * SG_MAT_SIZE; lsmb += BLOCK_SIZE_N/SG_MAT_ROW * SG_MAT_SIZE; #pragma unroll(8) for (short i = 0; i < 8; i++){ simdgroup_multiply_accumulate(mc[i], mb[i/4], ma[i%4], mc[i]); } } } if ((r0 + 1) * BLOCK_SIZE_M <= ne0 && (r1 + 1) * BLOCK_SIZE_N <= ne1) { device float * C = dst + (BLOCK_SIZE_M * r0 + 32 * (sgitg & 1)) \ + (BLOCK_SIZE_N * r1 + 16 * (sgitg >> 1)) * ne0 + im*ne1*ne0; for (short i = 0; i < 8; i++) { simdgroup_store(mc[i], C + 8 * (i%4) + 8 * ne0 * (i/4), ne0); } } else { // block is smaller than 64x32, we should avoid writing data outside of the matrix threadgroup_barrier(mem_flags::mem_threadgroup); threadgroup float * temp_str = ((threadgroup float *) shared_memory) \ + 32 * (sgitg&1) + (16 * (sgitg>>1))*BLOCK_SIZE_M; for (short i = 0; i < 8; i++) { simdgroup_store(mc[i], temp_str + 8*(i%4) + 8*BLOCK_SIZE_M*(i/4), BLOCK_SIZE_M); } threadgroup_barrier(mem_flags::mem_threadgroup); if (sgitg == 0) { for (int j = tiitg; j < n_cols; j += BLOCK_SIZE_N) { device float * D = dst + (r0*BLOCK_SIZE_M) + (r1*BLOCK_SIZE_N + j)*ne0 + im*ne1*ne0; device float4 * D4 = (device float4 *) D; threadgroup float * C = temp_str + (j*BLOCK_SIZE_M); threadgroup float4 * C4 = (threadgroup float4 *) C; int i = 0; for (; i < n_rows/4; i++) { *(D4 + i) = *(C4 + i); } i *= 4; for (; i < n_rows; i++) { *(D + i) = *(C + i); } } } } } // same as kernel_mul_mm_impl, but src1 and dst are accessed via indices stored in rowids template<typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread half4x4 &)> void kernel_mul_mm_id_impl( device const uchar * src0, device const uchar * src1, threadgroup ushort2 * rowids, device float * dst, constant int64_t & ne00, constant int64_t & ne02, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne11, constant int64_t & ne12, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant int64_t & ne0, int64_t ne1, int64_t ne0ne1, threadgroup uchar * shared_memory, uint3 tgpig[[threadgroup_position_in_grid]], uint tiitg[[thread_index_in_threadgroup]], uint sgitg[[simdgroup_index_in_threadgroup]]) { threadgroup half * sa = (threadgroup half *)(shared_memory); threadgroup float * sb = (threadgroup float *)(shared_memory + 4096); const uint r0 = tgpig.y; const uint r1 = tgpig.x; if (r1 * BLOCK_SIZE_N >= ne1) return; // if this block is of 64x32 shape or smaller short n_rows = (ne0 - r0 * BLOCK_SIZE_M < BLOCK_SIZE_M) ? (ne0 - r0 * BLOCK_SIZE_M) : BLOCK_SIZE_M; short n_cols = (ne1 - r1 * BLOCK_SIZE_N < BLOCK_SIZE_N) ? (ne1 - r1 * BLOCK_SIZE_N) : BLOCK_SIZE_N; // a thread shouldn't load data outside of the matrix short thread_row = ((short)tiitg/THREAD_PER_ROW) < n_rows ? ((short)tiitg/THREAD_PER_ROW) : n_rows - 1; short thread_col = ((short)tiitg/THREAD_PER_COL) < n_cols ? ((short)tiitg/THREAD_PER_COL) : n_cols - 1; simdgroup_half8x8 ma[4]; simdgroup_float8x8 mb[2]; simdgroup_float8x8 c_res[8]; for (int i = 0; i < 8; i++){ c_res[i] = make_filled_simdgroup_matrix<float, 8>(0.f); } short il = (tiitg % THREAD_PER_ROW); ushort offset1 = il/nl; threadgroup const auto & id = rowids[r1 * BLOCK_SIZE_N + thread_col]; device const block_q * x = (device const block_q *)(src0 + (r0 * BLOCK_SIZE_M + thread_row) * nb01) + offset1; device const float * y = (device const float *)(src1 + nb12 * id[1] + nb11 * (id[0] % ne11) + nb10 * (BLOCK_SIZE_K / THREAD_PER_COL * (tiitg % THREAD_PER_COL))); for (int loop_k = 0; loop_k < ne00; loop_k += BLOCK_SIZE_K) { // load data and store to threadgroup memory half4x4 temp_a; dequantize_func(x, il, temp_a); threadgroup_barrier(mem_flags::mem_threadgroup); for (int i = 0; i < 16; i++) { *(sa + SG_MAT_SIZE * ((tiitg / THREAD_PER_ROW / 8) \ + (tiitg % THREAD_PER_ROW) * 16 + (i / 8) * 8) \ + (tiitg / THREAD_PER_ROW) % 8 + (i & 7) * 8) = temp_a[i/4][i%4]; } *(threadgroup float2x4 *)(sb + (tiitg % THREAD_PER_COL) * 8 * 32 + 8 * (tiitg / THREAD_PER_COL)) = *((device float2x4 *)y); il = (il + 2 < nl) ? il + 2 : il % 2; x = (il < 2) ? x + (2+nl-1)/nl : x; y += BLOCK_SIZE_K; threadgroup_barrier(mem_flags::mem_threadgroup); // load matrices from threadgroup memory and conduct outer products threadgroup half * lsma = (sa + THREAD_MAT_M * SG_MAT_SIZE * (sgitg % 2)); threadgroup float * lsmb = (sb + THREAD_MAT_N * SG_MAT_SIZE * (sgitg / 2)); for (int ik = 0; ik < BLOCK_SIZE_K / 8; ik++) { for (int i = 0; i < 4; i++) { simdgroup_load(ma[i], lsma + SG_MAT_SIZE * i); } simdgroup_barrier(mem_flags::mem_none); for (int i = 0; i < 2; i++) { simdgroup_load(mb[i], lsmb + SG_MAT_SIZE * i); } lsma += BLOCK_SIZE_M / SG_MAT_ROW * SG_MAT_SIZE; lsmb += BLOCK_SIZE_N / SG_MAT_ROW * SG_MAT_SIZE; for (int i = 0; i < 8; i++){ simdgroup_multiply_accumulate(c_res[i], mb[i/4], ma[i%4], c_res[i]); } } } { threadgroup_barrier(mem_flags::mem_threadgroup); threadgroup float * temp_str = ((threadgroup float *)shared_memory) \ + 32 * (sgitg&1) + (16 * (sgitg>>1)) * BLOCK_SIZE_M; for (int i = 0; i < 8; i++) { simdgroup_store(c_res[i], temp_str + 8 * (i%4) + 8 * BLOCK_SIZE_M * (i/4), BLOCK_SIZE_M); } threadgroup_barrier(mem_flags::mem_threadgroup); device float * C = dst + (BLOCK_SIZE_M * r0); if (sgitg == 0) { for (int j = tiitg; j < n_cols; j += BLOCK_SIZE_N) { threadgroup const auto & jid = rowids[r1 * BLOCK_SIZE_N + j]; int joff = jid[0] * ne0 + jid[1] * ne0ne1; for (int i = 0; i < n_rows; i++) { *(C + i + joff) = *(temp_str + i + j * BLOCK_SIZE_M); } } } } } template<typename block_q, short nl, void (*dequantize_func)(device const block_q *, short, thread half4x4 &)> kernel void kernel_mul_mm_id( device const uchar * src0s, device const uchar * src1, device float * dst, device const uchar * ids, constant int64_t & nei0, constant int64_t & nei1, constant uint64_t & nbi1, constant int64_t & ne00, constant int64_t & ne02, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne11, constant int64_t & ne12, constant int64_t & ne13, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant int64_t & ne0, constant int64_t & ne1, constant uint64_t & nb1, threadgroup uchar * shared_memory [[threadgroup(0)]], uint3 tgpig[[threadgroup_position_in_grid]], uint tiitg[[thread_index_in_threadgroup]], uint sgitg[[simdgroup_index_in_threadgroup]]) { const int32_t i02 = tgpig.z; tgpig.z = 0; device const uchar * src0 = src0s + i02*nb02; // row indices threadgroup ushort2 * rowids = (threadgroup ushort2 *)(shared_memory + 8192); // TODO: parallelize this loop int64_t _ne1 = 0; for (ushort ii1 = 0; ii1 < nei1; ii1++) { for (ushort ii0 = 0; ii0 < nei0; ii0++) { int32_t id = ((device int32_t *) (ids + ii1*nbi1))[ii0]; if (id == i02) { //if (tiitg == 0) { rowids[_ne1] = ushort2(ii0, ii1); //} _ne1++; } } } threadgroup_barrier(mem_flags::mem_threadgroup); kernel_mul_mm_id_impl<block_q, nl, dequantize_func>( src0, src1, rowids, dst, ne00, ne02, nb01, nb02, ne11, ne12, nb10, nb11, nb12, ne0, _ne1, ne0*ne1, shared_memory, tgpig, tiitg, sgitg); } #define QK_NL 16 // // get rows // typedef decltype(kernel_get_rows_f<float>) get_rows_f_t; template [[host_name("kernel_get_rows_f32")]] kernel get_rows_f_t kernel_get_rows_f<float>; template [[host_name("kernel_get_rows_f16")]] kernel get_rows_f_t kernel_get_rows_f<half>; #if defined(__HAVE_BFLOAT__) template [[host_name("kernel_get_rows_bf16")]] kernel get_rows_f_t kernel_get_rows_f<bfloat>; #endif typedef decltype(kernel_get_rows_q<block_q4_0, 2, dequantize_q4_0>) get_rows_q_t; template [[host_name("kernel_get_rows_q4_0")]] kernel get_rows_q_t kernel_get_rows_q<block_q4_0, 2, dequantize_q4_0>; template [[host_name("kernel_get_rows_q4_1")]] kernel get_rows_q_t kernel_get_rows_q<block_q4_1, 2, dequantize_q4_1>; template [[host_name("kernel_get_rows_q5_0")]] kernel get_rows_q_t kernel_get_rows_q<block_q5_0, 2, dequantize_q5_0>; template [[host_name("kernel_get_rows_q5_1")]] kernel get_rows_q_t kernel_get_rows_q<block_q5_1, 2, dequantize_q5_1>; template [[host_name("kernel_get_rows_q8_0")]] kernel get_rows_q_t kernel_get_rows_q<block_q8_0, 2, dequantize_q8_0>; template [[host_name("kernel_get_rows_q2_K")]] kernel get_rows_q_t kernel_get_rows_q<block_q2_K, QK_NL, dequantize_q2_K>; template [[host_name("kernel_get_rows_q3_K")]] kernel get_rows_q_t kernel_get_rows_q<block_q3_K, QK_NL, dequantize_q3_K>; template [[host_name("kernel_get_rows_q4_K")]] kernel get_rows_q_t kernel_get_rows_q<block_q4_K, QK_NL, dequantize_q4_K>; template [[host_name("kernel_get_rows_q5_K")]] kernel get_rows_q_t kernel_get_rows_q<block_q5_K, QK_NL, dequantize_q5_K>; template [[host_name("kernel_get_rows_q6_K")]] kernel get_rows_q_t kernel_get_rows_q<block_q6_K, QK_NL, dequantize_q6_K>; template [[host_name("kernel_get_rows_iq2_xxs")]] kernel get_rows_q_t kernel_get_rows_q<block_iq2_xxs, QK_NL, dequantize_iq2_xxs>; template [[host_name("kernel_get_rows_iq2_xs")]] kernel get_rows_q_t kernel_get_rows_q<block_iq2_xs, QK_NL, dequantize_iq2_xs>; template [[host_name("kernel_get_rows_iq3_xxs")]] kernel get_rows_q_t kernel_get_rows_q<block_iq3_xxs, QK_NL, dequantize_iq3_xxs>; template [[host_name("kernel_get_rows_iq3_s")]] kernel get_rows_q_t kernel_get_rows_q<block_iq3_s, QK_NL, dequantize_iq3_s>; template [[host_name("kernel_get_rows_iq2_s")]] kernel get_rows_q_t kernel_get_rows_q<block_iq2_s, QK_NL, dequantize_iq2_s>; template [[host_name("kernel_get_rows_iq1_s")]] kernel get_rows_q_t kernel_get_rows_q<block_iq1_s, QK_NL, dequantize_iq1_s>; template [[host_name("kernel_get_rows_iq1_m")]] kernel get_rows_q_t kernel_get_rows_q<block_iq1_m, QK_NL, dequantize_iq1_m>; template [[host_name("kernel_get_rows_iq4_nl")]] kernel get_rows_q_t kernel_get_rows_q<block_iq4_nl, 2, dequantize_iq4_nl>; template [[host_name("kernel_get_rows_iq4_xs")]] kernel get_rows_q_t kernel_get_rows_q<block_iq4_xs, QK_NL, dequantize_iq4_xs>; // // matrix-matrix multiplication // typedef decltype(kernel_mul_mm<half, half4x4, simdgroup_half8x8, float4x4, 1, dequantize_f32>) mat_mm_t; template [[host_name("kernel_mul_mm_f32_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, float4x4, 1, dequantize_f32>; template [[host_name("kernel_mul_mm_f16_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, half4x4, 1, dequantize_f16>; #if defined(__HAVE_BFLOAT__) template [[host_name("kernel_mul_mm_bf16_f32")]] kernel mat_mm_t kernel_mul_mm<bfloat, bfloat4x4, simdgroup_bfloat8x8, bfloat4x4, 1, dequantize_bf16>; #endif template [[host_name("kernel_mul_mm_q4_0_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_q4_0, 2, dequantize_q4_0>; template [[host_name("kernel_mul_mm_q4_1_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_q4_1, 2, dequantize_q4_1>; template [[host_name("kernel_mul_mm_q5_0_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_q5_0, 2, dequantize_q5_0>; template [[host_name("kernel_mul_mm_q5_1_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_q5_1, 2, dequantize_q5_1>; template [[host_name("kernel_mul_mm_q8_0_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_q8_0, 2, dequantize_q8_0>; template [[host_name("kernel_mul_mm_q2_K_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_q2_K, QK_NL, dequantize_q2_K>; template [[host_name("kernel_mul_mm_q3_K_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_q3_K, QK_NL, dequantize_q3_K>; template [[host_name("kernel_mul_mm_q4_K_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_q4_K, QK_NL, dequantize_q4_K>; template [[host_name("kernel_mul_mm_q5_K_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_q5_K, QK_NL, dequantize_q5_K>; template [[host_name("kernel_mul_mm_q6_K_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_q6_K, QK_NL, dequantize_q6_K>; template [[host_name("kernel_mul_mm_iq2_xxs_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_iq2_xxs, QK_NL, dequantize_iq2_xxs>; template [[host_name("kernel_mul_mm_iq2_xs_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_iq2_xs, QK_NL, dequantize_iq2_xs>; template [[host_name("kernel_mul_mm_iq3_xxs_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_iq3_xxs, QK_NL, dequantize_iq3_xxs>; template [[host_name("kernel_mul_mm_iq3_s_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_iq3_s, QK_NL, dequantize_iq3_s>; template [[host_name("kernel_mul_mm_iq2_s_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_iq2_s, QK_NL, dequantize_iq2_s>; template [[host_name("kernel_mul_mm_iq1_s_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_iq1_s, QK_NL, dequantize_iq1_s>; template [[host_name("kernel_mul_mm_iq1_m_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_iq1_m, QK_NL, dequantize_iq1_m>; template [[host_name("kernel_mul_mm_iq4_nl_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_iq4_nl, 2, dequantize_iq4_nl>; template [[host_name("kernel_mul_mm_iq4_xs_f32")]] kernel mat_mm_t kernel_mul_mm<half, half4x4, simdgroup_half8x8, block_iq4_xs, QK_NL, dequantize_iq4_xs>; // // indirect matrix-matrix multiplication // typedef decltype(kernel_mul_mm_id<float4x4, 1, dequantize_f32>) mat_mm_id_t; template [[host_name("kernel_mul_mm_id_f32_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<float4x4, 1, dequantize_f32>; template [[host_name("kernel_mul_mm_id_f16_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<half4x4, 1, dequantize_f16>; template [[host_name("kernel_mul_mm_id_q4_0_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_q4_0, 2, dequantize_q4_0>; template [[host_name("kernel_mul_mm_id_q4_1_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_q4_1, 2, dequantize_q4_1>; template [[host_name("kernel_mul_mm_id_q5_0_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_q5_0, 2, dequantize_q5_0>; template [[host_name("kernel_mul_mm_id_q5_1_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_q5_1, 2, dequantize_q5_1>; template [[host_name("kernel_mul_mm_id_q8_0_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_q8_0, 2, dequantize_q8_0>; template [[host_name("kernel_mul_mm_id_q2_K_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_q2_K, QK_NL, dequantize_q2_K>; template [[host_name("kernel_mul_mm_id_q3_K_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_q3_K, QK_NL, dequantize_q3_K>; template [[host_name("kernel_mul_mm_id_q4_K_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_q4_K, QK_NL, dequantize_q4_K>; template [[host_name("kernel_mul_mm_id_q5_K_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_q5_K, QK_NL, dequantize_q5_K>; template [[host_name("kernel_mul_mm_id_q6_K_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_q6_K, QK_NL, dequantize_q6_K>; template [[host_name("kernel_mul_mm_id_iq2_xxs_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_iq2_xxs, QK_NL, dequantize_iq2_xxs>; template [[host_name("kernel_mul_mm_id_iq2_xs_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_iq2_xs, QK_NL, dequantize_iq2_xs>; template [[host_name("kernel_mul_mm_id_iq3_xxs_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_iq3_xxs, QK_NL, dequantize_iq3_xxs>; template [[host_name("kernel_mul_mm_id_iq3_s_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_iq3_s, QK_NL, dequantize_iq3_s>; template [[host_name("kernel_mul_mm_id_iq2_s_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_iq2_s, QK_NL, dequantize_iq2_s>; template [[host_name("kernel_mul_mm_id_iq1_s_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_iq1_s, QK_NL, dequantize_iq1_s>; template [[host_name("kernel_mul_mm_id_iq1_m_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_iq1_m, QK_NL, dequantize_iq1_m>; template [[host_name("kernel_mul_mm_id_iq4_nl_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_iq4_nl, 2, dequantize_iq4_nl>; template [[host_name("kernel_mul_mm_id_iq4_xs_f32")]] kernel mat_mm_id_t kernel_mul_mm_id<block_iq4_xs, QK_NL, dequantize_iq4_xs>; // // matrix-vector multiplication // typedef void (kernel_mul_mv_impl_t)( device const char * src0, device const char * src1, device float * dst, int64_t ne00, int64_t ne01, int64_t ne02, uint64_t nb00, uint64_t nb01, uint64_t nb02, int64_t ne10, int64_t ne11, int64_t ne12, uint64_t nb10, uint64_t nb11, uint64_t nb12, int64_t ne0, int64_t ne1, uint r2, uint r3, uint3 tgpig, uint tiisg); typedef void (kernel_mul_mv2_impl_t)( device const void * src0, device const float * src1, device float * dst, int64_t ne00, int64_t ne01, int64_t ne02, int64_t ne10, int64_t ne12, int64_t ne0, int64_t ne1, uint r2, uint r3, threadgroup int8_t * shared_values, uint3 tgpig, uint tiisg, uint sgitg); template<kernel_mul_mv_impl_t impl_fn> void mmv_fn( device const char * src0, device const char * src1, device float * dst, int64_t ne00, int64_t ne01, int64_t ne02, uint64_t nb00, uint64_t nb01, uint64_t nb02, int64_t ne10, int64_t ne11, int64_t ne12, int64_t ne13, uint64_t nb10, uint64_t nb11, uint64_t nb12, int64_t ne0, int64_t ne1, uint64_t nb1, uint r2, uint r3, threadgroup int8_t * shared_values, uint3 tgpig, uint tiitg, uint tiisg, uint sgitg) { impl_fn(src0,src1,dst,ne00,ne01,ne02,nb00,nb01,nb02,ne10,ne11,ne12,nb10,nb11,nb12,ne0,ne1,r2,r3,tgpig,tiisg); } template<kernel_mul_mv2_impl_t impl_fn> void mmv_fn( device const char * src0, device const char * src1, device float * dst, int64_t ne00, int64_t ne01, int64_t ne02, uint64_t nb00, uint64_t nb01, uint64_t nb02, int64_t ne10, int64_t ne11, int64_t ne12, int64_t ne13, uint64_t nb10, uint64_t nb11, uint64_t nb12, int64_t ne0, int64_t ne1, uint64_t nb1, uint r2, uint r3, threadgroup int8_t * shared_values, uint3 tgpig, uint tiitg, uint tiisg, uint sgitg) { impl_fn(src0,(const device float *)src1,dst,ne00,ne01,ne02,ne10,ne12,ne0,ne1,r2,r3,shared_values,tgpig,tiisg,sgitg); } typedef decltype(mmv_fn<kernel_mul_mv_impl<half, half4, half, half4>>) mul_mv_impl_fn_t; template<mul_mv_impl_fn_t impl_fn> kernel void kernel_mul_mv_id( device const char * src0s, device const char * src1, device float * dst, device const char * ids, constant int64_t & nei0, constant int64_t & nei1, constant uint64_t & nbi1, constant int64_t & ne00, constant int64_t & ne01, constant int64_t & ne02, constant uint64_t & nb00, constant uint64_t & nb01, constant uint64_t & nb02, constant int64_t & ne10, constant int64_t & ne11, constant int64_t & ne12, constant int64_t & ne13, constant uint64_t & nb10, constant uint64_t & nb11, constant uint64_t & nb12, constant int64_t & ne0, constant int64_t & ne1, constant uint64_t & nb1, threadgroup int8_t * shared_values [[threadgroup(0)]], uint3 tgpig[[threadgroup_position_in_grid]], uint tiitg[[thread_index_in_threadgroup]], uint tiisg[[thread_index_in_simdgroup]], uint sgitg[[simdgroup_index_in_threadgroup]]) { const int iid1 = tgpig.z/nei0; const int idx = tgpig.z%nei0; tgpig.z = 0; const int32_t i02 = ((device const int32_t *) (ids + iid1*nbi1))[idx]; const int64_t i11 = idx % ne11; const int64_t i12 = iid1; const int64_t i1 = idx; const int64_t i2 = i12; device const char * src0_cur = src0s + i02*nb02; device const char * src1_cur = src1 + i11*nb11 + i12*nb12; device float * dst_cur = dst + i1*ne0 + i2*ne1*ne0; impl_fn( /* src0 */ src0_cur, /* src1 */ src1_cur, /* dst */ dst_cur, /* ne00 */ ne00, /* ne01 */ ne01, /* ne02 */ 1,//ne02, /* nb00 */ nb00, /* nb01 */ nb01, /* nb02 */ nb02, /* ne10 */ ne10, /* ne11 */ 1,//ne11, /* ne12 */ 1,//ne12, /* ne13 */ 1,//ne13, /* nb10 */ nb10, /* nb11 */ nb11, /* nb12 */ nb12, /* ne0 */ ne0, /* ne1 */ 1,//ne1, /* nb1 */ nb1, /* r2 */ 1, /* r3 */ 1, shared_values, tgpig, tiitg, tiisg, sgitg); } typedef decltype(kernel_mul_mv_id<mmv_fn<kernel_mul_mv_impl<float, float4, float, float4>>>) kernel_mul_mv_id_t; template [[host_name("kernel_mul_mv_id_f32_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_impl<float, float4, float, float4>>>; template [[host_name("kernel_mul_mv_id_f16_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_impl<half, half4, float, float4>>>; template [[host_name("kernel_mul_mv_id_q8_0_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_q8_0_f32_impl>>; template [[host_name("kernel_mul_mv_id_q4_0_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<mul_vec_q_n_f32_impl<block_q4_0, N_DST, N_SIMDGROUP, N_SIMDWIDTH>>>; template [[host_name("kernel_mul_mv_id_q4_1_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<mul_vec_q_n_f32_impl<block_q4_1, N_DST, N_SIMDGROUP, N_SIMDWIDTH>>>; template [[host_name("kernel_mul_mv_id_q5_0_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<mul_vec_q_n_f32_impl<block_q5_0, N_DST, N_SIMDGROUP, N_SIMDWIDTH>>>; template [[host_name("kernel_mul_mv_id_q5_1_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<mul_vec_q_n_f32_impl<block_q5_1, N_DST, N_SIMDGROUP, N_SIMDWIDTH>>>; template [[host_name("kernel_mul_mv_id_q2_K_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_q2_K_f32_impl>>; template [[host_name("kernel_mul_mv_id_q3_K_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_q3_K_f32_impl>>; template [[host_name("kernel_mul_mv_id_q4_K_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_q4_K_f32_impl>>; template [[host_name("kernel_mul_mv_id_q5_K_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_q5_K_f32_impl>>; template [[host_name("kernel_mul_mv_id_q6_K_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_q6_K_f32_impl>>; template [[host_name("kernel_mul_mv_id_iq1_s_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_iq1_s_f32_impl>>; template [[host_name("kernel_mul_mv_id_iq1_m_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_iq1_m_f32_impl>>; template [[host_name("kernel_mul_mv_id_iq2_xxs_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_iq2_xxs_f32_impl>>; template [[host_name("kernel_mul_mv_id_iq2_xs_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_iq2_xs_f32_impl>>; template [[host_name("kernel_mul_mv_id_iq3_xxs_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_iq3_xxs_f32_impl>>; template [[host_name("kernel_mul_mv_id_iq3_s_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_iq3_s_f32_impl>>; template [[host_name("kernel_mul_mv_id_iq2_s_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_iq2_s_f32_impl>>; template [[host_name("kernel_mul_mv_id_iq4_nl_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_iq4_nl_f32_impl>>; template [[host_name("kernel_mul_mv_id_iq4_xs_f32")]] kernel kernel_mul_mv_id_t kernel_mul_mv_id<mmv_fn<kernel_mul_mv_iq4_xs_f32_impl>>; kernel void kernel_pool_2d_max_f32( device const float * src0, device float * dst, constant int32_t & k0, constant int32_t & k1, constant int32_t & s0, constant int32_t & s1, constant int32_t & p0, constant int32_t & p1, constant int64_t & IH, constant int64_t & IW, constant int64_t & OH, constant int64_t & OW, constant int64_t & parallel_elements, uint gid[[thread_position_in_grid]]) { if (gid >= parallel_elements) { return; } const int idx = gid; const int I_HW = IH * IW; const int O_HW = OH * OW; const int nc = idx / O_HW; const int cur_oh = idx % O_HW / OW; const int cur_ow = idx % O_HW % OW; device const float * i_ptr = src0 + nc * I_HW; device float * o_ptr = dst + nc * O_HW; const int start_h = cur_oh * s1 - p1; const int bh = MAX(0, start_h); const int eh = MIN(IH, start_h + k1); const int start_w = cur_ow * s0 - p0; const int bw = MAX(0, start_w); const int ew = MIN(IW, start_w + k0); float res = -INFINITY; for (int i = bh; i < eh; i += 1) { for (int j = bw; j < ew; j += 1) { res = MAX(res, i_ptr[i * IW + j]); } } o_ptr[cur_oh * OW + cur_ow] = res; } kernel void kernel_pool_2d_avg_f32( device const float * src0, device float * dst, constant int32_t & k0, constant int32_t & k1, constant int32_t & s0, constant int32_t & s1, constant int32_t & p0, constant int32_t & p1, constant int64_t & IH, constant int64_t & IW, constant int64_t & OH, constant int64_t & OW, constant int64_t & parallel_elements, uint gid[[thread_position_in_grid]]) { if (gid >= parallel_elements) { return; } const int idx = gid; const int I_HW = IH * IW; const int O_HW = OH * OW; const int nc = idx / O_HW; const int cur_oh = idx % O_HW / OW; const int cur_ow = idx % O_HW % OW; device const float * i_ptr = src0 + nc * I_HW; device float * o_ptr = dst + nc * O_HW; const int start_h = cur_oh * s1 - p1; const int bh = MAX(0, start_h); const int eh = MIN(IH, start_h + k1); const int start_w = cur_ow * s0 - p0; const int bw = MAX(0, start_w); const int ew = MIN(IW, start_w + k0); // const float scale = 1. / ((eh - bh) * (ew - bw)); const float scale = 1. / (k0 * k1); float res = 0; for (int i = bh; i < eh; i += 1) { for (int j = bw; j < ew; j += 1) { float cur = i_ptr[i * IW + j]; res += cur * scale; } } o_ptr[cur_oh * OW + cur_ow] = res; }
candle/candle-metal-kernels/src/quantized.metal/0
{ "file_path": "candle/candle-metal-kernels/src/quantized.metal", "repo_id": "candle", "token_count": 179540 }
51
# candle-nn
candle/candle-nn/README.md/0
{ "file_path": "candle/candle-nn/README.md", "repo_id": "candle", "token_count": 5 }
52
//! Cache Implementations //! use candle::{DType, Device, Result, Tensor}; #[derive(Debug, Clone)] pub struct Cache { // all_data is an option on a Tensor, this makes it possible to only create the actual tensor // on the first call where the batch size is easily known. // Also this makes it safe to clone a KvCache that has been reseted (as in it will not share // its internal state with the cloned instance). all_data: Option<Tensor>, dim: usize, current_seq_len: usize, grow_by: usize, max_seq_len: usize, } impl Cache { pub fn new(dim: usize, max_seq_len: usize) -> Self { Self { all_data: None, dim, current_seq_len: 0, grow_by: max_seq_len, max_seq_len, } } pub fn dim(&self) -> usize { self.dim } pub fn current_seq_len(&self) -> usize { self.current_seq_len } pub fn max_seq_len(&self) -> usize { self.max_seq_len } pub fn all_data(&self) -> &Option<Tensor> { &self.all_data } pub fn current_data(&self) -> Result<Option<Tensor>> { let data = match self.all_data.as_ref() { None => None, Some(d) => Some(d.narrow(self.dim, 0, self.current_seq_len)?), }; Ok(data) } pub fn reset(&mut self) { self.current_seq_len = 0; self.all_data = None; } pub fn append(&mut self, src: &Tensor) -> Result<()> { let seq_len = src.dim(self.dim)?; // This doesn't seem very idiomatic but because the creation can fail, it's tricky to use // self.all_data.get_or_insert_with. if self.all_data.is_none() { let mut shape = src.dims().to_vec(); shape[self.dim] = self.max_seq_len; let ad = Tensor::zeros(shape, src.dtype(), src.device())?; self.all_data = Some(ad) }; let ad = self.all_data.as_mut().unwrap(); if self.current_seq_len + seq_len > self.max_seq_len { let mut shape = src.dims().to_vec(); shape[self.dim] = self.grow_by; let next_ad = Tensor::zeros(shape, src.dtype(), src.device())?; *ad = Tensor::cat(&[&*ad, &next_ad], self.dim)?; self.max_seq_len += self.grow_by; } ad.slice_set(src, self.dim, self.current_seq_len)?; self.current_seq_len += seq_len; Ok(()) } } #[derive(Debug, Clone)] pub struct KvCache { k: Cache, v: Cache, } impl KvCache { pub fn new(dim: usize, max_seq_len: usize) -> Self { let k = Cache::new(dim, max_seq_len); let v = Cache::new(dim, max_seq_len); Self { k, v } } pub fn k_cache(&self) -> &Cache { &self.k } pub fn v_cache(&self) -> &Cache { &self.v } pub fn k_cache_mut(&mut self) -> &mut Cache { &mut self.k } pub fn v_cache_mut(&mut self) -> &mut Cache { &mut self.v } pub fn k(&self) -> Result<Option<Tensor>> { self.k.current_data() } pub fn v(&self) -> Result<Option<Tensor>> { self.v.current_data() } pub fn append(&mut self, k: &Tensor, v: &Tensor) -> Result<(Tensor, Tensor)> { self.k.append(k)?; self.v.append(v)?; let out_k = self.k.current_data()?; let out_v = self.v.current_data()?; let k = match out_k { None => { let mut shape = k.dims().to_vec(); shape[self.k.dim] = 0; Tensor::zeros(shape, k.dtype(), k.device())? } Some(k) => k, }; let v = match out_v { None => { let mut shape = v.dims().to_vec(); shape[self.k.dim] = 0; Tensor::zeros(shape, v.dtype(), v.device())? } Some(v) => v, }; Ok((k, v)) } pub fn current_seq_len(&self) -> usize { self.k.current_seq_len() } pub fn reset(&mut self) { self.k.reset(); self.v.reset(); } } #[derive(Debug, Clone)] pub struct RotatingCache { all_data: Option<Tensor>, dim: usize, // `offset` is the current write index in the buffer offset: usize, // The total size of the sequence seen so far. current_seq_len: usize, // max_seq_len is the size of the rotating buffer, it is actually allowed for the full // sequence to grow past this limit. max_seq_len: usize, } impl RotatingCache { pub fn new(dim: usize, max_seq_len: usize) -> Self { Self { all_data: None, dim, offset: 0, current_seq_len: 0, max_seq_len, } } pub fn offset(&self) -> usize { self.offset } pub fn dim(&self) -> usize { self.dim } pub fn current_seq_len(&self) -> usize { self.current_seq_len } pub fn max_seq_len(&self) -> usize { self.max_seq_len } pub fn all_data(&self) -> &Option<Tensor> { &self.all_data } pub fn current_data(&self) -> Result<Option<Tensor>> { let data = match self.all_data.as_ref() { None => None, Some(d) => { if self.current_seq_len >= self.max_seq_len { Some(d.clone()) } else { Some(d.narrow(self.dim, 0, self.current_seq_len)?) } } }; Ok(data) } pub fn reset(&mut self) { self.offset = 0; self.current_seq_len = 0; self.all_data = None; } pub fn append(&mut self, src: &Tensor) -> Result<Tensor> { let seq_len = src.dim(self.dim)?; // This doesn't seem very idiomatic but because the creation can fail, it's tricky to use // self.all_data.get_or_insert_with. if self.all_data.is_none() { let mut shape = src.dims().to_vec(); shape[self.dim] = self.max_seq_len; let ad = Tensor::zeros(shape, src.dtype(), src.device())?; self.all_data = Some(ad) }; let ad = self.all_data.as_mut().unwrap(); self.current_seq_len += seq_len; if seq_len >= self.max_seq_len { let to_copy = src .narrow(self.dim, seq_len - self.max_seq_len, self.max_seq_len)? .contiguous()?; ad.slice_set(&to_copy, self.dim, 0)?; self.offset = 0; // Here we return `src` rather than `ad` so that all the past can be used. Ok(src.clone()) } else { let rem_len = self.max_seq_len - self.offset; if seq_len <= rem_len { ad.slice_set(&src.contiguous()?, self.dim, self.offset)?; self.offset = (self.offset + seq_len) % self.max_seq_len; } else { // We have to make two copies here as we go over the boundary of the cache. if rem_len > 0 { let src1 = src.narrow(self.dim, 0, rem_len)?.contiguous()?; ad.slice_set(&src1, self.dim, self.offset)?; } let src2 = src .narrow(self.dim, rem_len, seq_len - rem_len)? .contiguous()?; ad.slice_set(&src2, self.dim, 0)?; self.offset = seq_len - rem_len; } if self.current_seq_len >= self.max_seq_len { Ok(ad.clone()) } else { Ok(ad.narrow(self.dim, 0, self.current_seq_len)?) } } } fn get_mask_abs(&self, size1: usize, size2: usize, device: &Device) -> Result<Tensor> { let context = self.max_seq_len; let mask: Vec<_> = (0..size1) .flat_map(|i| { (0..size2).map(move |j| { u8::from(size1 + j > size2 + i || size1 + j + context < size2 + i) }) }) .collect(); Tensor::from_slice(&mask, (size1, size2), device) } fn get_mask_rel(&self, size1: usize, size2: usize, device: &Device) -> Result<Tensor> { let context = self.max_seq_len; let upd_offset = (self.offset + size1) % self.max_seq_len; let mask: Vec<_> = (0..size1) .flat_map(|pos_src| { // The absolute position of the elements that will get added to the cache. let pos_src = self.current_seq_len + pos_src; (0..size2).map(move |pos_cache_rel| { // The absolute position of the cache elements after the addition. let pos_cache = self.current_seq_len + size1 + pos_cache_rel - upd_offset; let pos_cache = if pos_cache_rel < upd_offset { pos_cache } else { pos_cache - self.max_seq_len }; u8::from(pos_cache > pos_src || pos_cache + context < pos_src) }) }) .collect(); Tensor::from_slice(&mask, (size1, size2), device) } /// Returns the positions corresponding to all the elements that will be retured /// *after* adding `seq_len` to the cache. pub fn positions(&self, seq_len: usize) -> Vec<usize> { if seq_len <= self.max_seq_len { let upd_offset = (self.offset + seq_len) % self.max_seq_len; let cache_out_len = (self.current_seq_len + seq_len).min(self.max_seq_len); (0..cache_out_len) .map(|i| { let pos_cache = self.current_seq_len + seq_len + i - upd_offset; if i < upd_offset { pos_cache } else { pos_cache - self.max_seq_len } }) .collect() } else { (self.current_seq_len..(self.current_seq_len + seq_len)).collect() } } /// Returns the attn_mask to be applied *after* adding `seq_len` to the cache. pub fn attn_mask(&self, seq_len: usize, device: &Device) -> Result<Option<Tensor>> { let mask = if seq_len == 1 { None } else { let mask = if seq_len < self.max_seq_len { let cache_out_len = (self.current_seq_len + seq_len).min(self.max_seq_len); self.get_mask_rel(seq_len, cache_out_len, device)? } else { self.get_mask_abs(seq_len, seq_len, device)? }; Some(mask) }; Ok(mask) } } #[derive(Debug, Clone)] pub struct RotatingKvCache { k: RotatingCache, v: RotatingCache, } impl RotatingKvCache { pub fn new(dim: usize, max_seq_len: usize) -> Self { let k = RotatingCache::new(dim, max_seq_len); let v = RotatingCache::new(dim, max_seq_len); Self { k, v } } pub fn k_cache(&self) -> &RotatingCache { &self.k } pub fn v_cache(&self) -> &RotatingCache { &self.v } pub fn k_cache_mut(&mut self) -> &mut RotatingCache { &mut self.k } pub fn v_cache_mut(&mut self) -> &mut RotatingCache { &mut self.v } pub fn k(&self) -> Result<Option<Tensor>> { self.k.current_data() } pub fn v(&self) -> Result<Option<Tensor>> { self.v.current_data() } pub fn append(&mut self, k: &Tensor, v: &Tensor) -> Result<(Tensor, Tensor)> { let out_k = self.k.append(k)?; let out_v = self.v.append(v)?; Ok((out_k, out_v)) } pub fn offset(&self) -> usize { self.k.offset() } pub fn current_seq_len(&self) -> usize { self.k.current_seq_len() } /// Returns the attn_mask to be applied *after* adding `seq_len` to the cache. pub fn attn_mask(&self, seq_len: usize, device: &Device) -> Result<Option<Tensor>> { self.k.attn_mask(seq_len, device) } /// Returns the positions corresponding to all the elements that will be retured /// *after* adding `seq_len` to the cache. pub fn positions(&self, seq_len: usize) -> Vec<usize> { self.k.positions(seq_len) } pub fn reset(&mut self) { self.k.reset(); self.v.reset(); } } #[derive(Debug, Clone)] pub struct IndicesAndMask { indices: Tensor, mask: Tensor, } impl IndicesAndMask { pub fn mask(&self) -> &Tensor { &self.mask } } #[derive(Debug, Clone)] pub struct ScatteredKvCache { k: Tensor, v: Tensor, context: usize, } impl ScatteredKvCache { pub fn append( &mut self, k: &Tensor, v: &Tensor, iam: &IndicesAndMask, ) -> Result<(Tensor, Tensor)> { if self.context <= k.dim(2)? { return Ok((k.clone(), v.clone())); } let indices = iam.indices.unsqueeze(2)?.unsqueeze(1)?; let indices = indices.broadcast_as(k.shape())?.contiguous()?; self.k.scatter_set(&indices, k, 2)?; self.v.scatter_set(&indices, v, 2)?; Ok((self.k.clone(), self.v.clone())) } pub fn k(&self) -> &Tensor { &self.k } pub fn v(&self) -> &Tensor { &self.v } } #[derive(Debug, Clone)] pub struct ScatteredCacheBuilder { context: usize, // The current position in the stream, this can be larger than context. positions: Vec<usize>, // The index where the next element will be stored. indices: Vec<usize>, dtype: DType, device: Device, } impl ScatteredCacheBuilder { pub fn new(batch_size: usize, context: usize, dtype: DType, device: &Device) -> Result<Self> { let positions = vec![0; batch_size]; let indices = vec![0; batch_size]; Ok(Self { positions, indices, context, dtype, device: device.clone(), }) } pub fn make_cache(&self, num_heads: usize, head_dim: usize) -> Result<ScatteredKvCache> { let batch_size = self.batch_size(); let shape = (batch_size, num_heads, self.context, head_dim); let k = Tensor::zeros(shape, self.dtype, self.device())?; let v = Tensor::zeros(shape, self.dtype, self.device())?; Ok(ScatteredKvCache { k, v, context: self.context, }) } pub fn positions(&self) -> &[usize] { &self.positions } pub fn reset(&mut self) { self.positions.fill(0); self.indices.fill(0); } pub fn batch_size(&self) -> usize { self.positions.len() } pub fn reset_batch_index(&mut self, batch_index: usize) { self.positions[batch_index] = 0; self.indices[batch_index] = 0; } #[allow(clippy::needless_range_loop)] pub fn indices_and_mask( &mut self, seq_len: usize, batch_mask: &[bool], ) -> Result<IndicesAndMask> { // mask shape is (b, h, t, k) let context = self.context; if self.context <= seq_len { return self.indices_and_mask_abs(seq_len, batch_mask); } let mut attention_masks = Vec::with_capacity(self.batch_size()); let mut cache_indices = Vec::with_capacity(self.batch_size()); for (batch_i, &batch_mask) in batch_mask.iter().enumerate() { if !batch_mask { let masks: Vec<Vec<f32>> = vec![vec![0.0; context]; seq_len]; let indices = vec![self.indices[batch_i] as u32; seq_len]; attention_masks.push(masks); cache_indices.push(indices); } else { let start_index = self.indices[batch_i]; let start_pos = self.positions[batch_i]; let mut masks: Vec<Vec<f32>> = Vec::with_capacity(seq_len); let mut indices = Vec::with_capacity(seq_len); let mut all_pos = vec![usize::MAX; context]; if start_pos < context { for i in 0..start_pos { all_pos[i] = i; } } else { let offset = start_pos - start_index; for i in 0..context { all_pos[i] = if i < start_index { i + offset } else { i + offset - context }; } } for seq_i in 0..seq_len { let index = self.indices[batch_i]; all_pos[index] = seq_i + start_pos; indices.push(index as u32); self.indices[batch_i] += 1; self.positions[batch_i] += 1; if self.indices[batch_i] >= self.context { self.indices[batch_i] = 0; } } for seq_i in 0..seq_len { let my_pos = seq_i + start_pos; let mask = all_pos .iter() .map(|&pos| { if pos <= my_pos { 0.0 } else { f32::NEG_INFINITY } }) .collect::<Vec<f32>>(); masks.push(mask); } attention_masks.push(masks); cache_indices.push(indices); } } // Flattening the attention mask then using Tensor::from_vec rather using Tensor::new ends // up being almost 10x faster with candle 0.9.0. This has been fixed in candle 0.9.1. let attention_masks = attention_masks .into_iter() .flat_map(|m| m.into_iter().flatten()) .collect::<Vec<f32>>(); let mask = Tensor::from_vec(attention_masks, ((), 1, seq_len, context), self.device())? .to_dtype(self.dtype)?; let indices = Tensor::new(cache_indices, self.device())?; Ok(IndicesAndMask { indices, mask }) } pub fn device(&self) -> &Device { &self.device } #[allow(clippy::needless_range_loop)] fn indices_and_mask_abs( &mut self, seq_len: usize, batch_mask: &[bool], ) -> Result<IndicesAndMask> { let mask = self.get_mask_abs(seq_len, seq_len)?; let mut cache_indices = Vec::with_capacity(self.batch_size()); for (batch_i, &batch_mask) in batch_mask.iter().enumerate() { if !batch_mask { let indices = vec![self.indices[batch_i] as u32; seq_len]; cache_indices.push(indices); } else { let mut indices = Vec::with_capacity(seq_len); for _ in 0..seq_len { let index = self.indices[batch_i]; indices.push(index as u32); self.indices[batch_i] += 1; self.positions[batch_i] += 1; if self.indices[batch_i] >= self.context { self.indices[batch_i] = 0; } } cache_indices.push(indices); } } let indices = Tensor::new(cache_indices, self.device())?; Ok(IndicesAndMask { indices, mask }) } fn get_mask_abs(&self, size1: usize, size2: usize) -> Result<Tensor> { let context = self.context; let mask: Vec<_> = (0..size1) .flat_map(|i| { (0..size2).map(move |j| { if size1 + j > size2 + i || size1 + j + context < size2 + i { f32::NEG_INFINITY } else { 0.0 } }) }) .collect(); Tensor::from_slice(&mask, (size1, size2), self.device()) } } #[cfg(test)] mod tests { use super::*; use candle::IndexOp; #[test] fn test_scattered_kv_cache() -> Result<()> { let device = Device::Cpu; let mut cache = ScatteredCacheBuilder::new(2, 5, DType::F32, &device)?; let inf = f32::INFINITY; let iam = cache.indices_and_mask(1, &[true, false])?; let mask = iam.mask.i((.., 0))?.to_vec3::<f32>()?; assert_eq!(iam.indices.to_vec2::<u32>()?, [[0], [0]]); assert_eq!( mask, [[[0.0, -inf, -inf, -inf, -inf]], [[0.0, 0.0, 0.0, 0.0, 0.0]]] ); let iam = cache.indices_and_mask(1, &[true, false])?; let mask = iam.mask.i((.., 0))?.to_vec3::<f32>()?; assert_eq!(iam.indices.to_vec2::<u32>()?, [[1], [0]]); assert_eq!( mask, [[[0.0, 0.0, -inf, -inf, -inf]], [[0.0, 0.0, 0.0, 0.0, 0.0]]] ); let iam = cache.indices_and_mask(3, &[false, true])?; let mask = iam.mask.i((.., 0))?.to_vec3::<f32>()?; assert_eq!(iam.indices.to_vec2::<u32>()?, [[2, 2, 2], [0, 1, 2]]); assert_eq!( mask, [ [ [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0] ], [ [0.0, -inf, -inf, -inf, -inf], [0.0, 0.0, -inf, -inf, -inf], [0.0, 0.0, 0.0, -inf, -inf] ] ] ); let iam = cache.indices_and_mask(3, &[true, true])?; let mask = iam.mask.i((.., 0))?.to_vec3::<f32>()?; assert_eq!(iam.indices.to_vec2::<u32>()?, [[2, 3, 4], [3, 4, 0]]); assert_eq!( mask, [ [ [0.0, 0.0, 0.0, -inf, -inf], [0.0, 0.0, 0.0, 0.0, -inf], [0.0, 0.0, 0.0, 0.0, 0.0] ], [ [-inf, 0.0, 0.0, 0.0, -inf], [-inf, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0] ] ] ); let iam = cache.indices_and_mask(1, &[true, false])?; let mask = iam.mask.i((.., 0))?.to_vec3::<f32>()?; assert_eq!(iam.indices.to_vec2::<u32>()?, [[0], [1]]); assert_eq!( mask, [[[0.0, 0.0, 0.0, 0.0, 0.0]], [[0.0, 0.0, 0.0, 0.0, 0.0]]] ); let iam = cache.indices_and_mask(2, &[true, false])?; let mask = iam.mask.i((.., 0))?.to_vec3::<f32>()?; assert_eq!(iam.indices.to_vec2::<u32>()?, [[1, 2], [1, 1]]); assert_eq!( mask, [ [[0.0, 0.0, -inf, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0]], [[0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0]] ] ); Ok(()) } }
candle/candle-nn/src/kv_cache.rs/0
{ "file_path": "candle/candle-nn/src/kv_cache.rs", "repo_id": "candle", "token_count": 12514 }
53
#[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; use anyhow::Result; use candle::{test_utils, Device, Tensor}; use candle_nn::{LayerNorm, Module}; #[test] fn layer_norm() -> Result<()> { let device = &Device::Cpu; let w = Tensor::new(&[3f32], device)?; let b = Tensor::new(&[0.5f32], device)?; let ln2 = LayerNorm::new(Tensor::cat(&[&w, &w], 0)?, Tensor::cat(&[&b, &b], 0)?, 1e-8); let ln3 = LayerNorm::new( Tensor::cat(&[&w, &w, &w], 0)?, Tensor::cat(&[&b, &b, &b], 0)?, 1e-8, ); let ln = LayerNorm::new(w, b, 1e-8); let two = Tensor::new(&[[[2f32]]], device)?; let res = ln.forward(&two)?.flatten_all()?; assert_eq!(res.to_vec1::<f32>()?, [0.5f32]); let inp = Tensor::new(&[[[4f32, 0f32]]], device)?; let res = ln2.forward(&inp)?; assert_eq!(res.to_vec3::<f32>()?, [[[3.5f32, -2.5]]]); let inp = Tensor::new(&[[[1f32, 2., 3.], [4., 5., 6.], [9., 8., 7.]]], device)?; let res = ln3.forward(&inp)?; assert_eq!( test_utils::to_vec3_round(&res, 4)?, [[ [-3.1742, 0.5, 4.1742], [-3.1742, 0.5, 4.1742], [4.1742, 0.5, -3.1742] ]] ); let mean = (res.sum_keepdim(2)? / 3.0)?; // The average value should be `b`. assert_eq!( test_utils::to_vec3_round(&mean, 4)?, [[[0.5], [0.5], [0.5]]] ); let std = (res.broadcast_sub(&mean)?.sqr()?.sum_keepdim(2)?.sqrt()? / 3.0)?; // The standard deviation should be sqrt(`w`). assert_eq!( test_utils::to_vec3_round(&std, 4)?, [[[1.7321], [1.7321], [1.7321]]] ); Ok(()) }
candle/candle-nn/tests/layer_norm.rs/0
{ "file_path": "candle/candle-nn/tests/layer_norm.rs", "repo_id": "candle", "token_count": 892 }
54
## Installation From the `candle-pyo3` directory, enable a virtual env where you will want the candle package to be installed then run. ```bash maturin develop -r python test.py ``` ## Generating Stub Files for Type Hinting For type hinting support, the `candle-pyo3` package requires `*.pyi` files. You can automatically generate these files using the `stub.py` script. ### Steps: 1. Install the package using `maturin`. 2. Generate the stub files by running: ``` python stub.py ``` ### Validation: To ensure that the stub files match the current implementation, execute: ``` python stub.py --check ```
candle/candle-pyo3/README.md/0
{ "file_path": "candle/candle-pyo3/README.md", "repo_id": "candle", "token_count": 190 }
55
import candle from candle import Tensor from .module import Module from typing import Union, List, Tuple, Optional, Any _shape_t = Union[int, List[int]] import numbers class LayerNorm(Module): r"""Applies Layer Normalization over a mini-batch of inputs as described in the paper `Layer Normalization <https://arxiv.org/abs/1607.06450>` math:: y = \frac{x - \mathrm{E}[x]}{ \sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta """ __constants__ = ["normalized_shape", "eps"] normalized_shape: Tuple[int, ...] eps: float def __init__( self, normalized_shape: _shape_t, eps: float = 1e-5, bias: bool = True, device=None, dtype=None, ) -> None: factory_kwargs = {"device": device, "dtype": dtype} super().__init__() if isinstance(normalized_shape, numbers.Integral): normalized_shape = (normalized_shape,) self.normalized_shape = tuple(normalized_shape) self.eps = eps self.weight = candle.ones(normalized_shape, **factory_kwargs) if bias: self.bias = candle.zeros(normalized_shape, **factory_kwargs) else: self.bias = None def forward(self, input: Tensor) -> Tensor: mean_x = input.sum_keepdim(2) / float(self.normalized_shape[-1]) x = input.broadcast_sub(mean_x) norm_x = x.sqr().sum_keepdim(2) / float(self.normalized_shape[-1]) x_normed = x.broadcast_div((norm_x + self.eps).sqrt()) x = x_normed.broadcast_mul(self.weight) if self.bias: x = x.broadcast_add(self.bias) return x def extra_repr(self) -> str: return "{normalized_shape}, eps={eps}, " "elementwise_affine={elementwise_affine}".format(**self.__dict__)
candle/candle-pyo3/py_src/candle/nn/normalization.py/0
{ "file_path": "candle/candle-pyo3/py_src/candle/nn/normalization.py", "repo_id": "candle", "token_count": 803 }
56
import candle import torch # convert from candle tensor to torch tensor t = candle.randn((3, 512, 512)) torch_tensor = t.to_torch() print(torch_tensor) print(type(torch_tensor)) # convert from torch tensor to candle tensor t = torch.randn((3, 512, 512)) candle_tensor = candle.Tensor(t) print(candle_tensor) print(type(candle_tensor))
candle/candle-pyo3/test_pytorch.py/0
{ "file_path": "candle/candle-pyo3/test_pytorch.py", "repo_id": "candle", "token_count": 126 }
57
//! Based on the BLIP paper from Salesforce Research. //! //! The blip-image-captioning model can generate captions for an input image. //! //! - ⚡ [Interactive Wasm Example](https://huggingface.co/spaces/radames/Candle-BLIP-Image-Captioning) //! - 💻 [GH Link](https://github.com/salesforce/BLIP) //! - 🤗 [HF Link](https://huggingface.co/Salesforce/blip-image-captioning-base) //! - 📝 [Paper](https://arxiv.org/abs/2201.12086) //! use super::blip_text; use super::with_tracing::{conv2d, linear, Conv2d, Linear}; use candle::{Module, Result, Tensor, D}; use candle_nn::{layer_norm, Conv2dConfig, LayerNorm, VarBuilder}; use serde::Deserialize; #[derive(Debug, Clone, Deserialize)] pub struct VisionConfig { pub hidden_size: usize, pub intermediate_size: usize, pub projection_dim: usize, pub num_hidden_layers: usize, pub num_attention_heads: usize, pub image_size: usize, pub patch_size: usize, pub hidden_act: candle_nn::Activation, pub layer_norm_eps: f64, } #[derive(Debug, Clone, Deserialize)] pub struct Config { pub text_config: blip_text::Config, pub vision_config: VisionConfig, pub projection_dim: usize, pub image_text_hidden_size: usize, } impl Config { pub fn image_captioning_large() -> Self { let text_config = blip_text::Config { vocab_size: 30524, hidden_size: 768, encoder_hidden_size: 1024, intermediate_size: 3072, projection_dim: 768, num_hidden_layers: 12, num_attention_heads: 12, max_position_embeddings: 512, hidden_act: candle_nn::Activation::Gelu, layer_norm_eps: 1e-12, is_decoder: true, }; let vision_config = VisionConfig { hidden_size: 1024, intermediate_size: 4096, projection_dim: 512, num_hidden_layers: 24, num_attention_heads: 16, image_size: 384, patch_size: 16, hidden_act: candle_nn::Activation::Gelu, layer_norm_eps: 1e-5, }; Self { text_config, vision_config, projection_dim: 512, image_text_hidden_size: 256, } } } #[derive(Debug, Clone)] struct VisionEmbeddings { class_embedding: Tensor, patch_embedding: Conv2d, position_embedding: Tensor, } impl VisionEmbeddings { fn new(cfg: &VisionConfig, vb: VarBuilder) -> Result<Self> { let class_embedding = vb.get((1, 1, cfg.hidden_size), "class_embedding")?; let conv_cfg = Conv2dConfig { stride: cfg.patch_size, ..Default::default() }; let patch_embedding = conv2d( 3, cfg.hidden_size, cfg.patch_size, conv_cfg, vb.pp("patch_embedding"), )?; let num_patches1 = cfg.image_size / cfg.patch_size; let num_patches = num_patches1 * num_patches1; let num_positions = num_patches + 1; let position_embedding = vb.get((1, num_positions, cfg.hidden_size), "position_embedding")?; Ok(Self { class_embedding, patch_embedding, position_embedding, }) } } impl Module for VisionEmbeddings { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let target_dtype = xs.dtype(); let b_size = xs.dim(0)?; let patch_embeds = xs.apply(&self.patch_embedding)?.flatten_from(2)?.t()?; let d = self.class_embedding.dim(D::Minus1)?; let class_embeds = self .class_embedding .broadcast_as((b_size, 1, d))? .to_dtype(target_dtype)?; let embeddings = Tensor::cat(&[&class_embeds, &patch_embeds], 1)?; let position_embedding = self.position_embedding.narrow(1, 0, embeddings.dim(1)?)?; embeddings.broadcast_add(&position_embedding) } } #[derive(Debug, Clone)] struct Attention { qkv: Linear, projection: Linear, scale: f64, num_heads: usize, } impl Attention { fn new(cfg: &VisionConfig, vb: VarBuilder) -> Result<Self> { let embed_dim = cfg.hidden_size; let num_heads = cfg.num_attention_heads; let head_dim = embed_dim / num_heads; let scale = 1f64 / (head_dim as f64).sqrt(); let qkv = linear(embed_dim, 3 * embed_dim, vb.pp("qkv"))?; let projection = linear(embed_dim, embed_dim, vb.pp("projection"))?; Ok(Self { qkv, projection, scale, num_heads, }) } fn forward(&self, xs: &Tensor, attn_mask: Option<&Tensor>) -> Result<Tensor> { let (b_sz, tgt_len, embed_dim) = xs.dims3()?; let mixed_qkv = xs .apply(&self.qkv)? .reshape((b_sz, tgt_len, 3, self.num_heads, embed_dim / self.num_heads))? .permute((2, 0, 3, 1, 4))?; let query = mixed_qkv.get(0)?; let key = mixed_qkv.get(1)?; let value = mixed_qkv.get(2)?; let attention_scores = query.matmul(&key.t()?)?; let attention_scores = (attention_scores * self.scale)?; let attention_probs = candle_nn::ops::softmax_last_dim(&attention_scores)?; let attention_probs = match attn_mask { None => attention_probs, Some(attn_mask) => (attention_probs * attn_mask)?, }; attention_probs .matmul(&value)? .permute((0, 2, 1, 3))? .flatten_from(D::Minus2)? .apply(&self.projection) } } #[derive(Debug, Clone)] #[allow(clippy::upper_case_acronyms)] struct MLP { activation_fn: candle_nn::Activation, fc1: Linear, fc2: Linear, } impl MLP { fn new(cfg: &VisionConfig, vb: VarBuilder) -> Result<Self> { let fc1 = linear(cfg.hidden_size, cfg.intermediate_size, vb.pp("fc1"))?; let fc2 = linear(cfg.intermediate_size, cfg.hidden_size, vb.pp("fc2"))?; Ok(Self { activation_fn: cfg.hidden_act, fc1, fc2, }) } } impl Module for MLP { fn forward(&self, xs: &Tensor) -> Result<Tensor> { xs.apply(&self.fc1)? .apply(&self.activation_fn)? .apply(&self.fc2) } } #[derive(Debug, Clone)] struct EncoderLayer { self_attn: Attention, layer_norm1: LayerNorm, mlp: MLP, layer_norm2: LayerNorm, } impl EncoderLayer { fn new(cfg: &VisionConfig, vb: VarBuilder) -> Result<Self> { let embed_dim = cfg.hidden_size; let self_attn = Attention::new(cfg, vb.pp("self_attn"))?; let layer_norm1 = layer_norm(embed_dim, cfg.layer_norm_eps, vb.pp("layer_norm1"))?; let layer_norm2 = layer_norm(embed_dim, cfg.layer_norm_eps, vb.pp("layer_norm2"))?; let mlp = MLP::new(cfg, vb.pp("mlp"))?; Ok(Self { self_attn, layer_norm1, mlp, layer_norm2, }) } fn forward(&self, xs: &Tensor, attention_mask: Option<&Tensor>) -> Result<Tensor> { let residual = xs; let xs = xs.apply(&self.layer_norm1)?; let xs = self.self_attn.forward(&xs, attention_mask)?; let xs = (xs + residual)?; let residual = &xs; let xs = xs.apply(&self.layer_norm2)?.apply(&self.mlp)?; xs + residual } } #[derive(Debug, Clone)] struct Encoder { layers: Vec<EncoderLayer>, } impl Encoder { fn new(cfg: &VisionConfig, vb: VarBuilder) -> Result<Self> { let mut layers = Vec::with_capacity(cfg.num_hidden_layers); let vb = vb.pp("layers"); for i in 0..cfg.num_hidden_layers { let layer = EncoderLayer::new(cfg, vb.pp(i))?; layers.push(layer) } Ok(Self { layers }) } fn forward(&self, xs: &Tensor, attention_mask: Option<&Tensor>) -> Result<Tensor> { let mut xs = xs.clone(); for layer in self.layers.iter() { xs = layer.forward(&xs, attention_mask)? } Ok(xs) } } #[derive(Debug, Clone)] pub struct VisionModel { embeddings: VisionEmbeddings, encoder: Encoder, post_layernorm: LayerNorm, } impl VisionModel { fn new(cfg: &VisionConfig, vb: VarBuilder) -> Result<Self> { let embeddings = VisionEmbeddings::new(cfg, vb.pp("embeddings"))?; let encoder = Encoder::new(cfg, vb.pp("encoder"))?; let post_layernorm = layer_norm(cfg.hidden_size, cfg.layer_norm_eps, vb.pp("post_layernorm"))?; Ok(Self { embeddings, encoder, post_layernorm, }) } } impl Module for VisionModel { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let xs = xs.apply(&self.embeddings)?; let encoder_outputs = self.encoder.forward(&xs, None)?; // Return the last hidden state rather than pooled outputs. encoder_outputs.apply(&self.post_layernorm) } } #[derive(Debug, Clone)] pub struct BlipForConditionalGeneration { vision_model: VisionModel, text_decoder: blip_text::TextLMHeadModel, } impl BlipForConditionalGeneration { pub fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let vision_model = VisionModel::new(&cfg.vision_config, vb.pp("vision_model"))?; let text_decoder = blip_text::TextLMHeadModel::new(&cfg.text_config, vb.pp("text_decoder"))?; Ok(Self { vision_model, text_decoder, }) } pub fn vision_model(&self) -> &VisionModel { &self.vision_model } pub fn text_decoder(&mut self) -> &mut blip_text::TextLMHeadModel { &mut self.text_decoder } pub fn reset_kv_cache(&mut self) { self.text_decoder.reset_kv_cache(); } }
candle/candle-transformers/src/models/blip.rs/0
{ "file_path": "candle/candle-transformers/src/models/blip.rs", "repo_id": "candle", "token_count": 4762 }
58
#![allow(clippy::cast_possible_truncation, clippy::cast_precision_loss)] use std::{f32::consts::PI, sync::Arc}; use candle::{ shape::Dim, CpuStorage, CustomOp1, DType, Device, Error, IndexOp, Layout, Result, Shape, Tensor, WithDType, D, }; use candle_nn::{embedding, rms_norm, Activation, Embedding, Linear, Module, RmsNorm, VarBuilder}; use rayon::iter::{IntoParallelRefIterator, ParallelIterator}; use serde::Deserialize; struct NonZero {} impl NonZero { // Sequential version fn nonzero<T: WithDType>(&self, vs: &[T], layout: &Layout) -> Vec<u32> { let n = layout.dims().len(); let mut result = Vec::new(); let mut indices = vec![0u32; n]; for (i, v) in vs.iter().enumerate() { if !v.is_zero() { let mut idx = i; for (dim_index, dim) in layout.dims().iter().enumerate().rev() { let d = idx % dim; indices[dim_index] = u32::try_from(d).unwrap(); idx /= dim; } result.extend_from_slice(&indices); } } result } } impl CustomOp1 for NonZero { fn name(&self) -> &'static str { "nonzero" } fn cpu_fwd(&self, storage: &CpuStorage, layout: &Layout) -> Result<(CpuStorage, Shape)> { if !layout.is_contiguous() { return Err(Error::RequiresContiguous { op: "nonzero" }); } let result = match storage { candle::CpuStorage::U8(vs) => self.nonzero(vs, layout), candle::CpuStorage::U32(vs) => self.nonzero(vs, layout), candle::CpuStorage::I64(vs) => self.nonzero(vs, layout), candle::CpuStorage::BF16(vs) => self.nonzero(vs, layout), candle::CpuStorage::F16(vs) => self.nonzero(vs, layout), candle::CpuStorage::F32(vs) => self.nonzero(vs, layout), candle::CpuStorage::F64(vs) => self.nonzero(vs, layout), candle::CpuStorage::F8E4M3(vs) => self.nonzero(vs, layout), }; let index_len = layout.dims().len(); let result_len = result.len() / index_len; let result = CpuStorage::U32(result); let shape = Shape::from_dims(&[result_len, index_len]); Ok((result, shape)) } } pub trait NonZeroOp { fn nonzero(&self) -> Result<Tensor>; } impl NonZeroOp for Tensor { fn nonzero(&self) -> Result<Tensor> { if !self.is_contiguous() { return Err(candle::Error::RequiresContiguous { op: "nonzero" }); } let original_device = self.device(); self.to_device(&candle::Device::Cpu)? .apply_op1_no_bwd(&NonZero {})? .to_device(original_device) } } pub struct TopKOutput { pub values: Tensor, pub indices: Tensor, } pub trait TopKLastDimOp { /// Topk in the last dim. `values` retains a gradient but `indices` has none w.r.t self. /// This expects a contiguous tensor. /// Note: this implements torch.topk with sorted=True. fn topk(&self, topk: usize) -> Result<TopKOutput>; /// Topk in the last dim. `values` retains a gradient but `indices` has none w.r.t self. /// This expects a contiguous tensor. /// Note: this implements torch.topk with sorted=False. fn topk_unsorted(&self, topk: usize) -> Result<TopKOutput>; } impl TopKLastDimOp for Tensor { fn topk(&self, topk: usize) -> Result<TopKOutput> { // Sorted descending let sorted_indices = self.arg_sort_last_dim(false)?; let topk_indices = sorted_indices.narrow(D::Minus1, 0, topk)?.contiguous()?; Ok(TopKOutput { values: self.gather(&topk_indices, D::Minus1)?, indices: topk_indices, }) } fn topk_unsorted(&self, topk: usize) -> Result<TopKOutput> { // Sorted descending let sorted_indices_all = self.arg_sort_last_dim(false)?; let topk_indices_sorted = sorted_indices_all .narrow(D::Minus1, 0, topk)? .contiguous()?; let topk_values_sorted = self.gather(&topk_indices_sorted, D::Minus1)?; // Reorder the indices ascending let reorder_indices = topk_indices_sorted.arg_sort_last_dim(true)?; let topk_indices_unsorted = topk_indices_sorted.gather(&reorder_indices, D::Minus1)?; let topk_values_unsorted = topk_values_sorted.gather(&reorder_indices, D::Minus1)?; Ok(TopKOutput { values: topk_values_unsorted, indices: topk_indices_unsorted, }) } } pub trait SplitOp { fn split<D: Dim>(&self, splits: &[usize], dim: D) -> Result<Vec<Tensor>>; } impl SplitOp for Tensor { fn split<D: Dim>(&self, splits: &[usize], dim: D) -> Result<Vec<Tensor>> { let dim = dim.to_index(self.shape(), "split")?; let mut split_res = Vec::new(); let mut index = 0; for split in splits { split_res.push(self.narrow(dim, index, *split)?); index += *split; } Ok(split_res) } } pub trait BincountOp { fn bincount(&self, minlength: u32) -> Result<Vec<u32>>; } fn bincount(values: &[u32], minlength: u32) -> Vec<u32> { // Find the maximum value in `values` (or zero if empty) let max_val = values.par_iter().max().copied().unwrap_or(0); // The final size of the bin counts must be at least `minlength` // and large enough to include the largest value in `values`. let result_len = (max_val + 1).max(minlength); // Each thread creates a local histogram (`fold`), // and then they are merged together (`reduce`). values .par_iter() .fold( // Create a local histogram || vec![0u32; result_len as usize], // Update the local histogram |mut local_counts, &val| { local_counts[val as usize] += 1; local_counts }, ) // Merge histograms from all threads .reduce( // Identity (empty histogram) || vec![0u32; result_len as usize], // Combine two histograms |mut global_counts, local_counts| { for (g, l) in global_counts.iter_mut().zip(local_counts) { *g += l; } global_counts }, ) } impl BincountOp for Tensor { fn bincount(&self, minlength: u32) -> Result<Vec<u32>> { let values = self.to_vec1::<u32>()?; Ok(bincount(&values, minlength)) } } fn masked_fill(on_false: &Tensor, mask: &Tensor, on_true: f32) -> Result<Tensor> { let shape = mask.shape(); let on_true = Tensor::new(on_true, on_false.device())?.broadcast_as(shape.dims())?; let m = mask.where_cond(&on_true, on_false)?; Ok(m) } #[doc(hidden)] #[macro_export] macro_rules! serde_default_fn { ($t:ty, $name:ident, $v:expr) => { fn $name() -> $t { $v } }; } serde_default_fn!(f64, routed_scaling_factor, 1.0); serde_default_fn!(TopkMethod, topk_method, TopkMethod::Greedy); serde_default_fn!(usize, moe_layer_freq, 1); serde_default_fn!(usize, first_k_dense_replace, 0); serde_default_fn!(bool, norm_topk_prob, false); serde_default_fn!(ScoringFunc, scoring_func, ScoringFunc::Softmax); serde_default_fn!(Activation, hidden_act, Activation::Silu); serde_default_fn!(bool, tie_word_embeddings, false); #[derive(Deserialize, Clone, Debug)] enum TopkMethod { #[serde(rename = "greedy")] Greedy, #[serde(rename = "group_limited_greedy")] GroupLimitedGreedy, } #[derive(Deserialize, Clone, Debug)] enum ScoringFunc { #[serde(rename = "softmax")] Softmax, } #[derive(Deserialize, Clone, Debug)] pub struct DeepSeekV2Config { pub(crate) vocab_size: usize, pub(crate) hidden_size: usize, pub(crate) intermediate_size: usize, pub(crate) moe_intermediate_size: usize, pub(crate) num_hidden_layers: usize, pub(crate) num_attention_heads: usize, pub(crate) n_shared_experts: Option<usize>, pub(crate) n_routed_experts: Option<usize>, #[serde(default = "routed_scaling_factor")] pub(crate) routed_scaling_factor: f64, #[serde(default = "topk_method")] topk_method: TopkMethod, pub(crate) num_experts_per_tok: Option<usize>, #[serde(default = "moe_layer_freq")] pub(crate) moe_layer_freq: usize, #[serde(default = "first_k_dense_replace")] pub(crate) first_k_dense_replace: usize, // k dense layers #[serde(default = "norm_topk_prob")] pub(crate) norm_topk_prob: bool, #[serde(default = "scoring_func")] scoring_func: ScoringFunc, #[serde(default = "hidden_act")] pub(crate) hidden_act: Activation, pub(crate) max_position_embeddings: usize, pub(crate) rms_norm_eps: f64, #[serde(default = "tie_word_embeddings")] pub(crate) tie_word_embeddings: bool, pub(crate) rope_theta: f32, pub(crate) rope_scaling: Option<DeepSeekV2RopeScaling>, pub(crate) attention_bias: bool, pub(crate) q_lora_rank: Option<usize>, pub(crate) qk_rope_head_dim: usize, pub(crate) kv_lora_rank: usize, pub(crate) v_head_dim: usize, pub(crate) qk_nope_head_dim: usize, pub(crate) n_group: usize, pub(crate) topk_group: usize, } #[derive(Debug, Clone, Deserialize)] #[serde(rename_all = "lowercase")] pub enum ScaledRopeType { #[serde(alias = "su")] #[serde(alias = "longrope")] Su, #[serde(alias = "yarn")] Yarn, #[serde(alias = "dynamic")] Dynamic, #[serde(alias = "linear")] Linear, } #[derive(Debug, Clone)] pub struct DeepSeekV2RotaryEmbedding { sin: Tensor, cos: Tensor, } #[derive(Debug, Clone, Deserialize)] #[serde(untagged)] pub enum DeepSeekV2RopeScaling { Yarn { original_max_position_embeddings: usize, beta_fast: f32, beta_slow: f32, mscale: f32, mscale_all_dim: f32, factor: f32, #[serde(rename = "type")] scaling_type: ScaledRopeType, }, LinearOrDynamic { #[serde(rename = "type")] scaling_type: ScaledRopeType, factor: f64, }, } pub struct DeepSeekV2RopeConfig { pub rope_scaling: Option<DeepSeekV2RopeScaling>, pub max_position_embeddings: usize, pub rope_theta: f32, pub qk_rope_head_dim: usize, } impl DeepSeekV2RotaryEmbedding { fn new_unscaled(cfg: &DeepSeekV2RopeConfig, dtype: DType, dev: &Device) -> Result<Self> { let max_seq_len = cfg.max_position_embeddings; let dim = cfg.qk_rope_head_dim; let inv_freq: Vec<_> = (0..dim) .step_by(2) .map(|i| 1f32 / cfg.rope_theta.powf(i as f32 / dim as f32)) .collect(); let inv_freq_len = inv_freq.len(); let inv_freq = Tensor::from_vec(inv_freq, (1, inv_freq_len), dev)?; let t = Tensor::arange(0u32, max_seq_len as u32, dev)? .to_dtype(DType::F32)? .reshape((max_seq_len, 1))?; let freqs = t.matmul(&inv_freq)?; let sin = freqs.sin()?.to_dtype(dtype)?; let cos = freqs.cos()?.to_dtype(dtype)?; Ok(Self { sin, cos }) } fn yarn_find_correction_dim( num_rot: f32, dim: usize, base: f32, max_position_embeddings: usize, ) -> f32 { (dim as f32 * (max_position_embeddings as f32 / (num_rot * 2. * PI)).ln()) / (2. * base.ln()) } fn yarn_find_correction_range( low_rot: f32, high_rot: f32, dim: usize, base: f32, max_position_embeddings: usize, ) -> (f32, f32) { let low = Self::yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings).floor(); let high = Self::yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings).ceil(); (low.max(0.), high.min(dim as f32 - 1.)) } fn yarn_linear_ramp_mask(min: f32, mut max: f32, dim: usize, dev: &Device) -> Result<Tensor> { if min == max { // https://huggingface.co/deepseek-ai/DeepSeek-V2-Lite/blob/604d5664dddd88a0433dbae533b7fe9472482de0/modeling_deepseek.py#L255 max += 0.001; } let linear_func = ((Tensor::arange(0f32, dim as f32, dev)? - min as f64)? / (max as f64 - min as f64))?; linear_func.clamp(0., 1.) } pub(crate) fn yarn_get_mscale(scale: f32, mscale: f32) -> f32 { if scale <= 1. { return 1.; } 0.1 * mscale * scale.ln() + 1. } #[allow(clippy::too_many_arguments)] fn new_yarn( cfg: &DeepSeekV2RopeConfig, dtype: DType, dev: &Device, original_max_position_embeddings: usize, beta_fast: f32, beta_slow: f32, factor: f32, mscale: f32, mscale_all_dim: f32, ) -> Result<Self> { let freq_extra: Vec<_> = (0..cfg.qk_rope_head_dim) .step_by(2) .map(|i| 1f32 / cfg.rope_theta.powf(i as f32 / cfg.qk_rope_head_dim as f32)) .collect(); let freq_extra_len = freq_extra.len(); let freq_extra = Tensor::from_vec(freq_extra, freq_extra_len, dev)?; let freq_inter: Vec<_> = (0..cfg.qk_rope_head_dim) .step_by(2) .map(|i| 1f32 / (factor * cfg.rope_theta.powf(i as f32 / cfg.qk_rope_head_dim as f32))) .collect(); let freq_inter_len = freq_inter.len(); let freq_inter = Tensor::from_vec(freq_inter, (1, freq_inter_len), dev)?; let (low, high) = Self::yarn_find_correction_range( beta_fast, beta_slow, cfg.qk_rope_head_dim, cfg.rope_theta, original_max_position_embeddings, ); let inv_freq_mask = (1. - Self::yarn_linear_ramp_mask(low, high, cfg.qk_rope_head_dim / 2, dev)?)?; let inv_freq = freq_inter .broadcast_mul(&(1. - &inv_freq_mask)?)? .broadcast_add(&freq_extra.broadcast_mul(&inv_freq_mask)?)?; let t = Tensor::arange(0u32, cfg.max_position_embeddings as u32, dev)? .to_dtype(DType::F32)? .reshape((cfg.max_position_embeddings, 1))?; let freqs = t.matmul(&inv_freq)?; let mscale = Self::yarn_get_mscale(factor, mscale) / Self::yarn_get_mscale(factor, mscale_all_dim); let sin = (freqs.sin()? * mscale as f64)?.to_dtype(dtype)?; let cos = (freqs.cos()? * mscale as f64)?.to_dtype(dtype)?; Ok(Self { sin, cos }) } pub fn new(cfg: &DeepSeekV2RopeConfig, dtype: DType, dev: &Device) -> Result<Self> { match &cfg.rope_scaling { Some(DeepSeekV2RopeScaling::LinearOrDynamic { scaling_type: _, factor: _, }) => candle::bail!("linear and dynamic rope are not implemented yet!"), Some(DeepSeekV2RopeScaling::Yarn { original_max_position_embeddings, beta_fast, beta_slow, factor, mscale, mscale_all_dim, scaling_type: _, }) => Self::new_yarn( cfg, dtype, dev, *original_max_position_embeddings, *beta_fast, *beta_slow, *factor, *mscale, *mscale_all_dim, ), None => Self::new_unscaled(cfg, dtype, dev), } } pub fn forward( &self, q: &Tensor, k: &Tensor, seqlen_offset: usize, ) -> Result<(Tensor, Tensor)> { let (_b_sz, _h, seq_len, _n_embd) = q.dims4()?; let sin = self.sin.narrow(0, seqlen_offset, seq_len)?; let cos = self.cos.narrow(0, seqlen_offset, seq_len)?; let q_embed = candle_nn::rotary_emb::rope_i(&q.contiguous()?, &cos, &sin)?; let k_embed = candle_nn::rotary_emb::rope_i(&k.contiguous()?, &cos, &sin)?; Ok((q_embed, k_embed)) } } impl DeepSeekV2Config { pub(crate) fn q_head_dim(&self) -> usize { self.qk_rope_head_dim + self.qk_nope_head_dim } fn softmax_scale(&self) -> f32 { let mut softmax_scale = 1.0 / (self.q_head_dim() as f32).sqrt(); if let Some(DeepSeekV2RopeScaling::Yarn { mscale_all_dim, factor, .. }) = self.rope_scaling { let mscale = DeepSeekV2RotaryEmbedding::yarn_get_mscale(factor, mscale_all_dim); softmax_scale = softmax_scale * mscale * mscale; } softmax_scale } } enum QProj { Plain(Linear), Lora { a: Linear, norm: RmsNorm, b: Linear }, } impl QProj { fn forward(&self, xs: &Tensor) -> Result<Tensor> { match self { Self::Lora { a, norm, b } => b.forward(&norm.forward(&a.forward(xs)?)?), Self::Plain(lin) => lin.forward(xs), } } } struct Attention { q: QProj, kv_a_proj_with_mqa: Linear, kv_a_layernorm: RmsNorm, kv_b_proj: Linear, o_proj: Linear, rotary_emb: Arc<DeepSeekV2RotaryEmbedding>, cfg: DeepSeekV2Config, q_head_dim: usize, softmax_scale: f64, kv_cache: Option<(Tensor, Tensor)>, } impl Attention { fn new( rotary_emb: Arc<DeepSeekV2RotaryEmbedding>, cfg: &DeepSeekV2Config, vb: VarBuilder, ) -> Result<Self> { let q_head_dim = cfg.q_head_dim(); let q = match cfg.q_lora_rank { Some(lora_rank) => { let a = candle_nn::linear_b( cfg.hidden_size, lora_rank, cfg.attention_bias, vb.pp("q_a_proj"), )?; let norm = rms_norm(lora_rank, cfg.rms_norm_eps, vb.pp("q_a_layernorm"))?; let b = candle_nn::linear_no_bias( lora_rank, cfg.num_attention_heads * q_head_dim, vb.pp("q_b_proj"), )?; QProj::Lora { a, norm, b } } None => QProj::Plain(candle_nn::linear_no_bias( cfg.hidden_size, cfg.num_attention_heads * q_head_dim, vb.pp("q_proj"), )?), }; let kv_a_proj_with_mqa = candle_nn::linear_b( cfg.hidden_size, cfg.kv_lora_rank + cfg.qk_rope_head_dim, cfg.attention_bias, vb.pp("kv_a_proj_with_mqa"), )?; let kv_a_layernorm = rms_norm(cfg.kv_lora_rank, cfg.rms_norm_eps, vb.pp("kv_a_layernorm"))?; let kv_b_proj = candle_nn::linear_no_bias( cfg.kv_lora_rank, cfg.num_attention_heads * (q_head_dim - cfg.qk_rope_head_dim + cfg.v_head_dim), vb.pp("kv_b_proj"), )?; let o_proj = candle_nn::linear_b( cfg.num_attention_heads * cfg.v_head_dim, cfg.hidden_size, cfg.attention_bias, vb.pp("o_proj"), )?; Ok(Self { q, kv_a_proj_with_mqa, kv_a_layernorm, kv_b_proj, o_proj, rotary_emb, cfg: cfg.clone(), q_head_dim, softmax_scale: cfg.softmax_scale() as f64, kv_cache: None, }) } fn forward( &mut self, xs: &Tensor, attention_mask: Option<&Tensor>, seqlen_offset: usize, ) -> Result<Tensor> { let (bs, seq_len, _) = xs.dims3()?; let q = { let q = self.q.forward(xs)?; q.reshape((bs, seq_len, self.cfg.num_attention_heads, self.q_head_dim))? .transpose(1, 2)? }; let q_split = q.split( &[self.cfg.qk_nope_head_dim, self.cfg.qk_rope_head_dim], D::Minus1, )?; let q_nope = q_split[0].clone(); let q_pe = q_split[1].clone(); let compressed_kv = self.kv_a_proj_with_mqa.forward(xs)?; let ckv_split = compressed_kv.split( &[self.cfg.kv_lora_rank, self.cfg.qk_rope_head_dim], D::Minus1, )?; let compressed_kv = ckv_split[0].clone(); let k_pe = { let k_pe = ckv_split[1].clone(); k_pe.reshape((bs, seq_len, 1, self.cfg.qk_rope_head_dim))? .transpose(1, 2)? }; let kv = { let kv = self .kv_b_proj .forward(&self.kv_a_layernorm.forward(&compressed_kv)?)?; kv.reshape(( bs, seq_len, self.cfg.num_attention_heads, self.cfg.qk_nope_head_dim + self.cfg.v_head_dim, ))? .transpose(1, 2)? }; let kv_split = kv.split(&[self.cfg.qk_nope_head_dim, self.cfg.v_head_dim], D::Minus1)?; let k_nope = kv_split[0].clone(); let v = kv_split[1].clone(); let (q_pe, k_pe) = self.rotary_emb.forward(&q_pe, &k_pe, seqlen_offset)?; let q = Tensor::cat(&[q_nope, q_pe], D::Minus1)?; let k = Tensor::cat(&[k_nope, k_pe.repeat((1, q.dim(1)?, 1, 1))?], D::Minus1)?; let (k, v) = match &self.kv_cache { None => (k, v), Some((prev_k, prev_v)) => { let key_states = Tensor::cat(&[prev_k, &k], 2)?; let value_states = Tensor::cat(&[prev_v, &v], 2)?; (key_states, value_states) } }; self.kv_cache = Some((k.clone(), v.clone())); let attn_out = { let att = (q.contiguous()?.matmul(&k.t()?.contiguous()?)? * self.softmax_scale)?; let att = match attention_mask { Some(mask) => att.broadcast_add(mask)?, None => att, }; let att = candle_nn::ops::softmax_last_dim(&att)?; // Convert to contiguous as matmul doesn't support strided vs for now. att.matmul(&v.contiguous()?)? }; let attn_out = if attention_mask.is_some() { attn_out.transpose(1, 2)?.reshape((bs, seq_len, ()))? } else { attn_out.reshape((bs, seq_len, ()))? }; self.o_proj.forward(&attn_out) } fn clear_kv_cache(&mut self) { self.kv_cache = None } } struct Mlp { gate: Linear, up: Linear, down: Linear, act: Activation, } impl Mlp { fn new( cfg: &DeepSeekV2Config, vb: VarBuilder, hidden_size: Option<usize>, intermediate_size: Option<usize>, ) -> Result<Self> { let hidden_size = hidden_size.unwrap_or(cfg.hidden_size); let intermediate_size = intermediate_size.unwrap_or(cfg.intermediate_size); Ok(Self { gate: candle_nn::linear_no_bias(hidden_size, intermediate_size, vb.pp("gate_proj"))?, up: candle_nn::linear_no_bias(hidden_size, intermediate_size, vb.pp("up_proj"))?, down: candle_nn::linear_no_bias(intermediate_size, hidden_size, vb.pp("down_proj"))?, act: cfg.hidden_act, }) } fn forward(&self, xs: &Tensor) -> Result<Tensor> { let lhs = self.gate.forward(xs)?.apply(&self.act)?; let rhs = self.up.forward(xs)?; self.down.forward(&(&lhs * &rhs)?) } } struct MoeGate { weight: Tensor, cfg: DeepSeekV2Config, top_k: usize, n_routed_experts: usize, } impl MoeGate { fn new(cfg: &DeepSeekV2Config, vb: VarBuilder, n_routed_experts: usize) -> Result<Self> { let weight = vb.get((n_routed_experts, cfg.hidden_size), "weight")?; Ok(Self { weight, cfg: cfg.clone(), top_k: cfg.num_experts_per_tok.unwrap(), n_routed_experts, }) } /// (topk_idx, topk_weight) fn forward(&self, xs: &Tensor) -> Result<(Tensor, Tensor)> { let (bs, seq_len, h) = xs.dims3()?; // Compute gating score let xs = xs.reshape(((), h))?; let logits = xs .to_dtype(DType::F32)? .broadcast_matmul(&self.weight.t()?.to_dtype(DType::F32)?)?; let scores = match self.cfg.scoring_func { ScoringFunc::Softmax => candle_nn::ops::softmax_last_dim(&logits)?, }; // Select top-k experts let (mut topk_weight, topk_idx) = match self.cfg.topk_method { TopkMethod::Greedy => { let TopKOutput { values, indices } = scores.topk_unsorted(self.top_k)?; (values, indices) } TopkMethod::GroupLimitedGreedy => { // (n, n_group) let group_scores = scores .reshape((bs * seq_len, self.cfg.n_group, ()))? .max(D::Minus1)?; // (n, topk_group) let group_idx = scores.topk_unsorted(self.cfg.topk_group)?.indices; // (n, n_group) let group_mask = group_scores.zeros_like()?.scatter_add( &group_idx, &group_idx.ones_like()?.to_dtype(group_scores.dtype())?, 1, )?; // (n, e) let score_mask = group_mask .unsqueeze(D::Minus1)? .expand(( bs * seq_len, self.cfg.n_group, self.n_routed_experts / self.cfg.n_group, ))? .reshape((bs, seq_len, ()))?; // (n, e) // Invert the mask let tmp_scores = masked_fill(&score_mask, &(1. - &score_mask.ne(0.)?)?, 0.)?; let TopKOutput { values, indices } = tmp_scores.topk_unsorted(self.top_k)?; (values, indices) } }; if self.top_k > 1 && self.cfg.norm_topk_prob { let denominator = (topk_weight.sum_keepdim(D::Minus1)? + 1e-20)?; topk_weight = (topk_weight / denominator)?; } else { topk_weight = (topk_weight * self.cfg.routed_scaling_factor)?; } Ok((topk_idx, topk_weight)) } } struct Moe { experts: Vec<Mlp>, shared_experts: Option<Mlp>, gate: MoeGate, } impl Moe { fn new( cfg: &DeepSeekV2Config, vb: VarBuilder, n_shared_experts: Option<usize>, n_routed_experts: usize, ) -> Result<Self> { let mut experts = Vec::with_capacity(n_routed_experts); for i in 0..n_routed_experts { let vb_e = vb.pp("experts").pp(i); experts.push(Mlp::new(cfg, vb_e, None, Some(cfg.moe_intermediate_size))?); } let shared_experts = if let Some(n_shared_experts) = n_shared_experts { let intermediate_size = cfg.moe_intermediate_size * n_shared_experts; Some(Mlp::new( cfg, vb.pp("shared_experts"), None, Some(intermediate_size), )?) } else { None }; let gate = MoeGate::new(cfg, vb.pp("gate"), n_routed_experts)?; Ok(Self { experts, shared_experts, gate, }) } fn moe_infer(&self, xs: &Tensor, topk_ids: &Tensor, topk_weight: &Tensor) -> Result<Tensor> { let mut y = xs.zeros_like()?; let counts = topk_ids .flatten_all()? .bincount(self.experts.len() as u32)?; for (i, expert) in self.experts.iter().enumerate() { if counts[i] == 0 { continue; } let idx_top = topk_ids.eq(i as f64)?.nonzero()?.t()?; let idx = &idx_top.i(0)?.contiguous()?; let top = &idx_top.i(1)?.contiguous()?; y = y.index_add( idx, &expert.forward(&xs.index_select(idx, 0)?)?.broadcast_mul( &topk_weight .index_select(idx, 0)? .gather(&top.unsqueeze(1)?, 1)? .squeeze(1)? .unsqueeze(D::Minus1)? .to_dtype(xs.dtype())?, )?, 0, )?; } Ok(y) } fn forward(&self, xs: &Tensor) -> Result<Tensor> { let identity = xs.clone(); let orig_shape = xs.shape(); let (topk_idx, topk_weight) = self.gate.forward(xs)?; let xs = xs.reshape(((), xs.dim(D::Minus1)?))?; let mut y = self .moe_infer(&xs, &topk_idx, &topk_weight)? .reshape(orig_shape)?; if let Some(ref shared_experts) = self.shared_experts { y = (y + shared_experts.forward(&identity)?)?; } Ok(y) } } enum MoeOrMlp { Moe(Box<Moe>), Mlp(Box<Mlp>), } impl MoeOrMlp { fn forward(&self, xs: &Tensor) -> Result<Tensor> { match self { Self::Mlp(mlp) => mlp.forward(xs), Self::Moe(moe) => moe.forward(xs), } } } struct DecoderLayer { input_layernorm: RmsNorm, post_attention_layernorm: RmsNorm, attn: Attention, moe_or_mlp: MoeOrMlp, } impl DecoderLayer { fn new( rotary_emb: Arc<DeepSeekV2RotaryEmbedding>, cfg: &DeepSeekV2Config, vb: VarBuilder, layer_idx: usize, ) -> Result<Self> { let attn = Attention::new(rotary_emb, cfg, vb.pp("self_attn"))?; let input_layernorm = rms_norm(cfg.hidden_size, cfg.rms_norm_eps, vb.pp("input_layernorm"))?; let post_attention_layernorm = rms_norm( cfg.hidden_size, cfg.rms_norm_eps, vb.pp("post_attention_layernorm"), )?; let moe_or_mlp = if cfg.n_routed_experts.is_some() && layer_idx >= cfg.first_k_dense_replace && layer_idx % cfg.moe_layer_freq == 0 { MoeOrMlp::Moe( Moe::new( cfg, vb.pp("mlp"), cfg.n_shared_experts, cfg.n_routed_experts.unwrap(), )? .into(), ) } else { MoeOrMlp::Mlp(Mlp::new(cfg, vb.pp("mlp"), None, None)?.into()) }; Ok(Self { input_layernorm, post_attention_layernorm, attn, moe_or_mlp, }) } fn forward( &mut self, xs: &Tensor, attention_mask: Option<&Tensor>, seqlen_offset: usize, ) -> Result<Tensor> { let residual = xs; let xs = self.input_layernorm.forward(xs)?; let xs = self.attn.forward(&xs, attention_mask, seqlen_offset)?; let xs = (xs + residual)?; let residual = &xs; let xs = self .moe_or_mlp .forward(&xs.apply(&self.post_attention_layernorm)?)?; residual + xs } fn clear_kv_cache(&mut self) { self.attn.clear_kv_cache(); } } pub struct DeepSeekV2 { lm_head: Linear, embed_tokens: Embedding, norm: RmsNorm, layers: Vec<DecoderLayer>, dtype: DType, device: Device, } impl DeepSeekV2 { pub fn new(cfg: &DeepSeekV2Config, vb: VarBuilder) -> Result<Self> { let vb_m = vb.pp("model"); let embed_tokens = embedding(cfg.vocab_size, cfg.hidden_size, vb_m.pp("embed_tokens"))?; let lm_head = if !cfg.tie_word_embeddings { candle_nn::linear_no_bias(cfg.hidden_size, cfg.vocab_size, vb.pp("lm_head"))? } else { candle_nn::Linear::new(embed_tokens.embeddings().clone(), None) }; let norm = rms_norm(cfg.hidden_size, cfg.rms_norm_eps, vb_m.pp("norm"))?; let rope_cfg = DeepSeekV2RopeConfig { rope_scaling: cfg.rope_scaling.clone(), max_position_embeddings: cfg.max_position_embeddings, rope_theta: cfg.rope_theta, qk_rope_head_dim: cfg.qk_rope_head_dim, }; let rotary_emb = Arc::new(DeepSeekV2RotaryEmbedding::new( &rope_cfg, vb.dtype(), vb.device(), )?); let mut layers = Vec::with_capacity(cfg.num_hidden_layers); let vb_l = vb_m.pp("layers"); for layer_idx in 0..cfg.num_hidden_layers { let layer = DecoderLayer::new(rotary_emb.clone(), cfg, vb_l.pp(layer_idx), layer_idx)?; layers.push(layer) } Ok(Self { lm_head, embed_tokens, norm, layers, dtype: vb.dtype(), device: vb.device().clone(), }) } fn prepare_decoder_attention_mask( &self, b_size: usize, tgt_len: usize, seqlen_offset: usize, ) -> Result<Tensor> { let mask: Vec<_> = (0..tgt_len) .flat_map(|i| (0..tgt_len).map(move |j| if i < j { f32::NEG_INFINITY } else { 0. })) .collect(); let mask = Tensor::from_slice(&mask, (tgt_len, tgt_len), &self.device)?; let mask = if seqlen_offset > 0 { let mask0 = Tensor::zeros((tgt_len, seqlen_offset), DType::F32, &self.device)?; Tensor::cat(&[&mask0, &mask], D::Minus1)? } else { mask }; mask.expand((b_size, 1, tgt_len, tgt_len + seqlen_offset))? .to_dtype(self.dtype) } pub fn forward(&mut self, input_ids: &Tensor, seqlen_offset: usize) -> Result<Tensor> { let (bs, seq_len) = input_ids.dims2()?; let mut xs = self.embed_tokens.forward(input_ids)?; let attention_mask = if seq_len == 1 { None } else { let mask = self.prepare_decoder_attention_mask(bs, seq_len, seqlen_offset)?; Some(mask) }; for layer in &mut self.layers { xs = layer.forward( &xs, attention_mask .as_ref() .map(|m| m.to_device(xs.device()).unwrap()) .as_ref(), seqlen_offset, )?; } let xs = xs.apply(&self.norm)?; let xs = xs.i((.., seq_len - 1, ..))?.contiguous()?; let logits = self.lm_head.forward(&xs)?; logits.to_dtype(DType::F32) } pub fn clear_kv_cache(&mut self) { for layer in self.layers.iter_mut() { layer.clear_kv_cache(); } } }
candle/candle-transformers/src/models/deepseek2.rs/0
{ "file_path": "candle/candle-transformers/src/models/deepseek2.rs", "repo_id": "candle", "token_count": 18564 }
59
//! Gemma inference implementation. //! //! See ["Gemma: Open Models Based on Gemini Technology"](https://blog.google/technology/developers/gemma-open-ai-model/) //! //! Based on implementation from Google and PyTorch use std::sync::Arc; use candle::{DType, Device, Module, Result, Tensor, D}; use candle_nn::{linear_b as linear, Activation, Linear, VarBuilder}; fn default_max_position_embeddings() -> usize { 4096 } #[derive(serde::Deserialize, Debug, Clone)] pub struct Config { pub attention_bias: bool, pub head_dim: usize, // The code gemma configs include both hidden_act and hidden_activation. pub hidden_act: Option<Activation>, pub hidden_activation: Option<Activation>, pub hidden_size: usize, pub intermediate_size: usize, pub num_attention_heads: usize, pub num_hidden_layers: usize, pub num_key_value_heads: usize, pub rms_norm_eps: f64, pub rope_theta: f64, pub vocab_size: usize, #[serde(default = "default_max_position_embeddings")] pub max_position_embeddings: usize, } impl Config { fn hidden_act(&self) -> Result<Activation> { match (self.hidden_act, self.hidden_activation) { (None, Some(act)) | (Some(act), None) => Ok(act), (Some(_), Some(_)) => candle::bail!("both hidden_act and hidden_activation are set"), (None, None) => candle::bail!("none of hidden_act and hidden_activation are set"), } } } #[derive(Debug, Clone)] struct RmsNorm { weight: Tensor, eps: f64, } impl RmsNorm { fn new(dim: usize, eps: f64, vb: VarBuilder) -> Result<Self> { let weight = vb.get(dim, "weight")?; Ok(Self { weight, eps }) } } impl Module for RmsNorm { fn forward(&self, x: &Tensor) -> Result<Tensor> { let x_dtype = x.dtype(); let internal_dtype = match x_dtype { DType::F16 | DType::BF16 => DType::F32, d => d, }; let hidden_size = x.dim(D::Minus1)?; let x = x.to_dtype(internal_dtype)?; let norm_x = (x.sqr()?.sum_keepdim(D::Minus1)? / hidden_size as f64)?; let x_normed = x.broadcast_div(&(norm_x + self.eps)?.sqrt()?)?; x_normed .to_dtype(x_dtype)? .broadcast_mul(&(&self.weight + 1.0)?) } } #[derive(Debug, Clone)] struct RotaryEmbedding { sin: Tensor, cos: Tensor, } impl RotaryEmbedding { fn new(dtype: DType, cfg: &Config, dev: &Device) -> Result<Self> { let dim = cfg.head_dim; let max_seq_len = cfg.max_position_embeddings; let inv_freq: Vec<_> = (0..dim) .step_by(2) .map(|i| 1f32 / cfg.rope_theta.powf(i as f64 / dim as f64) as f32) .collect(); let inv_freq_len = inv_freq.len(); let inv_freq = Tensor::from_vec(inv_freq, (1, inv_freq_len), dev)?.to_dtype(dtype)?; let t = Tensor::arange(0u32, max_seq_len as u32, dev)? .to_dtype(dtype)? .reshape((max_seq_len, 1))?; let freqs = t.matmul(&inv_freq)?; Ok(Self { sin: freqs.sin()?, cos: freqs.cos()?, }) } fn apply_rotary_emb_qkv( &self, q: &Tensor, k: &Tensor, seqlen_offset: usize, ) -> Result<(Tensor, Tensor)> { let (_b_sz, _h, seq_len, _n_embd) = q.dims4()?; let cos = self.cos.narrow(0, seqlen_offset, seq_len)?; let sin = self.sin.narrow(0, seqlen_offset, seq_len)?; let q_embed = candle_nn::rotary_emb::rope(&q.contiguous()?, &cos, &sin)?; let k_embed = candle_nn::rotary_emb::rope(&k.contiguous()?, &cos, &sin)?; Ok((q_embed, k_embed)) } } #[derive(Debug, Clone)] #[allow(clippy::upper_case_acronyms)] struct MLP { gate_proj: Linear, up_proj: Linear, down_proj: Linear, act_fn: candle_nn::Activation, } impl MLP { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let hidden_sz = cfg.hidden_size; let intermediate_sz = cfg.intermediate_size; let gate_proj = linear(hidden_sz, intermediate_sz, false, vb.pp("gate_proj"))?; let up_proj = linear(hidden_sz, intermediate_sz, false, vb.pp("up_proj"))?; let down_proj = linear(intermediate_sz, hidden_sz, false, vb.pp("down_proj"))?; Ok(Self { gate_proj, up_proj, down_proj, act_fn: cfg.hidden_act()?, }) } } impl Module for MLP { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let lhs = xs.apply(&self.gate_proj)?.apply(&self.act_fn)?; let rhs = xs.apply(&self.up_proj)?; (lhs * rhs)?.apply(&self.down_proj) } } #[derive(Debug, Clone)] struct Attention { q_proj: Linear, k_proj: Linear, v_proj: Linear, o_proj: Linear, num_heads: usize, num_kv_heads: usize, num_kv_groups: usize, head_dim: usize, rotary_emb: Arc<RotaryEmbedding>, kv_cache: Option<(Tensor, Tensor)>, use_flash_attn: bool, } impl Attention { fn new( rotary_emb: Arc<RotaryEmbedding>, use_flash_attn: bool, cfg: &Config, vb: VarBuilder, ) -> Result<Self> { let hidden_sz = cfg.hidden_size; let num_heads = cfg.num_attention_heads; let num_kv_heads = cfg.num_key_value_heads; let num_kv_groups = num_heads / num_kv_heads; let head_dim = cfg.head_dim; let bias = cfg.attention_bias; let q_proj = linear(hidden_sz, num_heads * head_dim, bias, vb.pp("q_proj"))?; let k_proj = linear(hidden_sz, num_kv_heads * head_dim, bias, vb.pp("k_proj"))?; let v_proj = linear(hidden_sz, num_kv_heads * head_dim, bias, vb.pp("v_proj"))?; let o_proj = linear(num_heads * head_dim, hidden_sz, bias, vb.pp("o_proj"))?; Ok(Self { q_proj, k_proj, v_proj, o_proj, num_heads, num_kv_heads, num_kv_groups, head_dim, rotary_emb, kv_cache: None, use_flash_attn, }) } fn forward( &mut self, xs: &Tensor, attention_mask: Option<&Tensor>, seqlen_offset: usize, ) -> Result<Tensor> { let (b_sz, q_len, _) = xs.dims3()?; let query_states = self.q_proj.forward(xs)?; let key_states = self.k_proj.forward(xs)?; let value_states = self.v_proj.forward(xs)?; let query_states = query_states .reshape((b_sz, q_len, self.num_heads, self.head_dim))? .transpose(1, 2)?; let key_states = key_states .reshape((b_sz, q_len, self.num_kv_heads, self.head_dim))? .transpose(1, 2)?; let value_states = value_states .reshape((b_sz, q_len, self.num_kv_heads, self.head_dim))? .transpose(1, 2)?; let (query_states, key_states) = self.rotary_emb .apply_rotary_emb_qkv(&query_states, &key_states, seqlen_offset)?; let (key_states, value_states) = match &self.kv_cache { None => (key_states, value_states), Some((prev_k, prev_v)) => { let key_states = Tensor::cat(&[prev_k, &key_states], 2)?; let value_states = Tensor::cat(&[prev_v, &value_states], 2)?; (key_states, value_states) } }; self.kv_cache = Some((key_states.clone(), value_states.clone())); let key_states = crate::utils::repeat_kv(key_states, self.num_kv_groups)?.contiguous()?; let value_states = crate::utils::repeat_kv(value_states, self.num_kv_groups)?.contiguous()?; let attn_output = if self.use_flash_attn { // flash-attn expects (b_sz, seq_len, nheads, head_dim) let q = query_states.transpose(1, 2)?; let k = key_states.transpose(1, 2)?; let v = value_states.transpose(1, 2)?; let scale = 1f32 / (self.head_dim as f32).sqrt(); flash_attn(&q, &k, &v, scale, attention_mask.is_some())?.transpose(1, 2)? } else { let scale = 1f64 / f64::sqrt(self.head_dim as f64); let attn_weights = (query_states.matmul(&key_states.transpose(2, 3)?)? * scale)?; let attn_weights = match attention_mask { None => attn_weights, Some(mask) => attn_weights.broadcast_add(mask)?, }; let attn_weights = candle_nn::ops::softmax_last_dim(&attn_weights)?; attn_weights.matmul(&value_states)? }; attn_output .transpose(1, 2)? .reshape((b_sz, q_len, ()))? .apply(&self.o_proj) } fn clear_kv_cache(&mut self) { self.kv_cache = None } } #[cfg(feature = "flash-attn")] fn flash_attn( q: &Tensor, k: &Tensor, v: &Tensor, softmax_scale: f32, causal: bool, ) -> Result<Tensor> { candle_flash_attn::flash_attn(q, k, v, softmax_scale, causal) } #[cfg(not(feature = "flash-attn"))] fn flash_attn(_: &Tensor, _: &Tensor, _: &Tensor, _: f32, _: bool) -> Result<Tensor> { unimplemented!("compile with '--features flash-attn'") } #[derive(Debug, Clone)] struct DecoderLayer { self_attn: Attention, mlp: MLP, input_layernorm: RmsNorm, post_attention_layernorm: RmsNorm, } impl DecoderLayer { fn new( rotary_emb: Arc<RotaryEmbedding>, use_flash_attn: bool, cfg: &Config, vb: VarBuilder, ) -> Result<Self> { let self_attn = Attention::new(rotary_emb, use_flash_attn, cfg, vb.pp("self_attn"))?; let mlp = MLP::new(cfg, vb.pp("mlp"))?; let input_layernorm = RmsNorm::new(cfg.hidden_size, cfg.rms_norm_eps, vb.pp("input_layernorm"))?; let post_attention_layernorm = RmsNorm::new( cfg.hidden_size, cfg.rms_norm_eps, vb.pp("post_attention_layernorm"), )?; Ok(Self { self_attn, mlp, input_layernorm, post_attention_layernorm, }) } fn forward( &mut self, xs: &Tensor, attention_mask: Option<&Tensor>, seqlen_offset: usize, ) -> Result<Tensor> { let residual = xs; let xs = self.input_layernorm.forward(xs)?; let xs = self.self_attn.forward(&xs, attention_mask, seqlen_offset)?; let xs = (xs + residual)?; let residual = &xs; let xs = xs.apply(&self.post_attention_layernorm)?.apply(&self.mlp)?; residual + xs } fn clear_kv_cache(&mut self) { self.self_attn.clear_kv_cache() } } #[derive(Debug, Clone)] pub struct Model { embed_tokens: candle_nn::Embedding, layers: Vec<DecoderLayer>, norm: RmsNorm, lm_head: Linear, device: Device, dtype: DType, hidden_size: usize, } impl Model { pub fn new(use_flash_attn: bool, cfg: &Config, vb: VarBuilder) -> Result<Self> { let vb_m = vb.pp("model"); let embed_tokens = candle_nn::embedding(cfg.vocab_size, cfg.hidden_size, vb_m.pp("embed_tokens"))?; let rotary_emb = Arc::new(RotaryEmbedding::new(vb.dtype(), cfg, vb_m.device())?); let mut layers = Vec::with_capacity(cfg.num_hidden_layers); let vb_l = vb_m.pp("layers"); for layer_idx in 0..cfg.num_hidden_layers { let layer = DecoderLayer::new(rotary_emb.clone(), use_flash_attn, cfg, vb_l.pp(layer_idx))?; layers.push(layer) } let norm = RmsNorm::new(cfg.hidden_size, cfg.rms_norm_eps, vb_m.pp("norm"))?; let lm_head = Linear::new(embed_tokens.embeddings().clone(), None); Ok(Self { embed_tokens, layers, norm, lm_head, device: vb.device().clone(), dtype: vb.dtype(), hidden_size: cfg.hidden_size, }) } pub fn embed_tokens(&self) -> &candle_nn::Embedding { &self.embed_tokens } fn prepare_decoder_attention_mask( &self, b_size: usize, tgt_len: usize, seqlen_offset: usize, ) -> Result<Tensor> { let mask: Vec<_> = (0..tgt_len) .flat_map(|i| (0..tgt_len).map(move |j| if i < j { f32::NEG_INFINITY } else { 0. })) .collect(); let mask = Tensor::from_slice(&mask, (tgt_len, tgt_len), &self.device)?; let mask = if seqlen_offset > 0 { let mask0 = Tensor::zeros((tgt_len, seqlen_offset), DType::F32, &self.device)?; Tensor::cat(&[&mask0, &mask], D::Minus1)? } else { mask }; mask.expand((b_size, 1, tgt_len, tgt_len + seqlen_offset))? .to_dtype(self.dtype) } pub fn forward(&mut self, input_ids: &Tensor, seqlen_offset: usize) -> Result<Tensor> { let (b_size, seq_len) = input_ids.dims2()?; let attention_mask = if seq_len <= 1 { None } else { let mask = self.prepare_decoder_attention_mask(b_size, seq_len, seqlen_offset)?; Some(mask) }; let xs = self.embed_tokens.forward(input_ids)?; let mut xs = (xs * (self.hidden_size as f64).sqrt())?; for layer in self.layers.iter_mut() { xs = layer.forward(&xs, attention_mask.as_ref(), seqlen_offset)? } xs.narrow(1, seq_len - 1, 1)? .apply(&self.norm)? .apply(&self.lm_head) } pub fn forward_embeds( &mut self, xs: &Tensor, attn_mask: Option<&Tensor>, seqlen_offset: usize, ) -> Result<Tensor> { let (_, seq_len, _) = xs.dims3()?; let mut xs = (xs * (self.hidden_size as f64).sqrt())?; for layer in self.layers.iter_mut() { xs = layer.forward(&xs, attn_mask, seqlen_offset)? } xs.narrow(1, seq_len - 1, 1)? .apply(&self.norm)? .apply(&self.lm_head) } // Forward the model and return the hidden states without the lm_head pub fn forward_embeds_without_projection( &mut self, xs: &Tensor, attn_mask: Option<&Tensor>, seqlen_offset: usize, ) -> Result<Tensor> { let (_, _, _) = xs.dims3()?; let mut xs = (xs * (self.hidden_size as f64).sqrt())?; for layer in self.layers.iter_mut() { xs = layer.forward(&xs, attn_mask, seqlen_offset)? } Ok(xs) } pub fn clear_kv_cache(&mut self) { for layer in self.layers.iter_mut() { layer.clear_kv_cache() } } }
candle/candle-transformers/src/models/gemma.rs/0
{ "file_path": "candle/candle-transformers/src/models/gemma.rs", "repo_id": "candle", "token_count": 7496 }
60
//! Marian Neural Machine Translation //! //! See "Marian: Fast Neural Machine Translation in C++" Junczys-Dowmunt et al. 2018 //! - [ACL Anthology](https://aclanthology.org/P18-4020/) //! - [Github](https://github.com/marian-nmt/marian) //! use super::with_tracing::{linear, Embedding, Linear}; use candle::{Result, Tensor}; use candle_nn::{layer_norm, LayerNorm, VarBuilder}; #[derive(Debug, Clone, serde::Deserialize)] pub struct Config { pub vocab_size: usize, pub decoder_vocab_size: Option<usize>, pub max_position_embeddings: usize, pub encoder_layers: usize, pub encoder_ffn_dim: usize, pub encoder_attention_heads: usize, pub decoder_layers: usize, pub decoder_ffn_dim: usize, pub decoder_attention_heads: usize, pub use_cache: bool, pub is_encoder_decoder: bool, pub activation_function: candle_nn::Activation, pub d_model: usize, pub decoder_start_token_id: u32, pub scale_embedding: bool, pub pad_token_id: u32, pub eos_token_id: u32, pub forced_eos_token_id: u32, pub share_encoder_decoder_embeddings: bool, } impl Config { // https://huggingface.co/Helsinki-NLP/opus-mt-tc-big-fr-en/blob/main/config.json pub fn opus_mt_tc_big_fr_en() -> Self { Self { activation_function: candle_nn::Activation::Relu, d_model: 1024, decoder_attention_heads: 16, decoder_ffn_dim: 4096, decoder_layers: 6, decoder_start_token_id: 53016, decoder_vocab_size: Some(53017), encoder_attention_heads: 16, encoder_ffn_dim: 4096, encoder_layers: 6, eos_token_id: 43311, forced_eos_token_id: 43311, is_encoder_decoder: true, max_position_embeddings: 1024, pad_token_id: 53016, scale_embedding: true, share_encoder_decoder_embeddings: true, use_cache: true, vocab_size: 53017, } } // https://huggingface.co/Helsinki-NLP/opus-mt-fr-en/blob/main/config.json pub fn opus_mt_fr_en() -> Self { Self { activation_function: candle_nn::Activation::Swish, d_model: 512, decoder_attention_heads: 8, decoder_ffn_dim: 2048, decoder_layers: 6, decoder_start_token_id: 59513, decoder_vocab_size: Some(59514), encoder_attention_heads: 8, encoder_ffn_dim: 2048, encoder_layers: 6, eos_token_id: 0, forced_eos_token_id: 0, is_encoder_decoder: true, max_position_embeddings: 512, pad_token_id: 59513, scale_embedding: true, share_encoder_decoder_embeddings: true, use_cache: true, vocab_size: 59514, } } pub fn opus_mt_en_zh() -> Self { Self { activation_function: candle_nn::Activation::Swish, d_model: 512, decoder_attention_heads: 8, decoder_ffn_dim: 2048, decoder_layers: 6, decoder_start_token_id: 65000, decoder_vocab_size: Some(65001), encoder_attention_heads: 8, encoder_ffn_dim: 2048, encoder_layers: 6, eos_token_id: 0, forced_eos_token_id: 0, is_encoder_decoder: true, max_position_embeddings: 512, pad_token_id: 65000, scale_embedding: true, share_encoder_decoder_embeddings: true, use_cache: true, vocab_size: 65001, } } pub fn opus_mt_en_hi() -> Self { Self { activation_function: candle_nn::Activation::Swish, d_model: 512, decoder_attention_heads: 8, decoder_ffn_dim: 2048, decoder_layers: 6, decoder_start_token_id: 61949, decoder_vocab_size: Some(61950), encoder_attention_heads: 8, encoder_ffn_dim: 2048, encoder_layers: 6, eos_token_id: 0, forced_eos_token_id: 0, is_encoder_decoder: true, max_position_embeddings: 512, pad_token_id: 61949, scale_embedding: true, share_encoder_decoder_embeddings: true, use_cache: true, vocab_size: 61950, } } pub fn opus_mt_en_es() -> Self { Self { activation_function: candle_nn::Activation::Swish, d_model: 512, decoder_attention_heads: 8, decoder_ffn_dim: 2048, decoder_layers: 6, decoder_start_token_id: 65000, decoder_vocab_size: Some(65001), encoder_attention_heads: 8, encoder_ffn_dim: 2048, encoder_layers: 6, eos_token_id: 0, forced_eos_token_id: 0, is_encoder_decoder: true, max_position_embeddings: 512, pad_token_id: 65000, scale_embedding: true, share_encoder_decoder_embeddings: true, use_cache: true, vocab_size: 65001, } } pub fn opus_mt_en_fr() -> Self { Self { activation_function: candle_nn::Activation::Swish, d_model: 512, decoder_attention_heads: 8, decoder_ffn_dim: 2048, decoder_layers: 6, decoder_start_token_id: 59513, decoder_vocab_size: Some(59514), encoder_attention_heads: 8, encoder_ffn_dim: 2048, encoder_layers: 6, eos_token_id: 0, forced_eos_token_id: 0, is_encoder_decoder: true, max_position_embeddings: 512, pad_token_id: 59513, scale_embedding: true, share_encoder_decoder_embeddings: true, use_cache: true, vocab_size: 59514, } } pub fn opus_mt_en_ru() -> Self { Self { activation_function: candle_nn::Activation::Swish, d_model: 512, decoder_attention_heads: 8, decoder_ffn_dim: 2048, decoder_layers: 6, decoder_start_token_id: 62517, decoder_vocab_size: Some(62518), encoder_attention_heads: 8, encoder_ffn_dim: 2048, encoder_layers: 6, eos_token_id: 0, forced_eos_token_id: 0, is_encoder_decoder: true, max_position_embeddings: 512, pad_token_id: 62517, scale_embedding: true, share_encoder_decoder_embeddings: true, use_cache: true, vocab_size: 62518, } } } #[derive(Debug, Clone)] struct SinusoidalPositionalEmbedding { emb: Embedding, } impl SinusoidalPositionalEmbedding { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let dev = vb.device(); let dtype = vb.dtype(); let num_positions = cfg.max_position_embeddings; let dim = cfg.d_model; let inv_freq: Vec<_> = (0..dim) .step_by(2) .map(|i| 1f32 / 10000f32.powf(i as f32 / dim as f32)) .collect(); let inv_freq_len = inv_freq.len(); let inv_freq = Tensor::from_vec(inv_freq, (1, inv_freq_len), dev)?.to_dtype(dtype)?; let t = Tensor::arange(0u32, num_positions as u32, dev)? .to_dtype(dtype)? .reshape((num_positions, 1))?; let freqs = t.matmul(&inv_freq)?; let sin = freqs.sin()?; let cos = freqs.cos()?; let weights = Tensor::cat(&[&sin, &cos], 1)?.contiguous()?; let emb = Embedding::from_weights(weights)?; Ok(Self { emb }) } fn forward(&self, input_ids: &Tensor, past_kv_len: usize) -> Result<Tensor> { let seq_len = input_ids.dim(1)?; Tensor::arange( past_kv_len as u32, (past_kv_len + seq_len) as u32, input_ids.device(), )? .apply(&self.emb) } } #[derive(Debug, Clone)] struct Attention { q_proj: Linear, k_proj: Linear, v_proj: Linear, out_proj: Linear, scaling: f64, num_heads: usize, head_dim: usize, kv_cache: Option<(Tensor, Tensor)>, is_decoder: bool, } impl Attention { fn new(cfg: &Config, is_decoder: bool, vb: VarBuilder) -> Result<Self> { let num_heads = if is_decoder { cfg.decoder_attention_heads } else { cfg.encoder_attention_heads }; let embed_dim = cfg.d_model; let head_dim = embed_dim / num_heads; let scaling = (head_dim as f64).powf(-0.5); let q_proj = linear(embed_dim, embed_dim, vb.pp("q_proj"))?; let k_proj = linear(embed_dim, embed_dim, vb.pp("k_proj"))?; let v_proj = linear(embed_dim, embed_dim, vb.pp("v_proj"))?; let out_proj = linear(embed_dim, embed_dim, vb.pp("out_proj"))?; Ok(Self { q_proj, k_proj, v_proj, out_proj, scaling, num_heads, head_dim, kv_cache: None, is_decoder, }) } fn _shape(&self, tensor: &Tensor, bsz: usize) -> Result<Tensor> { tensor .reshape((bsz, (), self.num_heads, self.head_dim))? .transpose(1, 2)? .contiguous() } fn forward( &mut self, xs: &Tensor, kv_states: Option<&Tensor>, attn_mask: Option<&Tensor>, ) -> Result<Tensor> { let (b_sz, tgt_len, _) = xs.dims3()?; let query_states = (xs.apply(&self.q_proj)? * self.scaling)?; let (key_states, value_states) = match kv_states { None => { let key_states = self._shape(&xs.apply(&self.k_proj)?, b_sz)?; let value_states = self._shape(&xs.apply(&self.v_proj)?, b_sz)?; if self.is_decoder { let kv_states = match &self.kv_cache { None => (key_states, value_states), Some((p_key_states, p_value_states)) => { let key_states = Tensor::cat(&[p_key_states, &key_states], 2)?; let value_states = Tensor::cat(&[p_value_states, &value_states], 2)?; (key_states, value_states) } }; self.kv_cache = Some(kv_states.clone()); kv_states } else { (key_states, value_states) } } Some(kv_states) => { let key_states = self._shape(&kv_states.apply(&self.k_proj)?, b_sz)?; let value_states = self._shape(&kv_states.apply(&self.v_proj)?, b_sz)?; (key_states, value_states) } }; let proj_shape = (b_sz * self.num_heads, (), self.head_dim); let query_states = self._shape(&query_states, b_sz)?.reshape(proj_shape)?; let key_states = key_states.reshape(proj_shape)?; let value_states = value_states.reshape(proj_shape)?; let attn_weights = query_states.matmul(&key_states.transpose(1, 2)?)?; let attn_weights = match attn_mask { None => attn_weights, Some(attn_mask) => attn_weights.broadcast_add(attn_mask)?, }; let attn_probs = candle_nn::ops::softmax_last_dim(&attn_weights)?; let attn_output = attn_probs.matmul(&value_states)?; attn_output .reshape((b_sz, self.num_heads, tgt_len, self.head_dim))? .transpose(1, 2)? .reshape((b_sz, tgt_len, self.head_dim * self.num_heads))? .apply(&self.out_proj) } fn reset_kv_cache(&mut self) { self.kv_cache = None } } #[derive(Debug, Clone)] struct EncoderLayer { self_attn: Attention, self_attn_layer_norm: LayerNorm, activation_fn: candle_nn::Activation, fc1: Linear, fc2: Linear, final_layer_norm: LayerNorm, } impl EncoderLayer { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let self_attn = Attention::new(cfg, true, vb.pp("self_attn"))?; let self_attn_layer_norm = layer_norm(cfg.d_model, 1e-5, vb.pp("self_attn_layer_norm"))?; let fc1 = linear(cfg.d_model, cfg.encoder_ffn_dim, vb.pp("fc1"))?; let fc2 = linear(cfg.encoder_ffn_dim, cfg.d_model, vb.pp("fc2"))?; let final_layer_norm = layer_norm(cfg.d_model, 1e-5, vb.pp("final_layer_norm"))?; Ok(Self { self_attn, self_attn_layer_norm, activation_fn: cfg.activation_function, fc1, fc2, final_layer_norm, }) } fn forward(&mut self, xs: &Tensor) -> Result<Tensor> { let residual = xs; let xs = (self.self_attn.forward(xs, None, None)? + residual)? .apply(&self.self_attn_layer_norm)?; let residual = &xs; let xs = xs .apply(&self.fc1)? .apply(&self.activation_fn)? .apply(&self.fc2)?; (xs + residual)?.apply(&self.final_layer_norm) } fn reset_kv_cache(&mut self) { self.self_attn.reset_kv_cache() } } #[derive(Debug, Clone)] struct DecoderLayer { self_attn: Attention, self_attn_layer_norm: LayerNorm, activation_fn: candle_nn::Activation, encoder_attn: Attention, encoder_attn_layer_norm: LayerNorm, fc1: Linear, fc2: Linear, final_layer_norm: LayerNorm, } impl DecoderLayer { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let self_attn = Attention::new(cfg, true, vb.pp("self_attn"))?; let self_attn_layer_norm = layer_norm(cfg.d_model, 1e-5, vb.pp("self_attn_layer_norm"))?; let encoder_attn = Attention::new(cfg, true, vb.pp("encoder_attn"))?; let encoder_attn_layer_norm = layer_norm(cfg.d_model, 1e-5, vb.pp("encoder_attn_layer_norm"))?; let fc1 = linear(cfg.d_model, cfg.decoder_ffn_dim, vb.pp("fc1"))?; let fc2 = linear(cfg.decoder_ffn_dim, cfg.d_model, vb.pp("fc2"))?; let final_layer_norm = layer_norm(cfg.d_model, 1e-5, vb.pp("final_layer_norm"))?; Ok(Self { self_attn, self_attn_layer_norm, activation_fn: cfg.activation_function, encoder_attn, encoder_attn_layer_norm, fc1, fc2, final_layer_norm, }) } fn forward( &mut self, xs: &Tensor, encoder_xs: Option<&Tensor>, attn_mask: &Tensor, ) -> Result<Tensor> { let residual = xs; let xs = (self.self_attn.forward(xs, None, Some(attn_mask))? + residual)? .apply(&self.self_attn_layer_norm)?; let xs = match encoder_xs { None => xs, Some(encoder_xs) => { let residual = &xs; let xs = self.encoder_attn.forward(&xs, Some(encoder_xs), None)?; (residual + xs)?.apply(&self.encoder_attn_layer_norm)? } }; let residual = &xs; let xs = xs .apply(&self.fc1)? .apply(&self.activation_fn)? .apply(&self.fc2)?; let xs = (xs + residual)?.apply(&self.final_layer_norm)?; Ok(xs) } fn reset_kv_cache(&mut self) { self.self_attn.reset_kv_cache(); self.encoder_attn.reset_kv_cache() } } #[derive(Debug, Clone)] pub struct Encoder { embed_tokens: Embedding, embed_positions: SinusoidalPositionalEmbedding, layers: Vec<EncoderLayer>, embed_scale: Option<f64>, } impl Encoder { fn new(cfg: &Config, embed_tokens: &Embedding, vb: VarBuilder) -> Result<Self> { let embed_positions = SinusoidalPositionalEmbedding::new(cfg, vb.pp("embed_positions"))?; let mut layers = Vec::with_capacity(cfg.encoder_layers); let vb_l = vb.pp("layers"); for idx in 0..cfg.encoder_layers { let layer = EncoderLayer::new(cfg, vb_l.pp(idx))?; layers.push(layer) } let embed_scale = if cfg.scale_embedding { Some((cfg.d_model as f64).sqrt()) } else { None }; Ok(Self { embed_tokens: embed_tokens.clone(), embed_positions, layers, embed_scale, }) } pub fn forward(&mut self, xs: &Tensor, past_kv_len: usize) -> Result<Tensor> { let xs = xs.apply(&self.embed_tokens)?; let xs = match self.embed_scale { None => xs, Some(scale) => (xs * scale)?, }; let embed_pos = self .embed_positions .forward(&xs, past_kv_len)? .unsqueeze(0)?; let mut xs = xs.broadcast_add(&embed_pos)?; for layer in self.layers.iter_mut() { xs = layer.forward(&xs)? } Ok(xs) } pub fn reset_kv_cache(&mut self) { for layer in self.layers.iter_mut() { layer.reset_kv_cache() } } } #[derive(Debug, Clone)] pub struct Decoder { embed_tokens: Embedding, embed_positions: SinusoidalPositionalEmbedding, layers: Vec<DecoderLayer>, embed_scale: Option<f64>, } impl Decoder { fn new(cfg: &Config, embed_tokens: &Embedding, vb: VarBuilder) -> Result<Self> { let embed_positions = SinusoidalPositionalEmbedding::new(cfg, vb.pp("embed_positions"))?; let mut layers = Vec::with_capacity(cfg.decoder_layers); let vb_l = vb.pp("layers"); for idx in 0..cfg.decoder_layers { let layer = DecoderLayer::new(cfg, vb_l.pp(idx))?; layers.push(layer) } let embed_scale = if cfg.scale_embedding { Some((cfg.d_model as f64).sqrt()) } else { None }; Ok(Self { embed_tokens: embed_tokens.clone(), embed_positions, layers, embed_scale, }) } pub fn forward( &mut self, xs: &Tensor, encoder_xs: Option<&Tensor>, past_kv_len: usize, attn_mask: &Tensor, ) -> Result<Tensor> { let xs = xs.apply(&self.embed_tokens)?; let xs = match self.embed_scale { None => xs, Some(scale) => (xs * scale)?, }; let embed_pos = self .embed_positions .forward(&xs, past_kv_len)? .unsqueeze(0)?; let mut xs = xs.broadcast_add(&embed_pos)?; for layer in self.layers.iter_mut() { xs = layer.forward(&xs, encoder_xs, attn_mask)?; } Ok(xs) } pub fn reset_kv_cache(&mut self) { for layer in self.layers.iter_mut() { layer.reset_kv_cache() } } } #[derive(Debug, Clone)] struct Model { shared: Embedding, encoder: Encoder, decoder: Decoder, } impl Model { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let shared = Embedding::new(cfg.vocab_size, cfg.d_model, vb.pp("shared"))?; let encoder = Encoder::new(cfg, &shared, vb.pp("encoder"))?; let decoder = Decoder::new(cfg, &shared, vb.pp("decoder"))?; Ok(Self { shared, encoder, decoder, }) } fn reset_kv_cache(&mut self) { self.encoder.reset_kv_cache(); self.decoder.reset_kv_cache(); } } #[derive(Debug, Clone)] pub struct MTModel { model: Model, lm_head: Linear, final_logits_bias: Tensor, } impl MTModel { pub fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let target_vocab_size = cfg.decoder_vocab_size.unwrap_or(cfg.vocab_size); let final_logits_bias = vb.get((1, target_vocab_size), "final_logits_bias")?; let model = Model::new(cfg, vb.pp("model"))?; let lm_head = Linear::from_weights(model.shared.embeddings().clone(), None); Ok(Self { model, lm_head, final_logits_bias, }) } pub fn encoder(&mut self) -> &mut Encoder { &mut self.model.encoder } pub fn decoder(&mut self) -> &mut Decoder { &mut self.model.decoder } pub fn decode( &mut self, xs: &Tensor, encoder_xs: &Tensor, past_kv_len: usize, ) -> Result<Tensor> { let seq_len = xs.dim(1)?; let mask: Vec<_> = (0..seq_len) .flat_map(|i| (0..seq_len).map(move |j| if j > i { f32::NEG_INFINITY } else { 0f32 })) .collect(); let mask = Tensor::from_vec(mask, (seq_len, seq_len), xs.device())?; self.model .decoder .forward(xs, Some(encoder_xs), past_kv_len, &mask)? .apply(&self.lm_head)? .broadcast_add(&self.final_logits_bias) } pub fn reset_kv_cache(&mut self) { self.model.reset_kv_cache(); } }
candle/candle-transformers/src/models/marian.rs/0
{ "file_path": "candle/candle-transformers/src/models/marian.rs", "repo_id": "candle", "token_count": 11295 }
61
//! Mobile CLIP model, combining a lightweight vision encoder with a text encoder //! //! A mobile-optimized CLIP implementation that uses: //! - FastViT as the vision encoder //! - OpenCLIP text encoder //! - Projection layers to align the feature spaces //! //! See model details at: //! - [FastViT](https://arxiv.org/abs/2303.14189) //! - [OpenCLIP](https://github.com/mlfoundations/open_clip) //! //! References: //! - [MobileVLM](https://huggingface.co/mobileVLM) //! - [MetaCLIP](https://arxiv.org/abs/2309.16671) //! use super::fastvit; use super::openclip::text_model; use candle::{Result, Tensor, D}; use candle_nn::{Func, VarBuilder}; #[derive(Clone, Debug)] pub struct MobileClipModel { text_model: text_model::OpenClipTextTransformer, vision_model: Func<'static>, text_projection: Tensor, logit_scale: Tensor, } #[derive(Clone, Debug)] pub struct MobileClipConfig { pub text_config: text_model::Config, pub vision_config: fastvit::Config, pub image_size: usize, } impl MobileClipConfig { pub fn s1() -> Self { let text_config = text_model::Config::vit_base_patch32(); let vision_config = fastvit::Config::mci1(); Self { text_config, vision_config, image_size: 256, } } pub fn s2() -> Self { let text_config = text_model::Config::vit_base_patch32(); let vision_config = fastvit::Config::mci2(); Self { text_config, vision_config, image_size: 256, } } } impl MobileClipModel { pub fn new(vs: VarBuilder, c: &MobileClipConfig) -> Result<Self> { let vision_model = fastvit::fastvit(&c.vision_config, 512, vs.pp("visual.trunk"))?; let text_model = text_model::OpenClipTextTransformer::new(vs.pp("text"), &c.text_config)?; let text_projection = vs.get( (c.text_config.embed_dim, c.text_config.projection_dim), "text.text_projection", )?; let logit_scale = vs.get(&[], "logit_scale")?; Ok(Self { text_model, vision_model, text_projection, logit_scale, }) } pub fn get_text_features(&self, input_ids: &Tensor) -> Result<Tensor> { input_ids .apply(&self.text_model)? .matmul(&self.text_projection) } pub fn get_image_features(&self, pixel_values: &Tensor) -> Result<Tensor> { pixel_values.apply(&self.vision_model) } pub fn forward(&self, pixel_values: &Tensor, input_ids: &Tensor) -> Result<(Tensor, Tensor)> { let image_features = self.get_image_features(pixel_values)?; let text_features = self.get_text_features(input_ids)?; let image_features_normalized = div_l2_norm(&image_features)?; let text_features_normalized = div_l2_norm(&text_features)?; let logits_per_text = text_features_normalized.matmul(&image_features_normalized.t()?)?; let logit_scale = self.logit_scale.exp()?; let logits_per_text = logits_per_text.broadcast_mul(&logit_scale)?; let logits_per_image = logits_per_text.t()?; Ok((logits_per_text, logits_per_image)) } } pub fn div_l2_norm(v: &Tensor) -> Result<Tensor> { let l2_norm = v.sqr()?.sum_keepdim(D::Minus1)?.sqrt()?; v.broadcast_div(&l2_norm) }
candle/candle-transformers/src/models/mobileclip.rs/0
{ "file_path": "candle/candle-transformers/src/models/mobileclip.rs", "repo_id": "candle", "token_count": 1499 }
62
//! Persimmon Model //! //! A transformer language model for efficient inference and general-purpose tasks. The model uses a standard transformer architecture with: //! - Layer normalization for Q/K attention //! - RoPE embeddings with partial rotary factor //! - ReLU activation //! - Separate number of attention heads and KV heads //! //! References: //! - 💻 [Hugging Face Implementation](https://github.com/huggingface/transformers/blob/main/src/transformers/models/persimmon/modeling_persimmon.py) //! - 💻 [Persimmon Config](https://github.com/huggingface/transformers/blob/main/src/transformers/models/persimmon/configuration_persimmon.py) //! - 🤗 [Hugging Face](https://huggingface.co/adept/persimmon-8b-base) //! use candle::DType; use serde::Deserialize; pub const DTYPE: DType = DType::F32; #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] #[serde(rename_all = "lowercase")] pub enum PositionEmbeddingType { Absolute, Alibi, } // https://github.com/huggingface/transformers/blob/main/src/transformers/models/persimmon/configuration_persimmon.py #[derive(Debug, Clone, PartialEq, Deserialize)] pub struct Config { pub vocab_size: usize, pub hidden_size: usize, pub intermediate_size: usize, pub num_hidden_layers: usize, pub num_attention_heads: usize, pub num_key_value_heads: usize, pub hidden_act: candle_nn::Activation, pub max_position_embeddings: usize, pub initializer_range: f64, pub layer_norm_eps: f64, pub rms_norm_eps: f64, pub use_cache: bool, pub tie_word_embeddings: bool, pub rope_theta: f64, pub qk_layernorm: bool, pub partial_rotary_factor: f64, } impl Config { pub fn base_8b() -> Self { // https://huggingface.co/adept/persimmon-8b-base/blob/main/config.json Self { hidden_act: candle_nn::Activation::Relu, hidden_size: 4096, initializer_range: 0.02, intermediate_size: 16384, layer_norm_eps: 1e-05, max_position_embeddings: 16384, num_attention_heads: 64, num_hidden_layers: 36, num_key_value_heads: 64, qk_layernorm: true, rms_norm_eps: 1e-06, rope_theta: 25000.0, tie_word_embeddings: false, use_cache: true, vocab_size: 262144, partial_rotary_factor: 0.5, } } }
candle/candle-transformers/src/models/persimmon.rs/0
{ "file_path": "candle/candle-transformers/src/models/persimmon.rs", "repo_id": "candle", "token_count": 1045 }
63
//! Phi2 model implementation with quantization support. //! //! Phi2 is a 2.7B parameter language model using scaled-up Transformer decoder architecture. //! This implementation provides quantization for reduced memory and compute usage. //! //! Key characteristics: //! - Partial attention with learned mixing to reduce quadratic costs //! - Layer reuse for improved inference efficiency //! - Linear transformations with scalar mixing //! - Rotary positional embeddings (RoPE) //! - Support for 8-bit quantization //! //! References: //! - [Phi2 Paper](https://arxiv.org/abs/2309.05463) //! - [Model Card](https://huggingface.co/microsoft/phi-2) //! use std::collections::HashMap; use candle::quantized::gguf_file; use candle::quantized::QTensor; use candle::{DType, Device, IndexOp, Module, Result, Tensor, D}; use candle_nn::{Embedding, LayerNorm}; pub const MAX_SEQ_LEN: usize = 4096; #[derive(Debug, Clone)] struct QLinear { inner: candle::quantized::QMatMul, bias: Tensor, span: tracing::Span, } impl QLinear { fn new<R: std::io::Read + std::io::Seek>( ct: &gguf_file::Content, r: &mut R, name: &str, device: &Device, ) -> Result<Self> { let span = tracing::span!(tracing::Level::TRACE, "qmatmul"); let w = ct.tensor(r, &format!("{name}.weight"), device)?; let b = ct.tensor(r, &format!("{name}.bias"), device)?; let inner = candle::quantized::QMatMul::from_qtensor(w)?; let bias = b.dequantize(device)?; Ok(Self { inner, bias, span }) } } impl Module for QLinear { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); self.inner.forward(xs)?.broadcast_add(&self.bias) } } #[derive(Debug, Clone)] struct Mlp { ffn_up: QLinear, ffn_down: QLinear, } impl Module for Mlp { fn forward(&self, xs: &Tensor) -> Result<Tensor> { xs.apply(&self.ffn_up)?.gelu()?.apply(&self.ffn_down) } } #[derive(Debug, Clone)] struct LayerWeights { attn_qkv: QLinear, attn_output: QLinear, attn_norm: LayerNorm, mlp: Mlp, n_head: usize, n_kv_head: usize, head_dim: usize, cos: Tensor, sin: Tensor, rope_dim: usize, neg_inf: Tensor, kv_cache: Option<(Tensor, Tensor)>, span_attn: tracing::Span, span_rot: tracing::Span, } fn masked_fill(on_false: &Tensor, mask: &Tensor, on_true: &Tensor) -> Result<Tensor> { let shape = mask.shape(); let m = mask.where_cond(&on_true.broadcast_as(shape.dims())?, on_false)?; Ok(m) } impl LayerWeights { fn apply_rotary_emb(&self, xs: &Tensor, index_pos: usize) -> Result<Tensor> { let _enter = self.span_rot.enter(); let (_b_sz, _n_head, seq_len, _n_embd) = xs.dims4()?; let xs_rot = xs.i((.., .., .., ..self.rope_dim))?; let xs_pass = xs.i((.., .., .., self.rope_dim..))?; let cos = self.cos.narrow(0, index_pos, seq_len)?; let sin = self.sin.narrow(0, index_pos, seq_len)?; let xs_rot = candle_nn::rotary_emb::rope(&xs_rot.contiguous()?, &cos, &sin)?; Tensor::cat(&[&xs_rot, &xs_pass], D::Minus1) } fn forward_attn( &mut self, x: &Tensor, mask: Option<&Tensor>, index_pos: usize, ) -> Result<Tensor> { let _enter = self.span_attn.enter(); let (b_sz, seq_len, n_embd) = x.dims3()?; let qkv = self.attn_qkv .forward(x)? .reshape((b_sz, seq_len, 3, self.n_head, self.head_dim))?; let q = qkv.i((.., .., 0))?.transpose(1, 2)?; let k = qkv.i((.., .., 1))?.transpose(1, 2)?; let v = qkv.i((.., .., 2))?.transpose(1, 2)?; // This call to contiguous ensures that the fast kernel can be called below. It's // actually a no-op except when processing the initial prompt so has no significant // impact on performance. let v = v.contiguous()?; let q = self.apply_rotary_emb(&q, index_pos)?.contiguous()?; let k = self.apply_rotary_emb(&k, index_pos)?; let (k, v) = match &self.kv_cache { None => (k.contiguous()?, v.contiguous()?), Some((k_cache, v_cache)) => { if index_pos == 0 { (k.contiguous()?, v.contiguous()?) } else { let k = Tensor::cat(&[k_cache, &k], 2)?; let v = Tensor::cat(&[v_cache, &v], 2)?; (k.contiguous()?, v.contiguous()?) } } }; self.kv_cache = Some((k.clone(), v.clone())); let k = crate::utils::repeat_kv(k, self.n_head / self.n_kv_head)?; let v = crate::utils::repeat_kv(v, self.n_head / self.n_kv_head)?; let att = (q.matmul(&k.t()?)? / (self.head_dim as f64).sqrt())?; let att = match mask { None => att, Some(mask) => { let mask = mask.broadcast_as(att.shape())?; masked_fill(&att, &mask, &self.neg_inf)? } }; let att = candle_nn::ops::softmax_last_dim(&att)?; // Convert to contiguous as matmul doesn't support strided vs for now. let y = att.matmul(&v.contiguous()?)?; let y = y.transpose(1, 2)?.reshape(&[b_sz, seq_len, n_embd])?; let y = self.attn_output.forward(&y)?; Ok(y) } } #[derive(Debug, Clone)] pub struct ModelWeights { tok_embeddings: Embedding, layers: Vec<LayerWeights>, output_norm: LayerNorm, output: QLinear, masks: HashMap<usize, Tensor>, span: tracing::Span, span_output: tracing::Span, } fn precomput_freqs_cis( head_dim: usize, freq_base: f32, device: &Device, ) -> Result<(Tensor, Tensor)> { let theta: Vec<_> = (0..head_dim) .step_by(2) .map(|i| 1f32 / freq_base.powf(i as f32 / head_dim as f32)) .collect(); let theta = Tensor::new(theta.as_slice(), device)?; let idx_theta = Tensor::arange(0, MAX_SEQ_LEN as u32, device)? .to_dtype(DType::F32)? .reshape((MAX_SEQ_LEN, 1))? .matmul(&theta.reshape((1, theta.elem_count()))?)?; let cos = idx_theta.cos()?; let sin = idx_theta.sin()?; Ok((cos, sin)) } fn layer_norm(w: QTensor, b: QTensor, eps: f64) -> Result<LayerNorm> { let w = w.dequantize(&w.device())?; let b = b.dequantize(&b.device())?; let ln = LayerNorm::new(w, b, eps); Ok(ln) } impl ModelWeights { pub fn from_gguf<R: std::io::Seek + std::io::Read>( ct: gguf_file::Content, reader: &mut R, device: &Device, ) -> Result<Self> { let md_get = |s: &str| match ct.metadata.get(s) { None => candle::bail!("cannot find {s} in metadata"), Some(v) => Ok(v), }; // Parameter extraction from metadata. let head_count = md_get("phi2.attention.head_count")?.to_u32()? as usize; let head_count_kv = md_get("phi2.attention.head_count_kv")?.to_u32()? as usize; let block_count = md_get("phi2.block_count")?.to_u32()? as usize; let embedding_length = md_get("phi2.embedding_length")?.to_u32()? as usize; let rope_dim = md_get("phi2.rope.dimension_count")?.to_u32()? as usize; let ln_eps = md_get("phi2.attention.layer_norm_epsilon")?.to_f32()? as f64; let (cos, sin) = precomput_freqs_cis(rope_dim, 10_000., device)?; let neg_inf = Tensor::new(f32::NEG_INFINITY, device)?; let tok_embeddings = ct.tensor(reader, "token_embd.weight", device)?; let tok_embeddings = tok_embeddings.dequantize(device)?; let output_norm = layer_norm( ct.tensor(reader, "output_norm.weight", device)?, ct.tensor(reader, "output_norm.bias", device)?, ln_eps, )?; let output = QLinear::new(&ct, reader, "output", device)?; let mut layers = Vec::with_capacity(block_count); for layer_idx in 0..block_count { let prefix = format!("blk.{layer_idx}"); let ffn_up = QLinear::new(&ct, reader, &format!("{prefix}.ffn_up"), device)?; let ffn_down = QLinear::new(&ct, reader, &format!("{prefix}.ffn_down"), device)?; let mlp = Mlp { ffn_up, ffn_down }; let attn_norm = layer_norm( ct.tensor(reader, &format!("{prefix}.attn_norm.weight"), device)?, ct.tensor(reader, &format!("{prefix}.attn_norm.bias"), device)?, ln_eps, )?; let span_attn = tracing::span!(tracing::Level::TRACE, "attn"); let span_rot = tracing::span!(tracing::Level::TRACE, "attn-rot"); layers.push(LayerWeights { attn_qkv: QLinear::new(&ct, reader, &format!("{prefix}.attn_qkv"), device)?, attn_output: QLinear::new(&ct, reader, &format!("{prefix}.attn_output"), device)?, attn_norm, mlp, n_head: head_count, n_kv_head: head_count_kv, head_dim: embedding_length / head_count, cos: cos.clone(), sin: sin.clone(), rope_dim, neg_inf: neg_inf.clone(), kv_cache: None, span_attn, span_rot, }) } let span = tracing::span!(tracing::Level::TRACE, "model"); let span_output = tracing::span!(tracing::Level::TRACE, "output"); Ok(Self { tok_embeddings: Embedding::new(tok_embeddings, embedding_length), layers, output_norm, output, masks: HashMap::new(), span, span_output, }) } fn mask(&mut self, t: usize, device: &Device) -> Result<Tensor> { if let Some(mask) = self.masks.get(&t) { Ok(mask.clone()) } else { let mask: Vec<_> = (0..t) .flat_map(|i| (0..t).map(move |j| u8::from(j > i))) .collect(); let mask = Tensor::from_slice(&mask, (t, t), device)?; self.masks.insert(t, mask.clone()); Ok(mask) } } pub fn forward(&mut self, xs: &Tensor, index_pos: usize) -> Result<Tensor> { let (_b_sz, seq_len) = xs.dims2()?; let mask = if seq_len == 1 { None } else { Some(self.mask(seq_len, xs.device())?) }; let _enter = self.span.enter(); let mut xs = self.tok_embeddings.forward(xs)?; for layer in self.layers.iter_mut() { let residual = &xs; let xs_norm = xs.apply(&layer.attn_norm)?; let attn_outputs = layer.forward_attn(&xs_norm, mask.as_ref(), index_pos)?; let feed_forward_hidden_states = layer.mlp.forward(&xs_norm)?; xs = (attn_outputs + feed_forward_hidden_states + residual)? } let xs = xs.apply(&self.output_norm)?.i((.., seq_len - 1, ..))?; let _enter = self.span_output.enter(); self.output.forward(&xs) } }
candle/candle-transformers/src/models/quantized_phi.rs/0
{ "file_path": "candle/candle-transformers/src/models/quantized_phi.rs", "repo_id": "candle", "token_count": 5545 }
64
//! RWKV v5 model implementation. //! //! The [RWKV model](https://wiki.rwkv.com/) is a recurrent neural network model //! with performance on par with transformer architectures. Several variants are //! available, candle implements the v5 and v6 versions and can be used with //! Eagle 7B([blog post](https://blog.rwkv.com/p/eagle-7b-soaring-past-transformers)). //! //! Key characteristics: //! - Time-mix attention mechanism //! - Channel-mix feed-forward network //! - Linear attention //! - Group normalization //! - Token shift mechanism //! //! References: //! - [RWKV Language Model](https://github.com/BlinkDL/RWKV-LM) //! - [RWKV v5 Release](https://github.com/BlinkDL/ChatRWKV/tree/main) //! //! # Example //! //! ```bash //! cargo run --example rwkv --release -- \ //! --prompt "The smallest prime is " //! //! > avx: true, neon: false, simd128: false, f16c: true //! > temp: 0.00 repeat-penalty: 1.10 repeat-last-n: 64 //! > The smallest prime is ϕ(2) = 2. //! > The smallest composite is ϕ(3) = 3. //! > The smallest perfect number is ϕ(5) = 5. //! > The smallest perfect square is ϕ(4) = 4. //! > The smallest perfect cube is ϕ(6) = 6. //! ``` use super::with_tracing::{layer_norm, linear_no_bias as linear, LayerNorm, Linear}; use candle::{DType, Device, IndexOp, Result, Tensor}; use candle_nn::{embedding, Embedding, Module, VarBuilder}; use std::collections::{HashMap, HashSet}; fn default_num_attention_heads() -> usize { 64 } // https://huggingface.co/RWKV/HF_v5-Eagle-7B/blob/main/configuration_rwkv5.py #[derive(Debug, Clone, serde::Deserialize)] pub struct Config { pub vocab_size: usize, pub hidden_size: usize, pub num_hidden_layers: usize, pub attention_hidden_size: usize, #[serde(default = "default_num_attention_heads")] pub num_attention_heads: usize, pub head_size: usize, pub intermediate_size: Option<usize>, pub layer_norm_epsilon: f64, pub rescale_every: usize, } pub struct StatePerLayer { pub extract_key_value: Tensor, pub linear_attention: Tensor, pub feed_forward: Tensor, } pub struct State { pub per_layer: Vec<StatePerLayer>, pub pos: usize, } impl State { pub fn new(batch_size: usize, cfg: &Config, dev: &Device) -> Result<Self> { let mut per_layer = Vec::with_capacity(cfg.num_hidden_layers); // Certainly a weird convention but taken from modeling_rwkv5.py let num_attention_heads = cfg.hidden_size / cfg.num_attention_heads; for _layer_idx in 0..cfg.num_hidden_layers { let extract_key_value = Tensor::zeros((batch_size, cfg.hidden_size), DType::F32, dev)?; let linear_attention = Tensor::zeros( ( batch_size, num_attention_heads, cfg.hidden_size / num_attention_heads, cfg.hidden_size / num_attention_heads, ), DType::F32, dev, )?; let feed_forward = Tensor::zeros((batch_size, cfg.hidden_size), DType::F32, dev)?; per_layer.push(StatePerLayer { extract_key_value, linear_attention, feed_forward, }); } Ok(Self { per_layer, pos: 0 }) } } #[derive(Debug, Clone)] struct SelfAttention { key: Linear, receptance: Linear, value: Linear, gate: Linear, output: Linear, ln_x: candle_nn::GroupNorm, time_mix_key: Tensor, time_mix_value: Tensor, time_mix_receptance: Tensor, time_decay: Tensor, time_faaaa: Tensor, time_mix_gate: Tensor, layer_id: usize, n_attn_heads: usize, } impl SelfAttention { pub fn new(layer_id: usize, cfg: &Config, vb: VarBuilder) -> Result<Self> { let hidden_size = cfg.hidden_size; let attn_hidden_size = cfg.attention_hidden_size; let key = linear(hidden_size, attn_hidden_size, vb.pp("key"))?; let receptance = linear(hidden_size, attn_hidden_size, vb.pp("receptance"))?; let value = linear(hidden_size, attn_hidden_size, vb.pp("value"))?; let gate = linear(hidden_size, attn_hidden_size, vb.pp("gate"))?; let output = linear(attn_hidden_size, hidden_size, vb.pp("output"))?; let ln_x = candle_nn::group_norm( hidden_size / cfg.head_size, hidden_size, 1e-5, vb.pp("ln_x"), )?; let time_mix_key = vb.get((1, 1, cfg.hidden_size), "time_mix_key")?; let time_mix_value = vb.get((1, 1, cfg.hidden_size), "time_mix_value")?; let time_mix_receptance = vb.get((1, 1, cfg.hidden_size), "time_mix_receptance")?; let n_attn_heads = cfg.hidden_size / cfg.head_size; let time_decay = vb.get((n_attn_heads, cfg.head_size), "time_decay")?; let time_faaaa = vb.get((n_attn_heads, cfg.head_size), "time_faaaa")?; let time_mix_gate = vb.get((1, 1, cfg.hidden_size), "time_mix_gate")?; Ok(Self { key, value, receptance, gate, output, ln_x, time_mix_key, time_mix_value, time_mix_receptance, time_decay, time_faaaa, time_mix_gate, layer_id, n_attn_heads, }) } pub fn forward(&self, xs: &Tensor, state: &mut State) -> Result<Tensor> { let h = self.time_decay.dim(0)?; let (b, t, s) = xs.dims3()?; let s = s / h; let (receptance, key, value, gate) = { // extract key-value let shifted = state.per_layer[self.layer_id].extract_key_value.clone(); let shifted = if shifted.rank() == 2 { shifted.unsqueeze(1)? } else { shifted }; let key = ((xs * &self.time_mix_key)? + &shifted * (1.0 - &self.time_mix_key)?)?; let value = ((xs * &self.time_mix_value)? + &shifted * (1.0 - &self.time_mix_value)?)?; let receptance = ((xs * &self.time_mix_receptance)? + &shifted * (1.0 - &self.time_mix_receptance)?)?; let gate = ((xs * &self.time_mix_gate)? + &shifted * (1.0 - &self.time_mix_gate)?)?; let key = self.key.forward(&key)?; let value = self.value.forward(&value)?; let receptance = self.receptance.forward(&receptance)?; let gate = candle_nn::ops::silu(&self.gate.forward(&gate)?)?; state.per_layer[self.layer_id].extract_key_value = xs.i((.., t - 1))?; (receptance, key, value, gate) }; // linear attention let mut state_ = state.per_layer[self.layer_id].linear_attention.clone(); let key = key.reshape((b, t, h, s))?.permute((0, 2, 3, 1))?; let value = value.reshape((b, t, h, s))?.transpose(1, 2)?; let receptance = receptance.reshape((b, t, h, s))?.transpose(1, 2)?; let time_decay = self .time_decay .exp()? .neg()? .exp()? .reshape(((), 1, 1))? .reshape((self.n_attn_heads, (), 1))?; let time_faaaa = self.time_faaaa .reshape(((), 1, 1))? .reshape((self.n_attn_heads, (), 1))?; let mut out: Vec<Tensor> = Vec::with_capacity(t); for t_ in 0..t { let rt = receptance.i((.., .., t_..t_ + 1))?.contiguous()?; let kt = key.i((.., .., .., t_..t_ + 1))?.contiguous()?; let vt = value.i((.., .., t_..t_ + 1))?.contiguous()?; let at = kt.matmul(&vt)?; let rhs = (time_faaaa.broadcast_mul(&at)? + &state_)?; let out_ = rt.matmul(&rhs)?.squeeze(2)?; state_ = (&at + time_decay.broadcast_mul(&state_))?; out.push(out_) } let out = Tensor::cat(&out, 1)?.reshape((b * t, h * s, 1))?; let out = out.apply(&self.ln_x)?.reshape((b, t, h * s))?; let out = (out * gate)?.apply(&self.output)?; state.per_layer[self.layer_id].linear_attention = state_; Ok(out) } } #[derive(Debug, Clone)] struct FeedForward { time_mix_key: Tensor, time_mix_receptance: Tensor, key: Linear, receptance: Linear, value: Linear, layer_id: usize, } impl FeedForward { pub fn new(layer_id: usize, cfg: &Config, vb: VarBuilder) -> Result<Self> { let int_size = cfg .intermediate_size .unwrap_or(((cfg.hidden_size as f64 * 3.5) as usize) / 32 * 32); let key = linear(cfg.hidden_size, int_size, vb.pp("key"))?; let receptance = linear(cfg.hidden_size, cfg.hidden_size, vb.pp("receptance"))?; let value = linear(int_size, cfg.hidden_size, vb.pp("value"))?; let time_mix_key = vb.get((1, 1, cfg.hidden_size), "time_mix_key")?; let time_mix_receptance = vb.get((1, 1, cfg.hidden_size), "time_mix_receptance")?; Ok(Self { key, receptance, value, time_mix_key, time_mix_receptance, layer_id, }) } pub fn forward(&self, xs: &Tensor, state: &mut State) -> Result<Tensor> { let shifted = &state.per_layer[self.layer_id].feed_forward; let key = (xs.broadcast_mul(&self.time_mix_key)? + shifted.broadcast_mul(&(1.0 - &self.time_mix_key)?)?)?; let receptance = (xs.broadcast_mul(&self.time_mix_receptance)? + shifted.broadcast_mul(&(1.0 - &self.time_mix_receptance)?)?)?; let key = key.apply(&self.key)?.relu()?.sqr()?; let value = key.apply(&self.value)?; let receptance = candle_nn::ops::sigmoid(&receptance.apply(&self.receptance)?)?; state.per_layer[self.layer_id].feed_forward = xs.i((.., xs.dim(1)? - 1))?; let xs = (receptance * value)?; Ok(xs) } } #[derive(Debug, Clone)] struct Block { pre_ln: Option<LayerNorm>, ln1: LayerNorm, ln2: LayerNorm, attention: SelfAttention, feed_forward: FeedForward, } impl Block { pub fn new(layer_id: usize, cfg: &Config, vb: VarBuilder) -> Result<Self> { let ln1 = layer_norm(cfg.hidden_size, cfg.layer_norm_epsilon, vb.pp("ln1"))?; let ln2 = layer_norm(cfg.hidden_size, cfg.layer_norm_epsilon, vb.pp("ln2"))?; let pre_ln = if layer_id == 0 { let ln = layer_norm(cfg.hidden_size, cfg.layer_norm_epsilon, vb.pp("pre_ln"))?; Some(ln) } else { None }; let attention = SelfAttention::new(layer_id, cfg, vb.pp("attention"))?; let feed_forward = FeedForward::new(layer_id, cfg, vb.pp("feed_forward"))?; Ok(Self { pre_ln, ln1, ln2, attention, feed_forward, }) } pub fn forward(&self, xs: &Tensor, state: &mut State) -> Result<Tensor> { let xs = match self.pre_ln.as_ref() { None => xs.clone(), Some(pre_ln) => xs.apply(pre_ln)?, }; let attention = self.attention.forward(&xs.apply(&self.ln1)?, state)?; let xs = (xs + attention)?; let feed_forward = self.feed_forward.forward(&xs.apply(&self.ln2)?, state)?; let xs = (xs + feed_forward)?; Ok(xs) } } #[derive(Debug, Clone)] pub struct Model { embeddings: Embedding, blocks: Vec<Block>, ln_out: LayerNorm, head: Linear, rescale_every: usize, layers_are_rescaled: bool, } impl Model { pub fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let vb_m = vb.pp("rwkv"); let embeddings = embedding(cfg.vocab_size, cfg.hidden_size, vb_m.pp("embeddings"))?; let mut blocks = Vec::with_capacity(cfg.num_hidden_layers); let vb_b = vb_m.pp("blocks"); for block_index in 0..cfg.num_hidden_layers { let block = Block::new(block_index, cfg, vb_b.pp(block_index))?; blocks.push(block) } let ln_out = layer_norm(cfg.hidden_size, 1e-5, vb_m.pp("ln_out"))?; let head = linear(cfg.hidden_size, cfg.vocab_size, vb.pp("head"))?; Ok(Self { embeddings, blocks, ln_out, head, rescale_every: cfg.rescale_every, layers_are_rescaled: false, // This seem to only happen for the f16/bf16 dtypes. }) } pub fn forward(&self, xs: &Tensor, state: &mut State) -> Result<Tensor> { let (_b_size, _seq_len) = xs.dims2()?; let mut xs = xs.apply(&self.embeddings)?; for (block_idx, block) in self.blocks.iter().enumerate() { xs = block.forward(&xs, state)?; if self.layers_are_rescaled && (block_idx + 1) % self.rescale_every == 0 { xs = (xs / 2.)? } } let xs = xs.apply(&self.ln_out)?.apply(&self.head)?; state.pos += 1; Ok(xs) } } type Bytes = Vec<u8>; // https://github.com/BlinkDL/ChatRWKV/blob/095e812aef15a1f74107f6c39d13578a2412dc46/RWKV_v5_demo.py#L14 pub struct Tokenizer { table: Vec<Vec<Vec<Bytes>>>, good: Vec<HashSet<u8>>, idx2token: HashMap<u32, Vec<u8>>, token2idx: HashMap<Vec<u8>, u32>, } impl Tokenizer { pub fn new<P: AsRef<std::path::Path>>(p: P) -> Result<Self> { let file = std::fs::File::open(p)?; let token2idx: HashMap<String, u32> = serde_json::from_reader(file).map_err(candle::Error::wrap)?; let token2idx = token2idx .into_iter() .map(|(key, value)| (key.into_bytes(), value)) .collect::<HashMap<_, _>>(); let idx2token = token2idx .iter() .map(|(key, value)| (*value, key.to_vec())) .collect::<HashMap<_, _>>(); let max_idx = token2idx.values().copied().max().unwrap_or(0); let mut table = vec![vec![vec![]; 256]; 256]; let mut good = vec![HashSet::new(); 256]; for idx in (0..(1 + max_idx)).rev() { let s = match idx2token.get(&idx) { None => continue, Some(s) => s, }; if s.len() >= 2 { let (s0, s1) = (s[0], s[1]); table[s0 as usize][s1 as usize].push(s.to_vec()); good[s0 as usize].insert(s1); } } Ok(Self { table, good, idx2token, token2idx, }) } pub fn decode_bytes(&self, tokens: &[u32]) -> Vec<u8> { let mut v = Vec::new(); for token_id in tokens.iter() { if let Some(token) = self.idx2token.get(token_id) { v.extend_from_slice(token.as_slice()) } } v } pub fn decode(&self, tokens: &[u32]) -> Result<String> { let bytes = self.decode_bytes(tokens); String::from_utf8(bytes).map_err(candle::Error::wrap) } pub fn encode_bytes(&self, bytes: &[u8]) -> Result<Vec<u32>> { let mut tokens = Vec::new(); let mut i = 0; while i < bytes.len() { let mut s = vec![bytes[i]]; if i + 1 < bytes.len() && self.good[bytes[i] as usize].contains(&bytes[i + 1]) { let table = &self.table[bytes[i] as usize][bytes[i + 1] as usize]; for table_elem in table.iter() { if bytes[i..].starts_with(table_elem) { s = table_elem.to_vec(); break; } } } i += s.len(); let token = match self.token2idx.get(&s) { None => candle::bail!("unexpected token '{}' {s:?}", String::from_utf8_lossy(&s)), Some(token) => *token, }; tokens.push(token) } Ok(tokens) } pub fn encode(&self, str: &str) -> Result<Vec<u32>> { self.encode_bytes(str.as_bytes()) } }
candle/candle-transformers/src/models/rwkv_v5.rs/0
{ "file_path": "candle/candle-transformers/src/models/rwkv_v5.rs", "repo_id": "candle", "token_count": 8119 }
65
use candle::{Result, Tensor, D}; use candle_nn as nn; use candle_nn::Module; #[derive(Debug)] pub struct TimestepEmbedding { linear_1: nn::Linear, linear_2: nn::Linear, } impl TimestepEmbedding { // act_fn: "silu" pub fn new(vs: nn::VarBuilder, channel: usize, time_embed_dim: usize) -> Result<Self> { let linear_1 = nn::linear(channel, time_embed_dim, vs.pp("linear_1"))?; let linear_2 = nn::linear(time_embed_dim, time_embed_dim, vs.pp("linear_2"))?; Ok(Self { linear_1, linear_2 }) } } impl Module for TimestepEmbedding { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let xs = nn::ops::silu(&self.linear_1.forward(xs)?)?; self.linear_2.forward(&xs) } } #[derive(Debug)] pub struct Timesteps { num_channels: usize, flip_sin_to_cos: bool, downscale_freq_shift: f64, } impl Timesteps { pub fn new(num_channels: usize, flip_sin_to_cos: bool, downscale_freq_shift: f64) -> Self { Self { num_channels, flip_sin_to_cos, downscale_freq_shift, } } } impl Module for Timesteps { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let half_dim = (self.num_channels / 2) as u32; let exponent = (Tensor::arange(0, half_dim, xs.device())?.to_dtype(candle::DType::F32)? * -f64::ln(10000.))?; let exponent = (exponent / (half_dim as f64 - self.downscale_freq_shift))?; let emb = exponent.exp()?.to_dtype(xs.dtype())?; // emb = timesteps[:, None].float() * emb[None, :] let emb = xs.unsqueeze(D::Minus1)?.broadcast_mul(&emb.unsqueeze(0)?)?; let (cos, sin) = (emb.cos()?, emb.sin()?); let emb = if self.flip_sin_to_cos { Tensor::cat(&[&cos, &sin], D::Minus1)? } else { Tensor::cat(&[&sin, &cos], D::Minus1)? }; if self.num_channels % 2 == 1 { emb.pad_with_zeros(D::Minus2, 0, 1) } else { Ok(emb) } } }
candle/candle-transformers/src/models/stable_diffusion/embeddings.rs/0
{ "file_path": "candle/candle-transformers/src/models/stable_diffusion/embeddings.rs", "repo_id": "candle", "token_count": 1008 }
66
//! Vision Transformer (ViT) implementation. //! //! Vision Transformer applies transformer architecture to image classification //! by splitting images into patches and processing them as a sequence. //! //! Key characteristics: //! - Image patches as sequence tokens //! - Self-attention between patches //! - Position embeddings //! - CLS token for classification //! - Layer normalization //! //! References: //! - [ViT Paper](https://arxiv.org/abs/2010.11929) //! - [Model Card](https://huggingface.co/google/vit-base-patch16-224) //! use crate::models::with_tracing::{conv2d, linear, linear_no_bias, Conv2d, Linear}; use candle::{IndexOp, Module, Result, Tensor, D}; use candle_nn::{layer_norm, LayerNorm, VarBuilder}; // https://github.com/huggingface/transformers/blob/main/src/transformers/models/vit/configuration_vit.py #[derive(Debug, Clone, serde::Deserialize)] pub struct Config { pub hidden_size: usize, pub num_hidden_layers: usize, pub num_attention_heads: usize, pub intermediate_size: usize, pub hidden_act: candle_nn::Activation, pub layer_norm_eps: f64, pub image_size: usize, pub patch_size: usize, pub num_channels: usize, pub qkv_bias: bool, } impl Config { // https://huggingface.co/google/vit-base-patch16-224/blob/main/config.json pub fn vit_base_patch16_224() -> Self { Self { hidden_size: 768, num_hidden_layers: 12, num_attention_heads: 12, intermediate_size: 3072, hidden_act: candle_nn::Activation::Gelu, layer_norm_eps: 1e-12, image_size: 224, patch_size: 16, num_channels: 3, qkv_bias: true, } } pub fn microsoft_trocr_base_handwritten() -> Self { Self { hidden_size: 768, num_hidden_layers: 12, num_attention_heads: 12, intermediate_size: 3072, hidden_act: candle_nn::Activation::Gelu, layer_norm_eps: 1e-12, image_size: 384, patch_size: 16, num_channels: 3, qkv_bias: false, } } } #[derive(Debug, Clone)] struct PatchEmbeddings { num_patches: usize, projection: Conv2d, } impl PatchEmbeddings { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let image_size = cfg.image_size; let patch_size = cfg.patch_size; let num_patches = (image_size / patch_size) * (image_size / patch_size); let conv_cfg = candle_nn::Conv2dConfig { stride: patch_size, ..Default::default() }; let projection = conv2d( cfg.num_channels, cfg.hidden_size, patch_size, conv_cfg, vb.pp("projection"), )?; Ok(Self { num_patches, projection, }) } } impl Module for PatchEmbeddings { fn forward(&self, pixel_values: &Tensor) -> Result<Tensor> { let (_b_size, _num_channels, _height, _width) = pixel_values.dims4()?; self.projection .forward(pixel_values)? .flatten_from(2)? .transpose(1, 2) } } #[derive(Debug, Clone)] pub struct Embeddings { cls_token: Tensor, mask_token: Option<Tensor>, patch_embeddings: PatchEmbeddings, position_embeddings: Tensor, hidden_size: usize, } impl Embeddings { pub fn new(cfg: &Config, use_mask_token: bool, vb: VarBuilder) -> Result<Self> { let hidden_size = cfg.hidden_size; let cls_token = vb.get((1, 1, hidden_size), "cls_token")?; let mask_token = if use_mask_token { Some(vb.get((1, 1, hidden_size), "mask_token")?) } else { None }; let patch_embeddings = PatchEmbeddings::new(cfg, vb.pp("patch_embeddings"))?; let num_patches = patch_embeddings.num_patches; let position_embeddings = vb.get((1, num_patches + 1, hidden_size), "position_embeddings")?; Ok(Self { cls_token, mask_token, patch_embeddings, position_embeddings, hidden_size, }) } fn interpolate_pos_encoding( &self, _embeddings: &Tensor, _height: usize, _width: usize, ) -> Result<Tensor> { todo!() } pub fn forward( &self, pixel_values: &Tensor, bool_masked_pos: Option<&Tensor>, interpolate_pos_encoding: bool, ) -> Result<Tensor> { let (b_size, _num_channels, height, width) = pixel_values.dims4()?; let embeddings = self.patch_embeddings.forward(pixel_values)?; let embeddings = match (bool_masked_pos, &self.mask_token) { (None, _) => embeddings, (Some(_), None) => candle::bail!("bool_masked_pos set without mask_token"), (Some(bool_masked_pos), Some(mask_tokens)) => { let seq_len = embeddings.dim(1)?; let mask_tokens = mask_tokens.broadcast_as((b_size, seq_len, self.hidden_size))?; let mask = bool_masked_pos .unsqueeze(D::Minus1)? .to_dtype(mask_tokens.dtype())?; ((mask_tokens * &mask)? - (embeddings * (mask - 1.)?)?)? } }; let cls_tokens = self.cls_token.broadcast_as((b_size, 1, self.hidden_size))?; let embeddings = Tensor::cat(&[&cls_tokens, &embeddings], 1)?; if interpolate_pos_encoding { let pos = self.interpolate_pos_encoding(&embeddings, height, width)?; embeddings.broadcast_add(&pos) } else { embeddings.broadcast_add(&self.position_embeddings) } } } #[derive(Debug, Clone)] struct SelfAttention { query: Linear, key: Linear, value: Linear, num_attention_heads: usize, attention_head_size: usize, } impl SelfAttention { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let attention_head_size = cfg.hidden_size / cfg.num_attention_heads; let num_attention_heads = cfg.num_attention_heads; let all_head_size = num_attention_heads * attention_head_size; let linear = |name| { if cfg.qkv_bias { linear(cfg.hidden_size, all_head_size, vb.pp(name)) } else { linear_no_bias(cfg.hidden_size, all_head_size, vb.pp(name)) } }; let query = linear("query")?; let key = linear("key")?; let value = linear("value")?; Ok(Self { query, key, value, num_attention_heads, attention_head_size, }) } fn transpose_for_scores(&self, xs: &Tensor) -> Result<Tensor> { let (b_size, seq_len, _) = xs.dims3()?; xs.reshape(( b_size, seq_len, self.num_attention_heads, self.attention_head_size, ))? .permute((0, 2, 1, 3)) } } impl Module for SelfAttention { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let query = self.query.forward(xs)?; let key = self.key.forward(xs)?; let value = self.value.forward(xs)?; let query = self.transpose_for_scores(&query)?.contiguous()?; let key = self.transpose_for_scores(&key)?.contiguous()?; let value = self.transpose_for_scores(&value)?.contiguous()?; let attention_scores = (query.matmul(&key.t()?)? / f64::sqrt(self.attention_head_size as f64))?; let attention_probs = candle_nn::ops::softmax_last_dim(&attention_scores)?; attention_probs .matmul(&value)? .permute((0, 2, 1, 3))? .contiguous()? .flatten_from(D::Minus2) } } #[derive(Debug, Clone)] struct SelfOutput { dense: Linear, } impl SelfOutput { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let dense = linear(cfg.hidden_size, cfg.hidden_size, vb.pp("dense"))?; Ok(Self { dense }) } } impl Module for SelfOutput { fn forward(&self, xs: &Tensor) -> Result<Tensor> { xs.apply(&self.dense) } } #[derive(Debug, Clone)] struct Attention { attention: SelfAttention, output: SelfOutput, } impl Attention { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let attention = SelfAttention::new(cfg, vb.pp("attention"))?; let output = SelfOutput::new(cfg, vb.pp("output"))?; Ok(Self { attention, output }) } } impl Module for Attention { fn forward(&self, xs: &Tensor) -> Result<Tensor> { xs.apply(&self.attention)?.apply(&self.output) } } #[derive(Debug, Clone)] struct Intermediate { dense: Linear, intermediate_act_fn: candle_nn::Activation, } impl Intermediate { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let dense = linear(cfg.hidden_size, cfg.intermediate_size, vb.pp("dense"))?; Ok(Self { dense, intermediate_act_fn: cfg.hidden_act, }) } } impl Module for Intermediate { fn forward(&self, xs: &Tensor) -> Result<Tensor> { xs.apply(&self.dense)?.apply(&self.intermediate_act_fn) } } #[derive(Debug, Clone)] struct Output { dense: Linear, } impl Output { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let dense = linear(cfg.intermediate_size, cfg.hidden_size, vb.pp("dense"))?; Ok(Self { dense }) } fn forward(&self, xs: &Tensor, input_tensor: &Tensor) -> Result<Tensor> { xs.apply(&self.dense)? + input_tensor } } #[derive(Debug, Clone)] struct Layer { attention: Attention, intermediate: Intermediate, output: Output, layernorm_before: LayerNorm, layernorm_after: LayerNorm, } impl Layer { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let attention = Attention::new(cfg, vb.pp("attention"))?; let intermediate = Intermediate::new(cfg, vb.pp("intermediate"))?; let output = Output::new(cfg, vb.pp("output"))?; let h_sz = cfg.hidden_size; let layernorm_before = layer_norm(h_sz, cfg.layer_norm_eps, vb.pp("layernorm_before"))?; let layernorm_after = layer_norm(h_sz, cfg.layer_norm_eps, vb.pp("layernorm_after"))?; Ok(Self { attention, intermediate, output, layernorm_after, layernorm_before, }) } } impl Module for Layer { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let xs = (xs.apply(&self.layernorm_before)?.apply(&self.attention)? + xs)?; let ys = xs.apply(&self.layernorm_after)?.apply(&self.intermediate)?; self.output.forward(&ys, &xs) } } #[derive(Debug, Clone)] pub struct Encoder { layers: Vec<Layer>, } impl Encoder { pub fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let vb = vb.pp("layer"); let mut layers = Vec::with_capacity(cfg.num_hidden_layers); for i in 0..cfg.num_hidden_layers { let layer = Layer::new(cfg, vb.pp(i))?; layers.push(layer) } Ok(Self { layers }) } } impl Module for Encoder { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let mut xs = xs.clone(); for layer in self.layers.iter() { xs = xs.apply(layer)? } Ok(xs) } } #[derive(Debug, Clone)] pub struct Model { embeddings: Embeddings, encoder: Encoder, layernorm: LayerNorm, // no need for pooling layer for image classification classifier: Linear, } impl Model { pub fn new(cfg: &Config, num_labels: usize, vb: VarBuilder) -> Result<Self> { let vb_v = vb.pp("vit"); let embeddings = Embeddings::new(cfg, false, vb_v.pp("embeddings"))?; let encoder = Encoder::new(cfg, vb_v.pp("encoder"))?; let layernorm = layer_norm(cfg.hidden_size, cfg.layer_norm_eps, vb_v.pp("layernorm"))?; let classifier = linear(cfg.hidden_size, num_labels, vb.pp("classifier"))?; Ok(Self { embeddings, encoder, layernorm, classifier, }) } pub fn forward(&self, xs: &Tensor) -> Result<Tensor> { let embedding_output = self.embeddings.forward(xs, None, false)?; let encoder_outputs = self.encoder.forward(&embedding_output)?; encoder_outputs .i((.., 0, ..))? .apply(&self.layernorm)? .apply(&self.classifier) } }
candle/candle-transformers/src/models/vit.rs/0
{ "file_path": "candle/candle-transformers/src/models/vit.rs", "repo_id": "candle", "token_count": 6028 }
67
use super::common::{AttnBlock, ResBlock, TimestepBlock}; use candle::{DType, Result, Tensor, D}; use candle_nn::VarBuilder; #[derive(Debug)] struct Block { res_block: ResBlock, ts_block: TimestepBlock, attn_block: AttnBlock, } #[derive(Debug)] pub struct WPrior { projection: candle_nn::Conv2d, cond_mapper_lin1: candle_nn::Linear, cond_mapper_lin2: candle_nn::Linear, blocks: Vec<Block>, out_ln: super::common::WLayerNorm, out_conv: candle_nn::Conv2d, c_r: usize, } impl WPrior { #[allow(clippy::too_many_arguments)] pub fn new( c_in: usize, c: usize, c_cond: usize, c_r: usize, depth: usize, nhead: usize, use_flash_attn: bool, vb: VarBuilder, ) -> Result<Self> { let projection = candle_nn::conv2d(c_in, c, 1, Default::default(), vb.pp("projection"))?; let cond_mapper_lin1 = candle_nn::linear(c_cond, c, vb.pp("cond_mapper.0"))?; let cond_mapper_lin2 = candle_nn::linear(c, c, vb.pp("cond_mapper.2"))?; let out_ln = super::common::WLayerNorm::new(c)?; let out_conv = candle_nn::conv2d(c, c_in * 2, 1, Default::default(), vb.pp("out.1"))?; let mut blocks = Vec::with_capacity(depth); for index in 0..depth { let res_block = ResBlock::new(c, 0, 3, vb.pp(format!("blocks.{}", 3 * index)))?; let ts_block = TimestepBlock::new(c, c_r, vb.pp(format!("blocks.{}", 3 * index + 1)))?; let attn_block = AttnBlock::new( c, c, nhead, true, use_flash_attn, vb.pp(format!("blocks.{}", 3 * index + 2)), )?; blocks.push(Block { res_block, ts_block, attn_block, }) } Ok(Self { projection, cond_mapper_lin1, cond_mapper_lin2, blocks, out_ln, out_conv, c_r, }) } pub fn gen_r_embedding(&self, r: &Tensor) -> Result<Tensor> { const MAX_POSITIONS: usize = 10000; let r = (r * MAX_POSITIONS as f64)?; let half_dim = self.c_r / 2; let emb = (MAX_POSITIONS as f64).ln() / (half_dim - 1) as f64; let emb = (Tensor::arange(0u32, half_dim as u32, r.device())?.to_dtype(DType::F32)? * -emb)? .exp()?; let emb = r.unsqueeze(1)?.broadcast_mul(&emb.unsqueeze(0)?)?; let emb = Tensor::cat(&[emb.sin()?, emb.cos()?], 1)?; let emb = if self.c_r % 2 == 1 { emb.pad_with_zeros(D::Minus1, 0, 1)? } else { emb }; emb.to_dtype(r.dtype()) } pub fn forward(&self, xs: &Tensor, r: &Tensor, c: &Tensor) -> Result<Tensor> { let x_in = xs; let mut xs = xs.apply(&self.projection)?; let c_embed = c .apply(&self.cond_mapper_lin1)? .apply(&|xs: &_| candle_nn::ops::leaky_relu(xs, 0.2))? .apply(&self.cond_mapper_lin2)?; let r_embed = self.gen_r_embedding(r)?; for block in self.blocks.iter() { xs = block.res_block.forward(&xs, None)?; xs = block.ts_block.forward(&xs, &r_embed)?; xs = block.attn_block.forward(&xs, &c_embed)?; } let ab = xs.apply(&self.out_ln)?.apply(&self.out_conv)?.chunk(2, 1)?; (x_in - &ab[0])? / ((&ab[1] - 1.)?.abs()? + 1e-5) } }
candle/candle-transformers/src/models/wuerstchen/prior.rs/0
{ "file_path": "candle/candle-transformers/src/models/wuerstchen/prior.rs", "repo_id": "candle", "token_count": 1920 }
68
use candle::{DType, Device, Tensor}; use candle_nn::VarBuilder; use candle_transformers::models::bert::{BertModel, Config}; use candle_wasm_example_bert::console_log; use tokenizers::{PaddingParams, Tokenizer}; use wasm_bindgen::prelude::*; #[wasm_bindgen] pub struct Model { bert: BertModel, tokenizer: Tokenizer, } #[wasm_bindgen] impl Model { #[wasm_bindgen(constructor)] pub fn load(weights: Vec<u8>, tokenizer: Vec<u8>, config: Vec<u8>) -> Result<Model, JsError> { console_error_panic_hook::set_once(); console_log!("loading model"); let device = &Device::Cpu; let vb = VarBuilder::from_buffered_safetensors(weights, DType::F32, device)?; let config: Config = serde_json::from_slice(&config)?; let tokenizer = Tokenizer::from_bytes(&tokenizer).map_err(|m| JsError::new(&m.to_string()))?; let bert = BertModel::load(vb, &config)?; Ok(Self { bert, tokenizer }) } pub fn get_embeddings(&mut self, input: JsValue) -> Result<JsValue, JsError> { let input: Params = serde_wasm_bindgen::from_value(input).map_err(|m| JsError::new(&m.to_string()))?; let sentences = input.sentences; let normalize_embeddings = input.normalize_embeddings; let device = &Device::Cpu; if let Some(pp) = self.tokenizer.get_padding_mut() { pp.strategy = tokenizers::PaddingStrategy::BatchLongest } else { let pp = PaddingParams { strategy: tokenizers::PaddingStrategy::BatchLongest, ..Default::default() }; self.tokenizer.with_padding(Some(pp)); } let tokens = self .tokenizer .encode_batch(sentences.to_vec(), true) .map_err(|m| JsError::new(&m.to_string()))?; let token_ids: Vec<Tensor> = tokens .iter() .map(|tokens| { let tokens = tokens.get_ids().to_vec(); Tensor::new(tokens.as_slice(), device) }) .collect::<Result<Vec<_>, _>>()?; let attention_mask: Vec<Tensor> = tokens .iter() .map(|tokens| { let tokens = tokens.get_attention_mask().to_vec(); Tensor::new(tokens.as_slice(), device) }) .collect::<Result<Vec<_>, _>>()?; let token_ids = Tensor::stack(&token_ids, 0)?; let attention_mask = Tensor::stack(&attention_mask, 0)?; let token_type_ids = token_ids.zeros_like()?; console_log!("running inference on batch {:?}", token_ids.shape()); let embeddings = self .bert .forward(&token_ids, &token_type_ids, Some(&attention_mask))?; console_log!("generated embeddings {:?}", embeddings.shape()); // Apply some avg-pooling by taking the mean embedding value for all tokens (including padding) let (_n_sentence, n_tokens, _hidden_size) = embeddings.dims3()?; let embeddings = (embeddings.sum(1)? / (n_tokens as f64))?; let embeddings = if normalize_embeddings { embeddings.broadcast_div(&embeddings.sqr()?.sum_keepdim(1)?.sqrt()?)? } else { embeddings }; let embeddings_data = embeddings.to_vec2()?; Ok(serde_wasm_bindgen::to_value(&Embeddings { data: embeddings_data, })?) } } #[derive(serde::Serialize, serde::Deserialize)] struct Embeddings { data: Vec<Vec<f32>>, } #[derive(serde::Serialize, serde::Deserialize)] pub struct Params { sentences: Vec<String>, normalize_embeddings: bool, } fn main() { console_error_panic_hook::set_once(); }
candle/candle-wasm-examples/bert/src/bin/m.rs/0
{ "file_path": "candle/candle-wasm-examples/bert/src/bin/m.rs", "repo_id": "candle", "token_count": 1752 }
69
import init, { Model } from "./build/m.js"; async function fetchArrayBuffer(url) { const cacheName = "llama2c-candle-cache"; const cache = await caches.open(cacheName); const cachedResponse = await cache.match(url); if (cachedResponse) { const data = await cachedResponse.arrayBuffer(); return new Uint8Array(data); } const res = await fetch(url, { cache: "force-cache" }); cache.put(url, res.clone()); return new Uint8Array(await res.arrayBuffer()); } class Llama2C { static instance = {}; static async getInstance(weightsURL, modelID, tokenizerURL) { // load individual modelID only once if (!this.instance[modelID]) { await init(); self.postMessage({ status: "loading", message: "Loading Model" }); const [weightsArrayU8, tokenizerArrayU8] = await Promise.all([ fetchArrayBuffer(weightsURL), fetchArrayBuffer(tokenizerURL), ]); this.instance[modelID] = new Model(weightsArrayU8, tokenizerArrayU8); } return this.instance[modelID]; } } let controller = null; self.addEventListener("message", (event) => { if (event.data.command === "start") { controller = new AbortController(); generate(event.data); } else if (event.data.command === "abort") { controller.abort(); } }); async function generate(data) { const { weightsURL, modelID, tokenizerURL, prompt, temp, top_p, repeatPenalty, seed, maxSeqLen, } = data; try { self.postMessage({ status: "loading", message: "Starting llama2.c" }); const model = await Llama2C.getInstance(weightsURL, modelID, tokenizerURL); self.postMessage({ status: "loading", message: "Initializing model" }); const firstToken = model.init_with_prompt( prompt, temp, top_p, repeatPenalty, seed ); const seq_len = model.get_seq_len(); let sentence = firstToken; let maxTokens = maxSeqLen ? maxSeqLen : seq_len - prompt.length - 1; let startTime = performance.now(); let tokensCount = 0; while (tokensCount < maxTokens) { await new Promise(async (resolve) => { if (controller && controller.signal.aborted) { self.postMessage({ status: "aborted", message: "Aborted", output: prompt + sentence, }); return; } const token = await model.next_token(); const tokensSec = ((tokensCount + 1) / (performance.now() - startTime)) * 1000; sentence += token; self.postMessage({ status: "generating", message: "Generating token", token: token, sentence: sentence, totalTime: performance.now() - startTime, tokensSec, prompt: prompt, }); setTimeout(resolve, 0); }); tokensCount++; } self.postMessage({ status: "complete", message: "complete", output: prompt + sentence, }); } catch (e) { self.postMessage({ error: e }); } }
candle/candle-wasm-examples/llama2-c/llama2cWorker.js/0
{ "file_path": "candle/candle-wasm-examples/llama2-c/llama2cWorker.js", "repo_id": "candle", "token_count": 1223 }
70
[package] name = "candle-wasm-example-phi" version.workspace = true edition.workspace = true description.workspace = true repository.workspace = true keywords.workspace = true categories.workspace = true license.workspace = true [dependencies] candle = { workspace = true } candle-nn = { workspace = true } candle-transformers = { workspace = true } tokenizers = { workspace = true, features = ["unstable_wasm"] } num-traits = { workspace = true } # App crates. anyhow = { workspace = true } byteorder = { workspace = true } getrandom = { version = "0.2", features = ["js"] } image = { workspace = true } log = { workspace = true } safetensors = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } # Wasm specific crates. console_error_panic_hook = "0.1.7" wasm-bindgen = "0.2.87" js-sys = "0.3.64"
candle/candle-wasm-examples/phi/Cargo.toml/0
{ "file_path": "candle/candle-wasm-examples/phi/Cargo.toml", "repo_id": "candle", "token_count": 278 }
71
//load Candle Bert Module wasm module let init, ModelConditionalGeneration; async function fetchArrayBuffer(url) { const cacheName = "t5-candle-cache"; const cache = await caches.open(cacheName); const cachedResponse = await cache.match(url); if (cachedResponse) { const data = await cachedResponse.arrayBuffer(); return new Uint8Array(data); } const res = await fetch(url, { cache: "force-cache" }); cache.put(url, res.clone()); return new Uint8Array(await res.arrayBuffer()); } class ConditionalGeneration { static instance = {}; static async getInstance(weightsURL, tokenizerURL, configURL, modelID) { if (modelID.includes("quantized")) { ({ default: init, ModelConditionalGeneration } = await import( "./build/m-quantized.js" )); } else { ({ default: init, ModelConditionalGeneration } = await import( "./build/m.js" )); } if (!this.instance[modelID]) { await init(); self.postMessage({ status: "loading", message: "Loading Model" }); const [weightsArrayU8, tokenizerArrayU8, configArrayU8] = await Promise.all([ fetchArrayBuffer(weightsURL), fetchArrayBuffer(tokenizerURL), fetchArrayBuffer(configURL), ]); this.instance[modelID] = new ModelConditionalGeneration( weightsArrayU8, tokenizerArrayU8, configArrayU8 ); } else { self.postMessage({ status: "ready", message: "Model Already Loaded" }); } return this.instance[modelID]; } } self.addEventListener("message", async (event) => { const { weightsURL, tokenizerURL, configURL, modelID, prompt, params } = event.data; let { temperature = 0.0, seed = 299792458, repeat_penalty = 1.1, repeat_last_n = 64, top_p = 1, } = { ...params }; try { self.postMessage({ status: "ready", message: "Starting T5 Conditional Generation", }); const model = await ConditionalGeneration.getInstance( weightsURL, tokenizerURL, configURL, modelID ); self.postMessage({ status: "decoding", message: "Decoding Prompt", }); const output = model.decode({ prompt, temperature, seed, top_p, repeat_penalty, repeat_last_n, }); self.postMessage({ status: "complete", message: "complete", output: output, }); } catch (e) { self.postMessage({ error: e }); } });
candle/candle-wasm-examples/t5/T5ModelConditionalGeneration.js/0
{ "file_path": "candle/candle-wasm-examples/t5/T5ModelConditionalGeneration.js", "repo_id": "candle", "token_count": 980 }
72
fn main() { wasm_logger::init(wasm_logger::Config::new(log::Level::Trace)); yew::Renderer::<candle_wasm_example_whisper::App>::new().render(); }
candle/candle-wasm-examples/whisper/src/bin/app.rs/0
{ "file_path": "candle/candle-wasm-examples/whisper/src/bin/app.rs", "repo_id": "candle", "token_count": 67 }
73
pub const NAMES: [&str; 80] = [ "person", "bicycle", "car", "motorbike", "aeroplane", "bus", "train", "truck", "boat", "traffic light", "fire hydrant", "stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow", "elephant", "bear", "zebra", "giraffe", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee", "skis", "snowboard", "sports ball", "kite", "baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket", "bottle", "wine glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich", "orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake", "chair", "sofa", "pottedplant", "bed", "diningtable", "toilet", "tvmonitor", "laptop", "mouse", "remote", "keyboard", "cell phone", "microwave", "oven", "toaster", "sink", "refrigerator", "book", "clock", "vase", "scissors", "teddy bear", "hair drier", "toothbrush", ];
candle/candle-wasm-examples/yolo/src/coco_classes.rs/0
{ "file_path": "candle/candle-wasm-examples/yolo/src/coco_classes.rs", "repo_id": "candle", "token_count": 648 }
74
{ "version": "0.2.0", "configurations": [ { "command": "npm run dev", "name": "Run development server", "request": "launch", "type": "node-terminal" } ] }
chat-ui/.vscode/launch.json/0
{ "file_path": "chat-ui/.vscode/launch.json", "repo_id": "chat-ui", "token_count": 82 }
75
{{- if $.Values.networkPolicy.enabled }} apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: {{ include "name" . }} namespace: {{ .Release.Namespace }} spec: egress: - ports: - port: 53 protocol: UDP to: - namespaceSelector: matchLabels: kubernetes.io/metadata.name: kube-system podSelector: matchLabels: k8s-app: kube-dns - to: {{- range $ip := .Values.networkPolicy.allowedBlocks }} - ipBlock: cidr: {{ $ip | quote }} {{- end }} - to: - ipBlock: cidr: 0.0.0.0/0 except: - 10.0.0.0/8 - 172.16.0.0/12 - 192.168.0.0/16 - 169.254.169.254/32 podSelector: matchLabels: {{ include "labels.standard" . | nindent 6 }} policyTypes: - Egress {{- end }}
chat-ui/chart/templates/network-policy.yaml/0
{ "file_path": "chat-ui/chart/templates/network-policy.yaml", "repo_id": "chat-ui", "token_count": 494 }
76
# LangServe | Feature | Available | | --------------------------- | --------- | | [Tools](../tools) | No | | [Multimodal](../multimodal) | No | LangChain applications that are deployed using LangServe can be called with the following config: ```ini MODELS=`[ { "name": "summarization-chain", "displayName": "Summarization Chain" "endpoints" : [{ "type": "langserve", "url" : "http://127.0.0.1:8100", }] } ]` ```
chat-ui/docs/source/configuration/models/providers/langserve.md/0
{ "file_path": "chat-ui/docs/source/configuration/models/providers/langserve.md", "repo_id": "chat-ui", "token_count": 220 }
77
import { publicConfigTransporter } from "$lib/utils/PublicConfig.svelte"; import type { Transport } from "@sveltejs/kit"; export const transport: Transport = { PublicConfig: publicConfigTransporter, };
chat-ui/src/hooks.ts/0
{ "file_path": "chat-ui/src/hooks.ts", "repo_id": "chat-ui", "token_count": 57 }
78
<script lang="ts" module> let isOpen = $state(false); export function closeMobileNav() { isOpen = false; } </script> <script lang="ts"> import { browser } from "$app/environment"; import { beforeNavigate } from "$app/navigation"; import { base } from "$app/paths"; import { page } from "$app/state"; import IconNew from "$lib/components/icons/IconNew.svelte"; import { Spring } from "svelte/motion"; import CarbonClose from "~icons/carbon/close"; import CarbonTextAlignJustify from "~icons/carbon/text-align-justify"; import { pan, type GestureCustomEvent, type PanCustomEvent } from "svelte-gestures"; interface Props { title: string | undefined; children?: import("svelte").Snippet; } let { title = $bindable(), children }: Props = $props(); let closeEl: HTMLButtonElement | undefined = $state(); let openEl: HTMLButtonElement | undefined = $state(); let panX: number | undefined = $state(undefined); let panStart: number | undefined = $state(undefined); let panStartTime: number | undefined = undefined; // Define the width for the drawer (less than 100% to create the gap) const drawerWidthPercentage = 85; const tween = Spring.of( () => { if (panX !== undefined) { return panX; } if (isOpen) { return 0 as number; } return -100 as number; }, { stiffness: 0.2, damping: 0.8 } ); $effect(() => { title ??= "New Chat"; }); beforeNavigate(() => { isOpen = false; panX = undefined; }); let shouldFocusClose = $derived(isOpen && closeEl); let shouldRefocusOpen = $derived(!isOpen && browser && document.activeElement === closeEl); $effect(() => { if (shouldFocusClose) { closeEl?.focus(); } else if (shouldRefocusOpen) { openEl?.focus(); } }); // Function to close the drawer when background is tapped function closeDrawer() { isOpen = false; panX = undefined; } </script> <nav class="flex h-12 items-center justify-between border-b bg-gray-50 px-3 dark:border-gray-800 dark:bg-gray-800/70 md:hidden" > <button type="button" class="-ml-3 flex size-12 shrink-0 items-center justify-center text-lg" onclick={() => (isOpen = true)} aria-label="Open menu" bind:this={openEl}><CarbonTextAlignJustify /></button > <div class="flex h-full items-center justify-center overflow-hidden"> {#if page.params?.id} <span class="max-w-full truncate px-4" data-testid="chat-title">{title}</span> {/if} </div> <a class:invisible={!page.params?.id} href="{base}/" class="-mr-3 flex size-12 shrink-0 items-center justify-center text-lg"><IconNew /></a > </nav> <!-- Mobile drawer overlay - shows when drawer is open --> {#if isOpen} <button type="button" class="fixed inset-0 z-20 cursor-default bg-black/30 md:hidden" style="opacity: {Math.max(0, Math.min(1, (100 + tween.current) / 100))};" onclick={closeDrawer} aria-label="Close mobile navigation" ></button> {/if} <nav use:pan={() => ({ delay: 0, preventdefault: true, touchAction: "pan-left" })} onpanup={(e: GestureCustomEvent) => { if (!panStart || !panStartTime || !panX) { return; } // measure the pan velocity to determine if the menu should snap open or closed const drawerWidth = window.innerWidth * (drawerWidthPercentage / 100); const trueX = e.detail.x + (panX / 100) * drawerWidth; const panDuration = Date.now() - panStartTime; const panVelocity = (trueX - panStart) / panDuration; panX = undefined; panStart = undefined; panStartTime = undefined; if (panVelocity < -0.5 || trueX < 50) { isOpen = !isOpen; } }} onpan={(e: PanCustomEvent) => { if (e.detail.pointerType !== "touch") { panX = undefined; panStart = undefined; panStartTime = undefined; return; } panX ??= 0; panStart ??= e.detail.x; panStartTime ??= Date.now(); const drawerWidth = window.innerWidth * (drawerWidthPercentage / 100); const trueX = e.detail.x + (panX / 100) * drawerWidth; const percentage = ((trueX - panStart) / drawerWidth) * 100; panX = Math.max(-100, Math.min(0, percentage)); tween.set(panX, { instant: true }); }} style="transform: translateX({Math.max( -100, Math.min(0, tween.current) )}%); width: {drawerWidthPercentage}%;" class:shadow-[5px_0_15px_0_rgba(0,0,0,0.3)]={isOpen} class="fixed bottom-0 left-0 top-0 z-30 grid max-h-screen grid-cols-1 grid-rows-[auto,1fr,auto,auto] bg-white pt-4 dark:bg-gray-900 md:hidden" > {#if page.url.pathname === base + "/"} <button type="button" class="absolute right-0 top-0 z-50 flex size-12 items-center justify-center text-lg" onclick={() => (isOpen = false)} aria-label="Close menu" bind:this={closeEl}><CarbonClose /></button > {/if} {@render children?.()} </nav>
chat-ui/src/lib/components/MobileNav.svelte/0
{ "file_path": "chat-ui/src/lib/components/MobileNav.svelte", "repo_id": "chat-ui", "token_count": 1778 }
79
<script lang="ts"> import { fade } from "svelte/transition"; import Portal from "./Portal.svelte"; import IconDazzled from "$lib/components/icons/IconDazzled.svelte"; interface Props { message?: string; } let { message = "" }: Props = $props(); </script> <Portal> <div transition:fade|global={{ duration: 300 }} class="pointer-events-none fixed right-0 top-12 z-50 bg-gradient-to-bl from-red-500/20 via-red-500/0 to-red-500/0 pb-36 pl-36 pr-2 pt-2 md:top-0 md:pr-8 md:pt-5" > <div class="pointer-events-auto flex items-center rounded-full bg-white/90 px-3 py-1 shadow-sm dark:bg-gray-900/80" > <IconDazzled classNames="text-2xl mr-2" /> <h2 class="max-w-2xl font-semibold text-gray-800 dark:text-gray-200">{message}</h2> </div> </div> </Portal>
chat-ui/src/lib/components/Toast.svelte/0
{ "file_path": "chat-ui/src/lib/components/Toast.svelte", "repo_id": "chat-ui", "token_count": 337 }
80
import MarkdownRenderer from "./MarkdownRenderer.svelte"; import { render } from "vitest-browser-svelte"; import { page } from "@vitest/browser/context"; import { describe, expect, it } from "vitest"; describe("MarkdownRenderer", () => { it("renders", () => { render(MarkdownRenderer, { content: "Hello, world!" }); expect(page.getByText("Hello, world!")).toBeInTheDocument(); }); it("renders headings", () => { render(MarkdownRenderer, { content: "# Hello, world!" }); expect(page.getByRole("heading", { level: 1 })).toBeInTheDocument(); }); it("renders links", () => { render(MarkdownRenderer, { content: "[Hello, world!](https://example.com)" }); const link = page.getByRole("link", { name: "Hello, world!" }); expect(link).toBeInTheDocument(); expect(link).toHaveAttribute("href", "https://example.com"); expect(link).toHaveAttribute("target", "_blank"); expect(link).toHaveAttribute("rel", "noreferrer"); }); it("renders inline codespans", () => { render(MarkdownRenderer, { content: "`foobar`" }); expect(page.getByRole("code")).toHaveTextContent("foobar"); }); it("renders block codes", () => { render(MarkdownRenderer, { content: "```foobar```" }); expect(page.getByRole("code")).toHaveTextContent("foobar"); }); it("renders sources correctly", () => { const props = { content: "Hello there [1]", sources: [ { title: "foo", link: "https://example.com", }, ], }; render(MarkdownRenderer, props); const link = page.getByRole("link"); expect(link).toBeInTheDocument(); expect(link).toHaveAttribute("href", "https://example.com"); expect(link).toHaveAttribute("target", "_blank"); expect(link).toHaveAttribute("rel", "noreferrer"); }); it("handles groups of sources", () => { render(MarkdownRenderer, { content: "Hello there [1], [2], [3]", sources: [ { title: "foo", link: "https://foo.com", }, { title: "bar", link: "https://bar.com", }, { title: "baz", link: "https://baz.com", }, ], }); expect(page.getByRole("link").all()).toHaveLength(3); expect(page.getByRole("link").nth(0)).toHaveAttribute("href", "https://foo.com"); expect(page.getByRole("link").nth(1)).toHaveAttribute("href", "https://bar.com"); expect(page.getByRole("link").nth(2)).toHaveAttribute("href", "https://baz.com"); }); it("does not render sources in code blocks", () => { render(MarkdownRenderer, { content: "```\narray[1]\n```", sources: [ { title: "foo", link: "https://example.com", }, ], }); const linkSelector = page.getByRole("link"); expect(linkSelector.elements).toHaveLength(0); }); it("doesnt render raw html directly", () => { render(MarkdownRenderer, { content: "<button>Click me</button>" }); expect(page.getByRole("button").elements).toHaveLength(0); expect(page.getByRole("paragraph")).toHaveTextContent("<button>Click me</button>"); }); it("renders latex", () => { const { baseElement } = render(MarkdownRenderer, { content: "$(oo)^2$" }); expect(baseElement.querySelectorAll(".katex")).toHaveLength(1); }); it("does not render latex in code blocks", () => { const { baseElement } = render(MarkdownRenderer, { content: "```\n$(oo)^2$\n```" }); expect(baseElement.querySelectorAll(".katex")).toHaveLength(0); }); it("does not render latex in inline codes", () => { const { baseElement } = render(MarkdownRenderer, { content: "`$oo` and `$bar`" }); expect(baseElement.querySelectorAll(".katex")).toHaveLength(0); }); it("does not render latex across multiple lines", () => { const { baseElement } = render(MarkdownRenderer, { content: "* $oo \n* $aa" }); expect(baseElement.querySelectorAll(".katex")).toHaveLength(0); }); it("renders latex with some < and > symbols", () => { const { baseElement } = render(MarkdownRenderer, { content: "$foo < bar > baz$" }); expect(baseElement.querySelectorAll(".katex")).toHaveLength(1); }); });
chat-ui/src/lib/components/chat/MarkdownRenderer.svelte.test.ts/0
{ "file_path": "chat-ui/src/lib/components/chat/MarkdownRenderer.svelte.test.ts", "repo_id": "chat-ui", "token_count": 1558 }
81
import type { Migration } from "."; import { collections } from "$lib/server/database"; import { ObjectId, type WithId } from "mongodb"; import type { Conversation } from "$lib/types/Conversation"; import { MessageUpdateType, MessageWebSearchUpdateType, type MessageUpdate, } from "$lib/types/MessageUpdate"; import type { Message } from "$lib/types/Message"; import { logger } from "$lib/server/logger"; // ----------- /** Converts the old message update to the new schema */ function convertMessageUpdate(message: Message, update: MessageUpdate): MessageUpdate | null { try { // trim final websearch update, and sources update if (update.type === "webSearch") { if (update.subtype === MessageWebSearchUpdateType.Sources) { return { type: MessageUpdateType.WebSearch, subtype: MessageWebSearchUpdateType.Sources, message: update.message, sources: update.sources.map(({ link, title }) => ({ link, title })), }; } else if (update.subtype === MessageWebSearchUpdateType.Finished) { return { type: MessageUpdateType.WebSearch, subtype: MessageWebSearchUpdateType.Finished, }; } } return update; } catch (error) { logger.error(error, "Error converting message update during migration. Skipping it.."); return null; } } const trimMessageUpdates: Migration = { _id: new ObjectId("000000000000000000000006"), name: "Trim message updates to reduce stored size", up: async () => { const allConversations = collections.conversations.find({}); let conversation: WithId<Pick<Conversation, "messages">> | null = null; while ((conversation = await allConversations.tryNext())) { const messages = conversation.messages.map((message) => { // Convert all of the existing updates to the new schema const updates = message.updates ?.map((update) => convertMessageUpdate(message, update)) .filter((update): update is MessageUpdate => Boolean(update)); return { ...message, updates }; }); // Set the new messages array await collections.conversations.updateOne({ _id: conversation._id }, { $set: { messages } }); } return true; }, runEveryTime: false, }; export default trimMessageUpdates;
chat-ui/src/lib/migrations/routines/06-trim-message-updates.ts/0
{ "file_path": "chat-ui/src/lib/migrations/routines/06-trim-message-updates.ts", "repo_id": "chat-ui", "token_count": 703 }
82
import { Elysia } from "elysia"; import { authPlugin } from "$api/authPlugin"; import { defaultModel } from "$lib/server/models"; import { collections } from "$lib/server/database"; import { authCondition } from "$lib/server/auth"; import { models, validateModel } from "$lib/server/models"; import { DEFAULT_SETTINGS, type SettingsEditable } from "$lib/types/Settings"; import { toolFromConfigs } from "$lib/server/tools"; import { ObjectId } from "mongodb"; import { z } from "zod"; export const userGroup = new Elysia() .use(authPlugin) .get("/login", () => { // todo: login throw new Error("Not implemented"); }) .get("/login/callback", () => { // todo: login callback throw new Error("Not implemented"); }) .post("/logout", () => { // todo: logout throw new Error("Not implemented"); }) .group("/user", (app) => { return app .get("/", ({ locals }) => { return locals.user ? { id: locals.user._id.toString(), username: locals.user.username, avatarUrl: locals.user.avatarUrl, email: locals.user.email, logoutDisabled: locals.user.logoutDisabled, isAdmin: locals.user.isAdmin ?? false, isEarlyAccess: locals.user.isEarlyAccess ?? false, } : null; }) .get("/settings", async ({ locals }) => { const settings = await collections.settings.findOne(authCondition(locals)); if ( settings && !validateModel(models).safeParse(settings?.activeModel).success && !settings.assistants?.map((el) => el.toString())?.includes(settings?.activeModel) ) { settings.activeModel = defaultModel.id; await collections.settings.updateOne(authCondition(locals), { $set: { activeModel: defaultModel.id }, }); } // if the model is unlisted, set the active model to the default model if ( settings?.activeModel && models.find((m) => m.id === settings?.activeModel)?.unlisted === true ) { settings.activeModel = defaultModel.id; await collections.settings.updateOne(authCondition(locals), { $set: { activeModel: defaultModel.id }, }); } // todo: get user settings return { ethicsModalAccepted: !!settings?.ethicsModalAcceptedAt, ethicsModalAcceptedAt: settings?.ethicsModalAcceptedAt ?? null, activeModel: settings?.activeModel ?? DEFAULT_SETTINGS.activeModel, hideEmojiOnSidebar: settings?.hideEmojiOnSidebar ?? DEFAULT_SETTINGS.hideEmojiOnSidebar, disableStream: settings?.disableStream ?? DEFAULT_SETTINGS.disableStream, directPaste: settings?.directPaste ?? DEFAULT_SETTINGS.directPaste, shareConversationsWithModelAuthors: settings?.shareConversationsWithModelAuthors ?? DEFAULT_SETTINGS.shareConversationsWithModelAuthors, customPrompts: settings?.customPrompts ?? {}, assistants: settings?.assistants?.map((assistantId) => assistantId.toString()) ?? [], tools: settings?.tools ?? toolFromConfigs .filter((el) => !el.isHidden && el.isOnByDefault) .map((el) => el._id.toString()), }; }) .post("/settings", async ({ locals, request }) => { const body = await request.json(); const { ethicsModalAccepted, ...settings } = z .object({ shareConversationsWithModelAuthors: z .boolean() .default(DEFAULT_SETTINGS.shareConversationsWithModelAuthors), hideEmojiOnSidebar: z.boolean().default(DEFAULT_SETTINGS.hideEmojiOnSidebar), ethicsModalAccepted: z.boolean().optional(), activeModel: z.string().default(DEFAULT_SETTINGS.activeModel), customPrompts: z.record(z.string()).default({}), tools: z.array(z.string()).optional(), disableStream: z.boolean().default(false), directPaste: z.boolean().default(false), }) .parse(body) satisfies SettingsEditable; // make sure all tools exist // either in db or in config if (settings.tools) { const newTools = [ ...(await collections.tools .find({ _id: { $in: settings.tools.map((toolId) => new ObjectId(toolId)) } }) .project({ _id: 1 }) .toArray() .then((tools) => tools.map((tool) => tool._id.toString()))), ...toolFromConfigs .filter((el) => (settings?.tools ?? []).includes(el._id.toString())) .map((el) => el._id.toString()), ]; settings.tools = newTools; } await collections.settings.updateOne( authCondition(locals), { $set: { ...settings, ...(ethicsModalAccepted && { ethicsModalAcceptedAt: new Date() }), updatedAt: new Date(), }, $setOnInsert: { createdAt: new Date(), }, }, { upsert: true, } ); // return ok response return new Response(); }) .get("/reports", async ({ locals }) => { if (!locals.user || !locals.sessionId) { return []; } const reports = await collections.reports .find({ createdBy: locals.user?._id ?? locals.sessionId, }) .toArray(); return reports; }) .get("/assistant/active", async ({ locals }) => { const settings = await collections.settings.findOne(authCondition(locals)); if (!settings) { return null; } if (settings.assistants?.map((el) => el.toString())?.includes(settings?.activeModel)) { return await collections.assistants.findOne({ _id: new ObjectId(settings.activeModel), }); } return null; }) .get("/assistants", async ({ locals }) => { const settings = await collections.settings.findOne(authCondition(locals)); if (!settings) { return []; } const userAssistants = settings?.assistants?.map((assistantId) => assistantId.toString()) ?? []; const assistants = await collections.assistants .find({ _id: { $in: [...userAssistants.map((el) => new ObjectId(el))], }, }) .toArray(); return assistants.map((el) => ({ ...el, _id: el._id.toString(), createdById: undefined, createdByMe: el.createdById.toString() === (locals.user?._id ?? locals.sessionId).toString(), })); }); });
chat-ui/src/lib/server/api/routes/groups/user.ts/0
{ "file_path": "chat-ui/src/lib/server/api/routes/groups/user.ts", "repo_id": "chat-ui", "token_count": 2538 }
83
import { z } from "zod"; import { config } from "$lib/server/config"; import type { Endpoint } from "../endpoints"; import type { TextGenerationStreamOutput } from "@huggingface/inference"; import type { Cohere, CohereClient } from "cohere-ai"; import { buildPrompt } from "$lib/buildPrompt"; import { ToolResultStatus, type ToolCall } from "$lib/types/Tool"; import { pipeline, Writable, type Readable } from "node:stream"; import { toolHasName } from "$lib/utils/tools"; export const endpointCohereParametersSchema = z.object({ weight: z.number().int().positive().default(1), model: z.any(), type: z.literal("cohere"), apiKey: z.string().default(config.COHERE_API_TOKEN), clientName: z.string().optional(), raw: z.boolean().default(false), forceSingleStep: z.boolean().default(true), }); export async function endpointCohere( input: z.input<typeof endpointCohereParametersSchema> ): Promise<Endpoint> { const { apiKey, clientName, model, raw, forceSingleStep } = endpointCohereParametersSchema.parse(input); let cohere: CohereClient; try { cohere = new (await import("cohere-ai")).CohereClient({ token: apiKey, clientName, }); } catch (e) { throw new Error("Failed to import cohere-ai", { cause: e }); } return async ({ messages, preprompt, generateSettings, continueMessage, tools, toolResults }) => { let system = preprompt; if (messages?.[0]?.from === "system") { system = messages[0].content; } // Tools must use [A-z_] for their names and directly_answer is banned // It's safe to convert the tool names because we treat - and _ the same tools = tools ?.filter((tool) => !toolHasName("directly_answer", tool)) .map((tool) => ({ ...tool, name: tool.name.replaceAll("-", "_") })); const parameters = { ...model.parameters, ...generateSettings }; return (async function* () { let stream; let tokenId = 0; if (raw) { const prompt = await buildPrompt({ messages, model, preprompt: system, continueMessage, tools, toolResults, }); stream = await cohere.chatStream({ forceSingleStep, message: prompt, rawPrompting: true, model: model.id ?? model.name, p: parameters?.top_p, k: parameters?.top_k, maxTokens: parameters?.max_new_tokens, temperature: parameters?.temperature, stopSequences: parameters?.stop, frequencyPenalty: parameters?.frequency_penalty, }); } else { const formattedMessages = messages .filter((message) => message.from !== "system") .map((message) => ({ role: message.from === "user" ? "USER" : "CHATBOT", message: message.content, })) satisfies Cohere.Message[]; stream = await cohere .chatStream({ forceSingleStep, model: model.id ?? model.name, chatHistory: formattedMessages.slice(0, -1), message: formattedMessages[formattedMessages.length - 1].message, preamble: system, p: parameters?.top_p, k: parameters?.top_k, maxTokens: parameters?.max_new_tokens, temperature: parameters?.temperature, stopSequences: parameters?.stop, frequencyPenalty: parameters?.frequency_penalty, tools, toolResults: toolResults?.length && toolResults?.length > 0 ? toolResults?.map((toolResult) => { if (toolResult.status === ToolResultStatus.Error) { return { call: toolResult.call, outputs: [{ error: toolResult.message }] }; } return { call: toolResult.call, outputs: toolResult.outputs }; }) : undefined, }) .catch(async (err) => { if (!err.body) throw err; // Decode the error message and throw const message = await convertStreamToBuffer(err.body).catch(() => { throw err; }); throw Error(message, { cause: err }); }); } for await (const output of stream) { if (output.eventType === "text-generation") { yield { token: { id: tokenId++, text: output.text, logprob: 0, special: false, }, generated_text: null, details: null, } satisfies TextGenerationStreamOutput; } else if (output.eventType === "tool-calls-generation") { yield { token: { id: tokenId++, text: "", logprob: 0, special: true, toolCalls: output.toolCalls as ToolCall[], }, generated_text: null, details: null, }; } else if (output.eventType === "stream-end") { if (["ERROR", "ERROR_TOXIC", "ERROR_LIMIT"].includes(output.finishReason)) { throw new Error(output.finishReason); } yield { token: { id: tokenId++, text: "", logprob: 0, special: true, }, generated_text: output.response.text, details: null, }; } } })(); }; } async function convertStreamToBuffer(webReadableStream: Readable) { return new Promise<string>((resolve, reject) => { const chunks: Buffer[] = []; pipeline( webReadableStream, new Writable({ write(chunk, _, callback) { chunks.push(chunk); callback(); }, }), (err) => { if (err) { reject(err); } else { resolve(Buffer.concat(chunks).toString("utf-8")); } } ); }); }
chat-ui/src/lib/server/endpoints/cohere/endpointCohere.ts/0
{ "file_path": "chat-ui/src/lib/server/endpoints/cohere/endpointCohere.ts", "repo_id": "chat-ui", "token_count": 2220 }
84
import { randomUUID } from "$lib/utils/randomUuid"; import { timeout } from "$lib/utils/timeout"; import { logger } from "./logger"; type ExitHandler = () => void | Promise<void>; type ExitHandlerUnsubscribe = () => void; const listeners = new Map<string, ExitHandler>(); export function onExit(cb: ExitHandler): ExitHandlerUnsubscribe { const uuid = randomUUID(); listeners.set(uuid, cb); return () => { listeners.delete(uuid); }; } async function runExitHandler(handler: ExitHandler): Promise<void> { return timeout(Promise.resolve().then(handler), 30_000).catch((err) => { logger.error(err, "Exit handler failed to run"); }); } export function initExitHandler() { let signalCount = 0; const exitHandler = async () => { if (signalCount === 1) { logger.info("Received signal... Exiting"); await Promise.all(Array.from(listeners.values()).map(runExitHandler)); logger.info("All exit handlers ran... Waiting for svelte server to exit"); } }; process.on("SIGINT", () => { signalCount++; if (signalCount >= 2) { process.kill(process.pid, "SIGKILL"); } else { exitHandler().catch((err) => { logger.error("Exit handler error:", err); process.kill(process.pid, "SIGKILL"); }); } }); process.on("SIGTERM", () => { signalCount++; if (signalCount >= 2) { process.kill(process.pid, "SIGKILL"); } else { exitHandler().catch((err) => { logger.error("Exit handler error:", err); process.kill(process.pid, "SIGKILL"); }); } }); }
chat-ui/src/lib/server/exitHandler.ts/0
{ "file_path": "chat-ui/src/lib/server/exitHandler.ts", "repo_id": "chat-ui", "token_count": 559 }
85
import pino from "pino"; import { dev } from "$app/environment"; import { config } from "$lib/server/config"; let options: pino.LoggerOptions = {}; if (dev) { options = { transport: { target: "pino-pretty", options: { colorize: true, }, }, }; } export const logger = pino({ ...options, level: config.LOG_LEVEL || "info" });
chat-ui/src/lib/server/logger.ts/0
{ "file_path": "chat-ui/src/lib/server/logger.ts", "repo_id": "chat-ui", "token_count": 134 }
86