text
stringlengths
5
631k
id
stringlengths
14
178
metadata
dict
__index_level_0__
int64
0
647
# Copyright 2023 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 unittest from transformers import ( MODEL_FOR_IMAGE_TO_IMAGE_MAPPING, AutoImageProcessor, AutoModelForImageToImage, ImageToImagePipeline, is_vision_available, pipeline, ) from transformers.testing_utils import ( is_pipeline_test, require_torch, require_vision, slow, ) if is_vision_available(): from PIL import Image else: class Image: @staticmethod def open(*args, **kwargs): pass @is_pipeline_test @require_torch @require_vision class ImageToImagePipelineTests(unittest.TestCase): model_mapping = MODEL_FOR_IMAGE_TO_IMAGE_MAPPING examples = [ Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"), "http://images.cocodataset.org/val2017/000000039769.jpg", ] @require_torch @require_vision @slow def test_pipeline(self, dtype="float32"): model_id = "caidas/swin2SR-classical-sr-x2-64" upscaler = pipeline("image-to-image", model=model_id, dtype=dtype) upscaled_list = upscaler(self.examples) self.assertEqual(len(upscaled_list), len(self.examples)) for output in upscaled_list: self.assertIsInstance(output, Image.Image) self.assertEqual(upscaled_list[0].size, (1296, 976)) self.assertEqual(upscaled_list[1].size, (1296, 976)) @require_torch @require_vision @slow def test_pipeline_fp16(self): self.test_pipeline(dtype="float16") @require_torch @require_vision @slow def test_pipeline_model_processor(self): model_id = "caidas/swin2SR-classical-sr-x2-64" model = AutoModelForImageToImage.from_pretrained(model_id) image_processor = AutoImageProcessor.from_pretrained(model_id) upscaler = ImageToImagePipeline(model=model, image_processor=image_processor) upscaled_list = upscaler(self.examples) self.assertEqual(len(upscaled_list), len(self.examples)) for output in upscaled_list: self.assertIsInstance(output, Image.Image) self.assertEqual(upscaled_list[0].size, (1296, 976)) self.assertEqual(upscaled_list[1].size, (1296, 976))
transformers/tests/pipelines/test_pipelines_image_to_image.py/0
{ "file_path": "transformers/tests/pipelines/test_pipelines_image_to_image.py", "repo_id": "transformers", "token_count": 1131 }
603
# Copyright 2023 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 unittest from datasets import load_dataset from transformers.pipelines import pipeline from transformers.testing_utils import is_pipeline_test, nested_simplify, require_torch, slow @is_pipeline_test @require_torch class ZeroShotAudioClassificationPipelineTests(unittest.TestCase): # Deactivating auto tests since we don't have a good MODEL_FOR_XX mapping, # and only CLAP would be there for now. # model_mapping = {CLAPConfig: CLAPModel} @require_torch def test_small_model_pt(self, dtype="float32"): audio_classifier = pipeline( task="zero-shot-audio-classification", model="hf-internal-testing/tiny-clap-htsat-unfused", dtype=dtype, ) dataset = load_dataset("hf-internal-testing/ashraq-esc50-1-dog-example") audio = dataset["train"]["audio"][-1]["array"] output = audio_classifier(audio, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"]) self.assertEqual( nested_simplify(output), [{"score": 0.501, "label": "Sound of a dog"}, {"score": 0.499, "label": "Sound of vaccum cleaner"}], ) @require_torch def test_small_model_pt_fp16(self): self.test_small_model_pt(dtype="float16") @unittest.skip(reason="No models are available in TF") def test_small_model_tf(self): pass @slow @require_torch def test_large_model_pt(self): audio_classifier = pipeline( task="zero-shot-audio-classification", model="laion/clap-htsat-unfused", ) # This is an audio of a dog dataset = load_dataset("hf-internal-testing/ashraq-esc50-1-dog-example") audio = dataset["train"]["audio"][-1]["array"] output = audio_classifier(audio, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"]) self.assertEqual( nested_simplify(output), [ {"score": 1.0, "label": "Sound of a dog"}, {"score": 0.0, "label": "Sound of vaccum cleaner"}, ], ) output = audio_classifier([audio] * 5, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"]) self.assertEqual( nested_simplify(output), [ [ {"score": 1.0, "label": "Sound of a dog"}, {"score": 0.0, "label": "Sound of vaccum cleaner"}, ], ] * 5, ) output = audio_classifier( [audio] * 5, candidate_labels=["Sound of a dog", "Sound of vaccum cleaner"], batch_size=5 ) self.assertEqual( nested_simplify(output), [ [ {"score": 1.0, "label": "Sound of a dog"}, {"score": 0.0, "label": "Sound of vaccum cleaner"}, ], ] * 5, ) @unittest.skip(reason="No models are available in TF") def test_large_model_tf(self): pass
transformers/tests/pipelines/test_pipelines_zero_shot_audio_classification.py/0
{ "file_path": "transformers/tests/pipelines/test_pipelines_zero_shot_audio_classification.py", "repo_id": "transformers", "token_count": 1600 }
604
import gc import unittest import warnings from transformers import AutoModelForCausalLM, AutoTokenizer from transformers.testing_utils import backend_empty_cache, require_compressed_tensors, require_torch, torch_device from transformers.utils import is_torch_available from transformers.utils.quantization_config import CompressedTensorsConfig if is_torch_available(): import torch @require_compressed_tensors @require_torch class StackCompressedModelTest(unittest.TestCase): # Define stubs as class attributes compressed_uncompressed_model_stubs = [ ( "nm-testing/llama2.c-stories42M-gsm8k-quantized-only-compressed", "nm-testing/llama2.c-stories42M-gsm8k-quantized-only-uncompressed", ), ( "nm-testing/llama2.c-stories42M-gsm8k-sparse-only-compressed", "nm-testing/llama2.c-stories42M-gsm8k-sparse-only-uncompressed", ), ( "nm-testing/llama2.c-stories42M-gsm8k-stacked-compressed", "nm-testing/llama2.c-stories42M-gsm8k-stacked-uncompressed", ), ] # Flatten the list for tests that require a single list of stubs. model_stubs = [stub for pair in compressed_uncompressed_model_stubs for stub in pair] # For the outputs matching test, use the sparse-only pair. sparse_compressed_model = "nm-testing/llama2.c-stories42M-gsm8k-sparse-only-compressed" sparse_uncompressed_model = "nm-testing/llama2.c-stories42M-gsm8k-sparse-only-uncompressed" prompt = "Paris is the capital of which country?" def tearDown(self): gc.collect() backend_empty_cache(torch_device) gc.collect() def test_compressed_uncompressed_model_shapes(self): """ Verify that the weights of an uncompressed model and its decompressed compressed counterpart match. Note: Weights for sparsely compressed models may differ due to packing. """ def _has_nested_attr(obj, attr_path): attrs = attr_path.split(".") for attr in attrs: if not hasattr(obj, attr): return None obj = getattr(obj, attr) return obj from compressed_tensors.quantization.utils import iter_named_leaf_modules for compressed_model, uncompressed_model in self.compressed_uncompressed_model_stubs: with self.subTest(compressed_model=compressed_model, uncompressed_model=uncompressed_model): uncompressed = AutoModelForCausalLM.from_pretrained( uncompressed_model, device_map="auto", dtype="auto", quantization_config=CompressedTensorsConfig(run_compressed=False), ) compressed_decompressed = AutoModelForCausalLM.from_pretrained( compressed_model, device_map="auto", dtype="auto", quantization_config=CompressedTensorsConfig(run_compressed=False), ) for name, submodule in iter_named_leaf_modules(uncompressed): comp_decomp_obj = _has_nested_attr(compressed_decompressed, name) if comp_decomp_obj is not None and hasattr(submodule, "weight"): if "sparse-only" in uncompressed_model: self.assertTrue( torch.equal(submodule.weight, comp_decomp_obj.weight), f"Weight mismatch for module '{name}' in sparse-only model.", ) else: self.assertTrue( torch.allclose(submodule.weight, comp_decomp_obj.weight, atol=0.2), f"Weight mismatch for module '{name}' in quantized-only or stacked model.", ) def test_outputs_match(self): """ Ensure that the generated outputs match between the uncompressed model and its decompressed compressed counterpart. """ tokenizer = AutoTokenizer.from_pretrained(self.sparse_uncompressed_model) input_ids = tokenizer(self.prompt, return_tensors="pt").input_ids uncompressed = AutoModelForCausalLM.from_pretrained( self.sparse_uncompressed_model, device_map="auto", dtype="auto", quantization_config=CompressedTensorsConfig(run_compressed=False), ) output_uncompressed = uncompressed.generate(input_ids.to(uncompressed.device), max_new_tokens=100) decompressed = AutoModelForCausalLM.from_pretrained( self.sparse_compressed_model, device_map="auto", dtype="auto", quantization_config=CompressedTensorsConfig(run_compressed=False), ) output_decompressed = decompressed.generate(input_ids.to(decompressed.device), max_new_tokens=100) self.assertEqual( tokenizer.decode(output_uncompressed[0]), tokenizer.decode(output_decompressed[0]), "Generated outputs do not match between compressed and uncompressed models.", ) def test_no_warnings_for_all_models(self): """ Confirm that loading any model using compressed tensors does not trigger warnings about missing or unexpected keys. """ for model_stub in self.model_stubs: with self.subTest(model_stub=model_stub): with warnings.catch_warnings(record=True) as caught_warnings: warnings.simplefilter("always") AutoModelForCausalLM.from_pretrained( model_stub, device_map="auto", dtype="auto", quantization_config=CompressedTensorsConfig(run_compressed=False), ) for warning in caught_warnings: self.assertNotIn( "missing keys", str(warning.message).lower(), f"'missing keys' found in warnings for model {model_stub}", ) self.assertNotIn( "unexpected keys", str(warning.message).lower(), f"'unexpected keys' found in warnings for model {model_stub}", ) @require_compressed_tensors @require_torch class RunCompressedTest(unittest.TestCase): tinyllama_w4a16 = "nm-testing/tinyllama-w4a16-compressed-hf-quantizer" tinyllama_w8a8 = "nm-testing/tinyllama-w8a8-compressed-hf-quantizer" prompt = "Paris is the capital of which country?" stubs = [tinyllama_w4a16, tinyllama_w8a8] def tearDown(self): gc.collect() backend_empty_cache(torch_device) gc.collect() def test_default_run_compressed__True(self): from compressed_tensors.linear.compressed_linear import CompressedLinear from compressed_tensors.quantization.utils import iter_named_leaf_modules for stub in self.stubs: model = AutoModelForCausalLM.from_pretrained( stub, ) compressed_linear_counts = 0 for _, submodule in iter_named_leaf_modules( model, ): if isinstance(submodule, CompressedLinear): compressed_linear_counts += 1 # some linear models are not compressed - ex. lm_head assert compressed_linear_counts > 0 def test_default_run_compressed__False(self): from compressed_tensors.linear.compressed_linear import CompressedLinear from compressed_tensors.quantization.utils import iter_named_leaf_modules from transformers.utils.quantization_config import CompressedTensorsConfig quantization_config = CompressedTensorsConfig(run_compressed=False) for stub in self.stubs: model = AutoModelForCausalLM.from_pretrained( stub, quantization_config=quantization_config, ) compressed_linear_counts = 0 for _, submodule in iter_named_leaf_modules( model, ): if isinstance(submodule, CompressedLinear): compressed_linear_counts += 1 # No modules should be CompressedLinear assert compressed_linear_counts == 0 def test_run_compressed_outputs_match(self): """Check that run_compressed=True/False output are the same""" from transformers import AutoTokenizer from transformers.utils.quantization_config import CompressedTensorsConfig quantization_config = CompressedTensorsConfig(run_compressed=False) for stub in self.stubs: tokenizer = AutoTokenizer.from_pretrained(stub) input_ids = tokenizer(self.prompt, return_tensors="pt").input_ids model_run_compressed__True = AutoModelForCausalLM.from_pretrained( stub, ) output_rc_true = model_run_compressed__True.generate(input_ids, max_new_tokens=100) model_run_compressed__False = AutoModelForCausalLM.from_pretrained( stub, quantization_config=quantization_config, ) output_rc_false = model_run_compressed__False.generate(input_ids, max_new_tokens=100) assert tokenizer.decode(output_rc_true[0]) == tokenizer.decode(output_rc_false[0])
transformers/tests/quantization/compressed_tensors_integration/test_compressed_models.py/0
{ "file_path": "transformers/tests/quantization/compressed_tensors_integration/test_compressed_models.py", "repo_id": "transformers", "token_count": 4545 }
605
# Copyright 2024 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 unittest import accelerate from transformers import AutoModelForCausalLM, AutoTokenizer, HqqConfig from transformers.testing_utils import ( backend_empty_cache, require_accelerate, require_deterministic_for_xpu, require_hqq, require_torch_accelerator, require_torch_multi_accelerator, slow, torch_device, ) from transformers.utils import is_hqq_available, is_torch_available if is_torch_available(): import torch if is_hqq_available(): from hqq.core.quantize import HQQBackend, HQQLinear class HQQLLMRunner: def __init__(self, model_id, quant_config, compute_dtype, device, cache_dir=None): self.model = AutoModelForCausalLM.from_pretrained( model_id, dtype=compute_dtype, device_map=device, quantization_config=quant_config, cache_dir=cache_dir, ) self.tokenizer = AutoTokenizer.from_pretrained(model_id, cache_dir=cache_dir) self.device = self.model.device HQQLinear.set_backend(HQQBackend.PYTORCH) def cleanup(): backend_empty_cache(torch_device) gc.collect() def check_hqqlayer(test_module, hqq_layer, batch_size=1, context_size=1024): # Test HQQ layer W_dequant = hqq_layer.dequantize() # Reconstructed weights inputs = ( torch.randn( (batch_size, context_size, hqq_layer.meta["shape"][1]), device=hqq_layer.device, dtype=hqq_layer.compute_dtype, ) / 10.0 ) with torch.no_grad(): outputs = hqq_layer(inputs) test_module.assertEqual(outputs.shape[-1], W_dequant.shape[0]) test_module.assertEqual(outputs.dtype, hqq_layer.compute_dtype) del W_dequant, inputs, outputs cleanup() def check_forward(test_module, model, batch_size=1, context_size=1024): # Test forward pass with torch.no_grad(): out = model(torch.zeros([batch_size, context_size], device=model.device, dtype=torch.int32)).logits test_module.assertEqual(out.shape[0], batch_size) test_module.assertEqual(out.shape[1], context_size) cleanup() MODEL_ID = "TinyLlama/TinyLlama-1.1B-Chat-v1.0" @require_torch_accelerator @require_hqq class HqqConfigTest(unittest.TestCase): def test_to_dict(self): """ Makes sure the config format is properly set """ quantization_config = HqqConfig() hqq_orig_config = quantization_config.to_dict() self.assertEqual(quantization_config.quant_config, hqq_orig_config["quant_config"]) @slow @require_torch_accelerator @require_accelerate @require_hqq class HQQTest(unittest.TestCase): def tearDown(self): cleanup() def test_fp16_quantized_model(self): """ Simple LLM model testing fp16 """ quant_config = HqqConfig(nbits=8, group_size=64) hqq_runner = HQQLLMRunner( model_id=MODEL_ID, quant_config=quant_config, compute_dtype=torch.float16, device=torch_device ) check_hqqlayer(self, hqq_runner.model.model.layers[0].self_attn.v_proj) check_forward(self, hqq_runner.model) def test_quantized_model_to_new_device_and_new_dtype(self): """ Simple LLM model testing different devices and dtypes """ quant_config = HqqConfig(nbits=8, group_size=64) hqq_runner = HQQLLMRunner( model_id=MODEL_ID, quant_config=quant_config, compute_dtype=torch.float16, device=torch_device ) check_hqqlayer(self, hqq_runner.model.model.layers[0].self_attn.v_proj) check_forward(self, hqq_runner.model) # Remove `accelerate` hooks to enable move the model to a new device accelerate.hooks.remove_hook_from_module(hqq_runner.model, recurse=True) hqq_runner.model.to("cpu", torch.bfloat16) check_hqqlayer(self, hqq_runner.model.model.layers[0].self_attn.v_proj) check_forward(self, hqq_runner.model) hqq_runner.model.to(torch_device) check_hqqlayer(self, hqq_runner.model.model.layers[0].self_attn.v_proj) check_forward(self, hqq_runner.model) def test_quantized_model_fake_weight_dtype(self): quant_config = HqqConfig(nbits=8, group_size=64) hqq_runner = HQQLLMRunner( model_id=MODEL_ID, quant_config=quant_config, compute_dtype=torch.float16, device=torch_device ) # We use a hack to inject a fake weight to HQQLinear. Check that it works self.assertEqual(hqq_runner.model.model.layers[0].self_attn.v_proj.weight.dtype, torch.float16) @slow @require_torch_accelerator @require_torch_multi_accelerator @require_accelerate @require_hqq class HQQTestMultiGPU(unittest.TestCase): def tearDown(self): cleanup() def test_fp16_quantized_model_multipgpu(self): """ Simple LLM model testing fp16 with multi-gpu """ quant_config = HqqConfig(nbits=8, group_size=64) hqq_runner = HQQLLMRunner( model_id=MODEL_ID, quant_config=quant_config, compute_dtype=torch.float16, device="auto" ) check_hqqlayer(self, hqq_runner.model.model.layers[0].self_attn.v_proj) check_forward(self, hqq_runner.model) @slow @require_torch_accelerator @require_accelerate @require_hqq class HQQTestBias(unittest.TestCase): def tearDown(self): cleanup() def test_fp16_quantized_model(self): """ Simple LLM model testing fp16 with bias """ quant_config = HqqConfig(nbits=8, group_size=64) hqq_runner = HQQLLMRunner( model_id="facebook/opt-125m", quant_config=quant_config, compute_dtype=torch.float16, device=torch_device ) check_hqqlayer(self, hqq_runner.model.model.decoder.layers[0].self_attn.v_proj) check_forward(self, hqq_runner.model) @require_deterministic_for_xpu def test_save_and_load_quantized_model(self): """ Test saving and loading a quantized model with bias """ import tempfile quant_config = HqqConfig(nbits=8, group_size=64) hqq_runner = HQQLLMRunner( model_id="facebook/opt-125m", quant_config=quant_config, compute_dtype=torch.float16, device=torch_device ) input_tensor = torch.zeros((1, 8), dtype=torch.int32, device=torch_device) # Get reference logits with torch.no_grad(): logits_ref = hqq_runner.model.forward(input_tensor).logits with tempfile.TemporaryDirectory() as tmpdirname: hqq_runner.model.save_pretrained(tmpdirname) del hqq_runner.model backend_empty_cache(torch_device) model_loaded = AutoModelForCausalLM.from_pretrained( tmpdirname, dtype=torch.float16, device_map=torch_device ) with torch.no_grad(): logits_loaded = model_loaded.forward(input_tensor).logits self.assertEqual((logits_loaded - logits_ref).abs().mean().item(), 0) @slow @require_torch_accelerator @require_accelerate @require_hqq class HQQSerializationTest(unittest.TestCase): def tearDown(self): cleanup() def test_model_serialization(self): """ Simple HQQ LLM save/load test """ quant_config = HqqConfig(nbits=4, group_size=64) hqq_runner = HQQLLMRunner( model_id=MODEL_ID, quant_config=quant_config, compute_dtype=torch.float16, device=torch_device ) input_tensor = torch.zeros((1, 8), dtype=torch.int32, device=torch_device) with torch.no_grad(): logits_ref = hqq_runner.model.forward(input_tensor).logits # Save saved_model_id = "quant_model" hqq_runner.model.save_pretrained(saved_model_id) # Remove old model del hqq_runner.model backend_empty_cache(torch_device) # Load and check if the logits match model_loaded = AutoModelForCausalLM.from_pretrained( "quant_model", dtype=torch.float16, device_map=torch_device, ) with torch.no_grad(): logits_loaded = model_loaded.forward(input_tensor).logits self.assertEqual((logits_loaded - logits_ref).abs().mean().item(), 0) def test_model_serialization_dynamic_quant_with_skip(self): """ Simple HQQ LLM save/load test with dynamic quant """ q4_config = {"nbits": 4, "group_size": 64} q3_config = {"nbits": 3, "group_size": 64} quant_config = HqqConfig( dynamic_config={ "self_attn.q_proj": q4_config, "self_attn.k_proj": q4_config, "self_attn.v_proj": q4_config, "self_attn.o_proj": q4_config, "mlp.gate_proj": q3_config, "mlp.up_proj": q3_config, }, skip_modules=["lm_head", "down_proj"], ) hqq_runner = HQQLLMRunner( model_id=MODEL_ID, quant_config=quant_config, compute_dtype=torch.float16, device=torch_device ) model = hqq_runner.model input_tensor = torch.zeros((1, 8), dtype=torch.int32, device=torch_device) with torch.no_grad(): model.forward(input_tensor).logits self.assertEqual(isinstance(model.model.layers[1].mlp.down_proj, torch.nn.Linear), True) self.assertEqual(model.model.layers[1].self_attn.v_proj.quant_config["weight_quant_params"]["nbits"], 4) self.assertEqual(model.model.layers[1].mlp.gate_proj.quant_config["weight_quant_params"]["nbits"], 3)
transformers/tests/quantization/hqq/test_hqq.py/0
{ "file_path": "transformers/tests/quantization/hqq/test_hqq.py", "repo_id": "transformers", "token_count": 4574 }
606
# Copyright 2023 The HuggingFace Inc. team. # # 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 os import sys import unittest git_repo_path = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, "utils")) import get_test_info # noqa: E402 from get_test_info import ( # noqa: E402 get_model_to_test_mapping, get_model_to_tester_mapping, get_test_to_tester_mapping, ) BERT_TEST_FILE = os.path.join("tests", "models", "bert", "test_modeling_bert.py") BLIP_TEST_FILE = os.path.join("tests", "models", "blip", "test_modeling_blip.py") class GetTestInfoTester(unittest.TestCase): def test_get_test_to_tester_mapping(self): bert_test_tester_mapping = get_test_to_tester_mapping(BERT_TEST_FILE) blip_test_tester_mapping = get_test_to_tester_mapping(BLIP_TEST_FILE) EXPECTED_BERT_MAPPING = {"BertModelTest": "BertModelTester"} EXPECTED_BLIP_MAPPING = { "BlipModelTest": "BlipModelTester", "BlipTextImageModelTest": "BlipTextImageModelsModelTester", "BlipTextModelTest": "BlipTextModelTester", "BlipTextRetrievalModelTest": "BlipTextRetrievalModelTester", "BlipVQAModelTest": "BlipVQAModelTester", "BlipVisionModelTest": "BlipVisionModelTester", } self.assertEqual(get_test_info.to_json(bert_test_tester_mapping), EXPECTED_BERT_MAPPING) self.assertEqual(get_test_info.to_json(blip_test_tester_mapping), EXPECTED_BLIP_MAPPING) def test_get_model_to_test_mapping(self): bert_model_test_mapping = get_model_to_test_mapping(BERT_TEST_FILE) blip_model_test_mapping = get_model_to_test_mapping(BLIP_TEST_FILE) EXPECTED_BERT_MAPPING = { "BertForMaskedLM": ["BertModelTest"], "BertForMultipleChoice": ["BertModelTest"], "BertForNextSentencePrediction": ["BertModelTest"], "BertForPreTraining": ["BertModelTest"], "BertForQuestionAnswering": ["BertModelTest"], "BertForSequenceClassification": ["BertModelTest"], "BertForTokenClassification": ["BertModelTest"], "BertLMHeadModel": ["BertModelTest"], "BertModel": ["BertModelTest"], } EXPECTED_BLIP_MAPPING = { "BlipForConditionalGeneration": ["BlipTextImageModelTest"], "BlipForImageTextRetrieval": ["BlipTextRetrievalModelTest"], "BlipForQuestionAnswering": ["BlipVQAModelTest"], "BlipModel": ["BlipModelTest"], "BlipTextModel": ["BlipTextModelTest"], "BlipVisionModel": ["BlipVisionModelTest"], } self.assertEqual(get_test_info.to_json(bert_model_test_mapping), EXPECTED_BERT_MAPPING) self.assertEqual(get_test_info.to_json(blip_model_test_mapping), EXPECTED_BLIP_MAPPING) def test_get_model_to_tester_mapping(self): bert_model_tester_mapping = get_model_to_tester_mapping(BERT_TEST_FILE) blip_model_tester_mapping = get_model_to_tester_mapping(BLIP_TEST_FILE) EXPECTED_BERT_MAPPING = { "BertForMaskedLM": ["BertModelTester"], "BertForMultipleChoice": ["BertModelTester"], "BertForNextSentencePrediction": ["BertModelTester"], "BertForPreTraining": ["BertModelTester"], "BertForQuestionAnswering": ["BertModelTester"], "BertForSequenceClassification": ["BertModelTester"], "BertForTokenClassification": ["BertModelTester"], "BertLMHeadModel": ["BertModelTester"], "BertModel": ["BertModelTester"], } EXPECTED_BLIP_MAPPING = { "BlipForConditionalGeneration": ["BlipTextImageModelsModelTester"], "BlipForImageTextRetrieval": ["BlipTextRetrievalModelTester"], "BlipForQuestionAnswering": ["BlipVQAModelTester"], "BlipModel": ["BlipModelTester"], "BlipTextModel": ["BlipTextModelTester"], "BlipVisionModel": ["BlipVisionModelTester"], } self.assertEqual(get_test_info.to_json(bert_model_tester_mapping), EXPECTED_BERT_MAPPING) self.assertEqual(get_test_info.to_json(blip_model_tester_mapping), EXPECTED_BLIP_MAPPING)
transformers/tests/repo_utils/test_get_test_info.py/0
{ "file_path": "transformers/tests/repo_utils/test_get_test_info.py", "repo_id": "transformers", "token_count": 2124 }
607
# Copyright 2025 HuggingFace Inc. # # 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 unittest import torch from transformers import AutoModelForCausalLM, set_seed from transformers.generation.configuration_utils import GenerationConfig from transformers.integrations.executorch import ( TorchExportableModuleForDecoderOnlyLM, TorchExportableModuleWithHybridCache, TorchExportableModuleWithStaticCache, ) from transformers.pytorch_utils import is_torch_greater_or_equal_than_2_3 from transformers.testing_utils import require_torch @require_torch class ExecutorchTest(unittest.TestCase): def setUp(self): if not is_torch_greater_or_equal_than_2_3: self.skipTest("torch >= 2.3 is required") set_seed(0) self.model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-LlamaForCausalLM") self.model.eval() # Create generation config with static cache for the model self.model.generation_config = GenerationConfig( use_cache=True, cache_implementation="static", cache_config={"batch_size": 1, "max_cache_len": 32, "device": "cpu"}, ) self.input_ids = torch.tensor([[1, 2, 3]], dtype=torch.long) self.inputs_embeds = torch.randn(1, 3, self.model.config.hidden_size) self.cache_position = torch.arange(3, dtype=torch.long) def test_static_cache_module_forward(self): """Test TorchExportableModuleWithStaticCache forward with both input types""" generation_config = GenerationConfig( use_cache=True, cache_implementation="static", cache_config={"batch_size": 1, "max_cache_len": 32, "device": "cpu"}, ) # Set generation config on model self.model.generation_config = generation_config module = TorchExportableModuleWithStaticCache(self.model) # Test with input_ids eager_output_ids = self.model(input_ids=self.input_ids, use_cache=False).logits wrapped_output_ids = module.forward(input_ids=self.input_ids, cache_position=self.cache_position) torch.testing.assert_close(eager_output_ids, wrapped_output_ids, atol=1e-4, rtol=1e-4) # Test with inputs_embeds eager_output_embeds = self.model(inputs_embeds=self.inputs_embeds, use_cache=False).logits wrapped_output_embeds = module.forward(inputs_embeds=self.inputs_embeds, cache_position=self.cache_position) torch.testing.assert_close(eager_output_embeds, wrapped_output_embeds, atol=1e-4, rtol=1e-4) def test_hybrid_cache_module_forward(self): """Test TorchExportableModuleWithHybridCache forward with both input types""" config = self.model.config config.sliding_window = 16 config.layer_types = ["full_attention"] * config.num_hidden_layers generation_config = GenerationConfig( use_cache=True, cache_implementation="hybrid", cache_config={"batch_size": 1, "max_cache_len": 32, "device": "cpu"}, ) # Set generation config on model self.model.generation_config = generation_config module = TorchExportableModuleWithHybridCache(self.model) # Test with input_ids eager_output_ids = self.model(input_ids=self.input_ids, use_cache=False).logits wrapped_output_ids = module.forward(input_ids=self.input_ids, cache_position=self.cache_position) torch.testing.assert_close(eager_output_ids, wrapped_output_ids, atol=1e-4, rtol=1e-4) # Test with inputs_embeds eager_output_embeds = self.model(inputs_embeds=self.inputs_embeds, use_cache=False).logits wrapped_output_embeds = module.forward(inputs_embeds=self.inputs_embeds, cache_position=self.cache_position) torch.testing.assert_close(eager_output_embeds, wrapped_output_embeds, atol=1e-4, rtol=1e-4) def test_decoder_only_lm_export_validation(self): """Test TorchExportableModuleForDecoderOnlyLM export validation""" module = TorchExportableModuleForDecoderOnlyLM(self.model) # Should fail with both input_ids and inputs_embeds with self.assertRaises(ValueError): module.export(input_ids=self.input_ids, inputs_embeds=self.inputs_embeds) # Should fail with neither with self.assertRaises(ValueError): module.export() def test_decoder_only_lm_export(self): """Test TorchExportableModuleForDecoderOnlyLM export with both input types""" module = TorchExportableModuleForDecoderOnlyLM(self.model) # Test export with input_ids exported_program_ids = module.export(input_ids=self.input_ids, cache_position=self.cache_position) eager_output_ids = self.model(input_ids=self.input_ids, use_cache=False).logits exported_output_ids = exported_program_ids.module()( input_ids=self.input_ids, cache_position=self.cache_position ) torch.testing.assert_close(eager_output_ids, exported_output_ids, atol=1e-4, rtol=1e-4) # Test export with inputs_embeds exported_program_embeds = module.export(inputs_embeds=self.inputs_embeds, cache_position=self.cache_position) eager_output_embeds = self.model(inputs_embeds=self.inputs_embeds, use_cache=False).logits exported_output_embeds = exported_program_embeds.module()( inputs_embeds=self.inputs_embeds, cache_position=self.cache_position ) torch.testing.assert_close(eager_output_embeds, exported_output_embeds, atol=1e-4, rtol=1e-4)
transformers/tests/test_executorch.py/0
{ "file_path": "transformers/tests/test_executorch.py", "repo_id": "transformers", "token_count": 2351 }
608
# Copyright 2020 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 os import shutil import tempfile import unittest import numpy as np from transformers import ( BertTokenizer, DataCollatorForLanguageModeling, DataCollatorForPermutationLanguageModeling, DataCollatorForSeq2Seq, DataCollatorForTokenClassification, DataCollatorForWholeWordMask, DataCollatorWithFlattening, DataCollatorWithPadding, default_data_collator, is_torch_available, set_seed, ) from transformers.testing_utils import require_torch from transformers.utils import PaddingStrategy if is_torch_available(): import torch @require_torch class DataCollatorIntegrationTest(unittest.TestCase): def setUp(self): self.tmpdirname = tempfile.mkdtemp() vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"] self.vocab_file = os.path.join(self.tmpdirname, "vocab.txt") with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) def tearDown(self): shutil.rmtree(self.tmpdirname) def test_default_with_dict(self): features = [{"label": i, "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)] batch = default_data_collator(features) self.assertTrue(batch["labels"].equal(torch.tensor(list(range(8))))) self.assertEqual(batch["labels"].dtype, torch.long) self.assertEqual(batch["inputs"].shape, torch.Size([8, 6])) # With label_ids features = [{"label_ids": [0, 1, 2], "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)] batch = default_data_collator(features) self.assertTrue(batch["labels"].equal(torch.tensor([[0, 1, 2]] * 8))) self.assertEqual(batch["labels"].dtype, torch.long) self.assertEqual(batch["inputs"].shape, torch.Size([8, 6])) # Features can already be tensors features = [{"label": i, "inputs": np.random.randint(0, 10, [10])} for i in range(8)] batch = default_data_collator(features) self.assertTrue(batch["labels"].equal(torch.tensor(list(range(8))))) self.assertEqual(batch["labels"].dtype, torch.long) self.assertEqual(batch["inputs"].shape, torch.Size([8, 10])) # Labels can already be tensors features = [{"label": torch.tensor(i), "inputs": np.random.randint(0, 10, [10])} for i in range(8)] batch = default_data_collator(features) self.assertEqual(batch["labels"].dtype, torch.long) self.assertTrue(batch["labels"].equal(torch.tensor(list(range(8))))) self.assertEqual(batch["labels"].dtype, torch.long) self.assertEqual(batch["inputs"].shape, torch.Size([8, 10])) def test_default_classification_and_regression(self): data_collator = default_data_collator features = [{"input_ids": [0, 1, 2, 3, 4], "label": i} for i in range(4)] batch = data_collator(features) self.assertEqual(batch["labels"].dtype, torch.long) features = [{"input_ids": [0, 1, 2, 3, 4], "label": float(i)} for i in range(4)] batch = data_collator(features) self.assertEqual(batch["labels"].dtype, torch.float) def test_default_with_no_labels(self): features = [{"label": None, "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)] batch = default_data_collator(features) self.assertTrue("labels" not in batch) self.assertEqual(batch["inputs"].shape, torch.Size([8, 6])) # With label_ids features = [{"label_ids": None, "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)] batch = default_data_collator(features) self.assertTrue("labels" not in batch) self.assertEqual(batch["inputs"].shape, torch.Size([8, 6])) def test_data_collator_with_padding(self): tokenizer = BertTokenizer(self.vocab_file) features = [{"input_ids": [0, 1, 2]}, {"input_ids": [0, 1, 2, 3, 4, 5]}] data_collator = DataCollatorWithPadding(tokenizer) batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, torch.Size([2, 6])) self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) data_collator = DataCollatorWithPadding(tokenizer, padding="max_length", max_length=10) batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, torch.Size([2, 10])) data_collator = DataCollatorWithPadding(tokenizer, pad_to_multiple_of=8) batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, torch.Size([2, 8])) def test_data_collator_with_flattening(self): features = [ {"input_ids": [10, 11, 12]}, {"input_ids": [20, 21, 22, 23, 24, 25]}, {"input_ids": [30, 31, 32, 33, 34, 35, 36]}, ] data_collator = DataCollatorWithFlattening(return_tensors="pt") batch = data_collator(features) for unexpected_key in [ "attention_mask", "cu_seq_lens_k", "cu_seq_lens_q", "max_length_k", "max_length_q", "seq_idx", ]: self.assertNotIn(unexpected_key, batch) self.assertIn("position_ids", batch) self.assertEqual(batch["input_ids"].shape, torch.Size([1, 16])) self.assertEqual( batch["input_ids"][0].tolist(), [10, 11, 12, 20, 21, 22, 23, 24, 25, 30, 31, 32, 33, 34, 35, 36] ) self.assertEqual(batch["position_ids"].shape, torch.Size([1, 16])) self.assertEqual(batch["position_ids"][0].tolist(), [0, 1, 2, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6]) def test_data_collator_with_flattening_flash_attn_kwargs(self): features = [ {"input_ids": [10, 11, 12]}, {"input_ids": [20, 21, 22, 23, 24, 25]}, {"input_ids": [30, 31, 32, 33, 34, 35, 36]}, ] data_collator = DataCollatorWithFlattening(return_tensors="pt", return_flash_attn_kwargs=True) batch = data_collator(features) for unexpected_key in [ "attention_mask", "seq_idx", ]: self.assertNotIn(unexpected_key, batch) for expected_key in [ "position_ids", "cu_seq_lens_k", "cu_seq_lens_q", "max_length_k", "max_length_q", ]: self.assertIn(expected_key, batch) self.assertEqual(batch["input_ids"].shape, torch.Size([1, 16])) self.assertEqual( batch["input_ids"][0].tolist(), [10, 11, 12, 20, 21, 22, 23, 24, 25, 30, 31, 32, 33, 34, 35, 36] ) self.assertEqual(batch["position_ids"].shape, torch.Size([1, 16])) self.assertEqual(batch["position_ids"][0].tolist(), [0, 1, 2, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6]) self.assertEqual(batch["cu_seq_lens_k"].shape, torch.Size([4])) self.assertEqual(batch["cu_seq_lens_k"].tolist(), [0, 3, 9, 16]) self.assertEqual(batch["cu_seq_lens_q"].shape, torch.Size([4])) self.assertEqual(batch["cu_seq_lens_q"].tolist(), [0, 3, 9, 16]) # The flash attn max_length_{k,q} are simple python ints self.assertEqual(batch["max_length_k"], 7) self.assertEqual(batch["max_length_q"], 7) def test_data_collator_with_flattening_seq_idx(self): features = [ {"input_ids": [10, 11, 12]}, {"input_ids": [20, 21, 22, 23, 24, 25]}, {"input_ids": [30, 31, 32, 33, 34, 35, 36]}, ] data_collator = DataCollatorWithFlattening(return_tensors="pt", return_seq_idx=True) batch = data_collator(features) for unexpected_key in [ "attention_mask", "cu_seq_lens_k", "cu_seq_lens_q", "max_length_k", "max_length_q", ]: self.assertNotIn(unexpected_key, batch) for expected_key in [ "position_ids", "seq_idx", ]: self.assertIn(expected_key, batch) self.assertEqual(batch["input_ids"].shape, torch.Size([1, 16])) self.assertEqual( batch["input_ids"][0].tolist(), [10, 11, 12, 20, 21, 22, 23, 24, 25, 30, 31, 32, 33, 34, 35, 36] ) self.assertEqual(batch["position_ids"].shape, torch.Size([1, 16])) self.assertEqual(batch["position_ids"][0].tolist(), [0, 1, 2, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6]) self.assertEqual(batch["seq_idx"].shape, batch["input_ids"].shape) self.assertEqual(batch["seq_idx"][0].tolist(), [0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]) def test_data_collator_for_token_classification(self): tokenizer = BertTokenizer(self.vocab_file) features = [ {"input_ids": [0, 1, 2], "labels": [0, 1, 2]}, {"input_ids": [0, 1, 2, 3, 4, 5], "labels": [0, 1, 2, 3, 4, 5]}, ] data_collator = DataCollatorForTokenClassification(tokenizer) batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, torch.Size([2, 6])) self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) self.assertEqual(batch["labels"].shape, torch.Size([2, 6])) self.assertEqual(batch["labels"][0].tolist(), [0, 1, 2] + [-100] * 3) data_collator = DataCollatorForTokenClassification(tokenizer, padding="max_length", max_length=10) batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, torch.Size([2, 10])) self.assertEqual(batch["labels"].shape, torch.Size([2, 10])) data_collator = DataCollatorForTokenClassification(tokenizer, pad_to_multiple_of=8) batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, torch.Size([2, 8])) self.assertEqual(batch["labels"].shape, torch.Size([2, 8])) data_collator = DataCollatorForTokenClassification(tokenizer, label_pad_token_id=-1) batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, torch.Size([2, 6])) self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) self.assertEqual(batch["labels"].shape, torch.Size([2, 6])) self.assertEqual(batch["labels"][0].tolist(), [0, 1, 2] + [-1] * 3) for feature in features: feature.pop("labels") batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, torch.Size([2, 6])) self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) def test_data_collator_for_token_classification_works_with_pt_tensors(self): tokenizer = BertTokenizer(self.vocab_file) features = [ {"input_ids": torch.tensor([0, 1, 2]), "labels": torch.tensor([0, 1, 2])}, {"input_ids": torch.tensor([0, 1, 2, 3, 4, 5]), "labels": torch.tensor([0, 1, 2, 3, 4, 5])}, ] data_collator = DataCollatorForTokenClassification(tokenizer) batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, torch.Size([2, 6])) self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) self.assertEqual(batch["labels"].shape, torch.Size([2, 6])) self.assertEqual(batch["labels"][0].tolist(), [0, 1, 2] + [-100] * 3) data_collator = DataCollatorForTokenClassification(tokenizer, padding="max_length", max_length=10) batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, torch.Size([2, 10])) self.assertEqual(batch["labels"].shape, torch.Size([2, 10])) data_collator = DataCollatorForTokenClassification(tokenizer, pad_to_multiple_of=8) batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, torch.Size([2, 8])) self.assertEqual(batch["labels"].shape, torch.Size([2, 8])) data_collator = DataCollatorForTokenClassification(tokenizer, label_pad_token_id=-1) batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, torch.Size([2, 6])) self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) self.assertEqual(batch["labels"].shape, torch.Size([2, 6])) self.assertEqual(batch["labels"][0].tolist(), [0, 1, 2] + [-1] * 3) for feature in features: feature.pop("labels") batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, torch.Size([2, 6])) self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) def _test_data_collator_for_seq2seq(self, to_torch): def create_features(to_torch): if to_torch: features = [ {"input_ids": torch.tensor(list(range(3))), "labels": torch.tensor(list(range(3)))}, {"input_ids": torch.tensor(list(range(6))), "labels": torch.tensor(list(range(6)))}, ] else: features = [ {"input_ids": list(range(3)), "labels": list(range(3))}, {"input_ids": list(range(6)), "labels": list(range(6))}, ] return features tokenizer = BertTokenizer(self.vocab_file) features = create_features(to_torch) data_collator = DataCollatorForSeq2Seq(tokenizer, padding=PaddingStrategy.LONGEST) batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, torch.Size([2, 6])) self.assertEqual(batch["input_ids"][0].tolist(), list(range(3)) + [tokenizer.pad_token_id] * 3) self.assertEqual(batch["input_ids"][1].tolist(), list(range(6))) self.assertEqual(batch["labels"].shape, torch.Size([2, 6])) self.assertEqual(batch["labels"][0].tolist(), list(range(3)) + [-100] * 3) self.assertEqual(batch["labels"][1].tolist(), list(range(6))) data_collator = DataCollatorForSeq2Seq(tokenizer, padding=PaddingStrategy.MAX_LENGTH, max_length=7) batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, torch.Size([2, 7])) self.assertEqual(batch["input_ids"][0].tolist(), list(range(3)) + [tokenizer.pad_token_id] * 4) self.assertEqual(batch["input_ids"][1].tolist(), list(range(6)) + [tokenizer.pad_token_id] * 1) self.assertEqual(batch["labels"].shape, torch.Size([2, 7])) self.assertEqual(batch["labels"][0].tolist(), list(range(3)) + [-100] * 4) self.assertEqual(batch["labels"][1].tolist(), list(range(6)) + [-100] * 1) data_collator = DataCollatorForSeq2Seq(tokenizer, padding=PaddingStrategy.DO_NOT_PAD) with self.assertRaises(ValueError): # expects an error due to unequal shapes to create tensor data_collator(features) batch = data_collator([features[0], features[0]]) input_ids = features[0]["input_ids"] if not to_torch else features[0]["input_ids"].tolist() labels = features[0]["labels"] if not to_torch else features[0]["labels"].tolist() self.assertEqual(batch["input_ids"][0].tolist(), input_ids) self.assertEqual(batch["input_ids"][1].tolist(), input_ids) self.assertEqual(batch["labels"][0].tolist(), labels) self.assertEqual(batch["labels"][1].tolist(), labels) data_collator = DataCollatorForSeq2Seq(tokenizer, padding=PaddingStrategy.LONGEST, pad_to_multiple_of=8) batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, torch.Size([2, 8])) self.assertEqual(batch["labels"].shape, torch.Size([2, 8])) # side effects on labels cause mismatch on longest strategy features = create_features(to_torch) data_collator = DataCollatorForSeq2Seq(tokenizer, padding=PaddingStrategy.LONGEST, label_pad_token_id=-1) batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, torch.Size([2, 6])) self.assertEqual(batch["input_ids"][0].tolist(), list(range(3)) + [tokenizer.pad_token_id] * 3) self.assertEqual(batch["input_ids"][1].tolist(), list(range(6))) self.assertEqual(batch["labels"].shape, torch.Size([2, 6])) self.assertEqual(batch["labels"][0].tolist(), list(range(3)) + [-1] * 3) self.assertEqual(batch["labels"][1].tolist(), list(range(6))) for feature in features: feature.pop("labels") batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, torch.Size([2, 6])) self.assertEqual(batch["input_ids"][0].tolist(), list(range(3)) + [tokenizer.pad_token_id] * 3) def test_data_collator_for_seq2seq_with_lists(self): self._test_data_collator_for_seq2seq(to_torch=False) def test_data_collator_for_seq2seq_with_pt(self): self._test_data_collator_for_seq2seq(to_torch=True) def _test_no_pad_and_pad(self, no_pad_features, pad_features): tokenizer = BertTokenizer(self.vocab_file) data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False) batch = data_collator(no_pad_features) self.assertEqual(batch["input_ids"].shape, torch.Size((2, 10))) self.assertEqual(batch["labels"].shape, torch.Size((2, 10))) batch = data_collator(pad_features) self.assertEqual(batch["input_ids"].shape, torch.Size((2, 10))) self.assertEqual(batch["labels"].shape, torch.Size((2, 10))) data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False, pad_to_multiple_of=8) batch = data_collator(no_pad_features) self.assertEqual(batch["input_ids"].shape, torch.Size((2, 16))) self.assertEqual(batch["labels"].shape, torch.Size((2, 16))) batch = data_collator(pad_features) self.assertEqual(batch["input_ids"].shape, torch.Size((2, 16))) self.assertEqual(batch["labels"].shape, torch.Size((2, 16))) tokenizer.pad_token = None data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False) with self.assertRaises(ValueError): # Expect error due to padding token missing data_collator(pad_features) set_seed(42) # For reproducibility tokenizer = BertTokenizer(self.vocab_file) data_collator = DataCollatorForLanguageModeling(tokenizer) batch = data_collator(no_pad_features) self.assertEqual(batch["input_ids"].shape, torch.Size((2, 10))) self.assertEqual(batch["labels"].shape, torch.Size((2, 10))) masked_tokens = batch["input_ids"] == tokenizer.mask_token_id self.assertTrue(torch.any(masked_tokens)) self.assertTrue(all(x == -100 for x in batch["labels"][~masked_tokens].tolist())) batch = data_collator(pad_features) self.assertEqual(batch["input_ids"].shape, torch.Size((2, 10))) self.assertEqual(batch["labels"].shape, torch.Size((2, 10))) masked_tokens = batch["input_ids"] == tokenizer.mask_token_id self.assertTrue(torch.any(masked_tokens)) self.assertTrue(all(x == -100 for x in batch["labels"][~masked_tokens].tolist())) data_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8) batch = data_collator(no_pad_features) self.assertEqual(batch["input_ids"].shape, torch.Size((2, 16))) self.assertEqual(batch["labels"].shape, torch.Size((2, 16))) masked_tokens = batch["input_ids"] == tokenizer.mask_token_id self.assertTrue(torch.any(masked_tokens)) self.assertTrue(all(x == -100 for x in batch["labels"][~masked_tokens].tolist())) batch = data_collator(pad_features) self.assertEqual(batch["input_ids"].shape, torch.Size((2, 16))) self.assertEqual(batch["labels"].shape, torch.Size((2, 16))) masked_tokens = batch["input_ids"] == tokenizer.mask_token_id self.assertTrue(torch.any(masked_tokens)) self.assertTrue(all(x == -100 for x in batch["labels"][~masked_tokens].tolist())) def test_data_collator_for_language_modeling(self): no_pad_features = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] pad_features = [{"input_ids": list(range(5))}, {"input_ids": list(range(10))}] self._test_no_pad_and_pad(no_pad_features, pad_features) no_pad_features = [list(range(10)), list(range(10))] pad_features = [list(range(5)), list(range(10))] self._test_no_pad_and_pad(no_pad_features, pad_features) def test_data_collator_for_language_modeling_with_seed(self): tokenizer = BertTokenizer(self.vocab_file) features = [{"input_ids": list(range(1000))}, {"input_ids": list(range(1000))}] # check if seed is respected between two different DataCollatorForLanguageModeling instances data_collator = DataCollatorForLanguageModeling(tokenizer, seed=42) batch_1 = data_collator(features) self.assertEqual(batch_1["input_ids"].shape, torch.Size((2, 1000))) self.assertEqual(batch_1["labels"].shape, torch.Size((2, 1000))) data_collator = DataCollatorForLanguageModeling(tokenizer, seed=42) batch_2 = data_collator(features) self.assertEqual(batch_2["input_ids"].shape, torch.Size((2, 1000))) self.assertEqual(batch_2["labels"].shape, torch.Size((2, 1000))) self.assertTrue(torch.all(batch_1["input_ids"] == batch_2["input_ids"])) self.assertTrue(torch.all(batch_1["labels"] == batch_2["labels"])) # check if seed is respected in multiple workers situation features = [{"input_ids": list(range(1000))} for _ in range(10)] dataloader = torch.utils.data.DataLoader( features, batch_size=2, num_workers=2, generator=torch.Generator().manual_seed(42), collate_fn=DataCollatorForLanguageModeling(tokenizer, seed=42), ) batch_3_input_ids = [] batch_3_labels = [] for batch in dataloader: batch_3_input_ids.append(batch["input_ids"]) batch_3_labels.append(batch["labels"]) batch_3_input_ids = torch.stack(batch_3_input_ids) batch_3_labels = torch.stack(batch_3_labels) self.assertEqual(batch_3_input_ids.shape, torch.Size((5, 2, 1000))) self.assertEqual(batch_3_labels.shape, torch.Size((5, 2, 1000))) dataloader = torch.utils.data.DataLoader( features, batch_size=2, num_workers=2, collate_fn=DataCollatorForLanguageModeling(tokenizer, seed=42), ) batch_4_input_ids = [] batch_4_labels = [] for batch in dataloader: batch_4_input_ids.append(batch["input_ids"]) batch_4_labels.append(batch["labels"]) batch_4_input_ids = torch.stack(batch_4_input_ids) batch_4_labels = torch.stack(batch_4_labels) self.assertEqual(batch_4_input_ids.shape, torch.Size((5, 2, 1000))) self.assertEqual(batch_4_labels.shape, torch.Size((5, 2, 1000))) self.assertTrue(torch.all(batch_3_input_ids == batch_4_input_ids)) self.assertTrue(torch.all(batch_3_labels == batch_4_labels)) # try with different seed dataloader = torch.utils.data.DataLoader( features, batch_size=2, num_workers=2, collate_fn=DataCollatorForLanguageModeling(tokenizer, seed=43), ) batch_5_input_ids = [] batch_5_labels = [] for batch in dataloader: batch_5_input_ids.append(batch["input_ids"]) batch_5_labels.append(batch["labels"]) batch_5_input_ids = torch.stack(batch_5_input_ids) batch_5_labels = torch.stack(batch_5_labels) self.assertEqual(batch_5_input_ids.shape, torch.Size((5, 2, 1000))) self.assertEqual(batch_5_labels.shape, torch.Size((5, 2, 1000))) self.assertFalse(torch.all(batch_3_input_ids == batch_5_input_ids)) self.assertFalse(torch.all(batch_3_labels == batch_5_labels)) def test_data_collator_for_whole_word_mask(self): tokenizer = BertTokenizer(self.vocab_file) data_collator = DataCollatorForWholeWordMask(tokenizer, return_tensors="pt") features = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, torch.Size((2, 10))) self.assertEqual(batch["labels"].shape, torch.Size((2, 10))) # Features can already be tensors features = [{"input_ids": np.arange(10)}, {"input_ids": np.arange(10)}] batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, torch.Size((2, 10))) self.assertEqual(batch["labels"].shape, torch.Size((2, 10))) def test_data_collator_for_whole_word_mask_with_seed(self): tokenizer = BertTokenizer(self.vocab_file) features = [{"input_ids": list(range(1000))}, {"input_ids": list(range(1000))}] # check if seed is respected between two different DataCollatorForWholeWordMask instances data_collator = DataCollatorForWholeWordMask(tokenizer, seed=42) batch_1 = data_collator(features) self.assertEqual(batch_1["input_ids"].shape, torch.Size((2, 1000))) self.assertEqual(batch_1["labels"].shape, torch.Size((2, 1000))) data_collator = DataCollatorForWholeWordMask(tokenizer, seed=42) batch_2 = data_collator(features) self.assertEqual(batch_2["input_ids"].shape, torch.Size((2, 1000))) self.assertEqual(batch_2["labels"].shape, torch.Size((2, 1000))) self.assertTrue(torch.all(batch_1["input_ids"] == batch_2["input_ids"])) self.assertTrue(torch.all(batch_1["labels"] == batch_2["labels"])) # check if seed is respected in multiple workers situation features = [{"input_ids": list(range(1000))} for _ in range(10)] dataloader = torch.utils.data.DataLoader( features, batch_size=2, num_workers=2, generator=torch.Generator().manual_seed(42), collate_fn=DataCollatorForWholeWordMask(tokenizer, seed=42), ) batch_3_input_ids = [] batch_3_labels = [] for batch in dataloader: batch_3_input_ids.append(batch["input_ids"]) batch_3_labels.append(batch["labels"]) batch_3_input_ids = torch.stack(batch_3_input_ids) batch_3_labels = torch.stack(batch_3_labels) self.assertEqual(batch_3_input_ids.shape, torch.Size((5, 2, 1000))) self.assertEqual(batch_3_labels.shape, torch.Size((5, 2, 1000))) dataloader = torch.utils.data.DataLoader( features, batch_size=2, num_workers=2, collate_fn=DataCollatorForWholeWordMask(tokenizer, seed=42), ) batch_4_input_ids = [] batch_4_labels = [] for batch in dataloader: batch_4_input_ids.append(batch["input_ids"]) batch_4_labels.append(batch["labels"]) batch_4_input_ids = torch.stack(batch_4_input_ids) batch_4_labels = torch.stack(batch_4_labels) self.assertEqual(batch_4_input_ids.shape, torch.Size((5, 2, 1000))) self.assertEqual(batch_4_labels.shape, torch.Size((5, 2, 1000))) self.assertTrue(torch.all(batch_3_input_ids == batch_4_input_ids)) self.assertTrue(torch.all(batch_3_labels == batch_4_labels)) # try with different seed dataloader = torch.utils.data.DataLoader( features, batch_size=2, num_workers=2, collate_fn=DataCollatorForWholeWordMask(tokenizer, seed=43), ) batch_5_input_ids = [] batch_5_labels = [] for batch in dataloader: batch_5_input_ids.append(batch["input_ids"]) batch_5_labels.append(batch["labels"]) batch_5_input_ids = torch.stack(batch_5_input_ids) batch_5_labels = torch.stack(batch_5_labels) self.assertEqual(batch_5_input_ids.shape, torch.Size((5, 2, 1000))) self.assertEqual(batch_5_labels.shape, torch.Size((5, 2, 1000))) self.assertFalse(torch.all(batch_3_input_ids == batch_5_input_ids)) self.assertFalse(torch.all(batch_3_labels == batch_5_labels)) def test_plm(self): tokenizer = BertTokenizer(self.vocab_file) no_pad_features = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] pad_features = [{"input_ids": list(range(5))}, {"input_ids": list(range(10))}] data_collator = DataCollatorForPermutationLanguageModeling(tokenizer) batch = data_collator(pad_features) self.assertIsInstance(batch, dict) self.assertEqual(batch["input_ids"].shape, torch.Size((2, 10))) self.assertEqual(batch["perm_mask"].shape, torch.Size((2, 10, 10))) self.assertEqual(batch["target_mapping"].shape, torch.Size((2, 10, 10))) self.assertEqual(batch["labels"].shape, torch.Size((2, 10))) batch = data_collator(no_pad_features) self.assertIsInstance(batch, dict) self.assertEqual(batch["input_ids"].shape, torch.Size((2, 10))) self.assertEqual(batch["perm_mask"].shape, torch.Size((2, 10, 10))) self.assertEqual(batch["target_mapping"].shape, torch.Size((2, 10, 10))) self.assertEqual(batch["labels"].shape, torch.Size((2, 10))) example = [np.random.randint(0, 5, [5])] with self.assertRaises(ValueError): # Expect error due to odd sequence length data_collator(example) def test_nsp(self): tokenizer = BertTokenizer(self.vocab_file) features = [ {"input_ids": [0, 1, 2, 3, 4], "token_type_ids": [0, 1, 2, 3, 4], "next_sentence_label": i} for i in range(2) ] data_collator = DataCollatorForLanguageModeling(tokenizer) batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, torch.Size((2, 5))) self.assertEqual(batch["token_type_ids"].shape, torch.Size((2, 5))) self.assertEqual(batch["labels"].shape, torch.Size((2, 5))) self.assertEqual(batch["next_sentence_label"].shape, torch.Size((2,))) data_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8) batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, torch.Size((2, 8))) self.assertEqual(batch["token_type_ids"].shape, torch.Size((2, 8))) self.assertEqual(batch["labels"].shape, torch.Size((2, 8))) self.assertEqual(batch["next_sentence_label"].shape, torch.Size((2,))) def test_sop(self): tokenizer = BertTokenizer(self.vocab_file) features = [ { "input_ids": torch.tensor([0, 1, 2, 3, 4]), "token_type_ids": torch.tensor([0, 1, 2, 3, 4]), "sentence_order_label": i, } for i in range(2) ] data_collator = DataCollatorForLanguageModeling(tokenizer) batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, torch.Size((2, 5))) self.assertEqual(batch["token_type_ids"].shape, torch.Size((2, 5))) self.assertEqual(batch["labels"].shape, torch.Size((2, 5))) self.assertEqual(batch["sentence_order_label"].shape, torch.Size((2,))) data_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8) batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, torch.Size((2, 8))) self.assertEqual(batch["token_type_ids"].shape, torch.Size((2, 8))) self.assertEqual(batch["labels"].shape, torch.Size((2, 8))) self.assertEqual(batch["sentence_order_label"].shape, torch.Size((2,))) @require_torch class DataCollatorImmutabilityTest(unittest.TestCase): def setUp(self): self.tmpdirname = tempfile.mkdtemp() vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"] self.vocab_file = os.path.join(self.tmpdirname, "vocab.txt") with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) def tearDown(self): shutil.rmtree(self.tmpdirname) def _turn_to_none(self, item): """used to convert `item` to `None` type""" return None def _validate_original_data_against_collated_data(self, collator, original_data, batch_data): # we only care about side effects, the results are tested elsewhere collator(batch_data) # we go through every item and convert to `primitive` datatypes if necessary # then compares for equivalence for the original data and the data that has been passed through the collator for original, batch in zip(original_data, batch_data): for original_val, batch_val in zip(original.values(), batch.values()): if isinstance(original_val, (np.ndarray, torch.Tensor)): self.assertEqual(original_val.tolist(), batch_val.tolist()) else: self.assertEqual(original_val, batch_val) def _validate_original_data_against_collated_data_on_specified_keys_and_datatypes( self, collator, base_data, input_key, input_datatype, label_key, label_datatype, ignore_label=False ): # using the arguments to recreate the features with their respective (potentially new) datatypes features_original = [ {label_key: label_datatype(sample[label_key]), input_key: input_datatype(sample[input_key])} for sample in base_data ] features_batch = [ {label_key: label_datatype(sample[label_key]), input_key: input_datatype(sample[input_key])} for sample in base_data ] # some collators do not use labels, or sometimes we want to check if the collator with labels can handle such cases if ignore_label: for original, batch in zip(features_original, features_batch): original.pop(label_key) batch.pop(label_key) self._validate_original_data_against_collated_data( collator=collator, original_data=features_original, batch_data=features_batch ) def test_default_collator_immutability(self): features_base_single_label = [{"label": i, "inputs": (0, 1, 2, 3, 4, 5)} for i in range(4)] features_base_multiple_labels = [{"label": (0, 1, 2), "inputs": (0, 1, 2, 3, 4, 5)} for i in range(4)] for datatype_input, datatype_label in [ (list, int), (list, float), (np.array, int), (np.array, torch.tensor), (list, self._turn_to_none), ]: self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( collator=default_data_collator, base_data=features_base_single_label, input_key="inputs", input_datatype=datatype_input, label_key="label", label_datatype=datatype_label, ) for datatype_input, datatype_label in [(list, list), (list, self._turn_to_none)]: self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( collator=default_data_collator, base_data=features_base_multiple_labels, input_key="inputs", input_datatype=datatype_input, label_key="label", label_datatype=datatype_label, ) features_base_single_label_alt = [{"input_ids": (0, 1, 2, 3, 4), "label": float(i)} for i in range(4)] self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( collator=default_data_collator, base_data=features_base_single_label_alt, input_key="input_ids", input_datatype=list, label_key="label", label_datatype=float, ) def test_with_padding_collator_immutability(self): tokenizer = BertTokenizer(self.vocab_file) features_original = [{"input_ids": [0, 1, 2]}, {"input_ids": [0, 1, 2, 3, 4, 5]}] features_batch = [{"input_ids": [0, 1, 2]}, {"input_ids": [0, 1, 2, 3, 4, 5]}] data_collator = DataCollatorWithPadding(tokenizer, padding="max_length", max_length=10) self._validate_original_data_against_collated_data( collator=data_collator, original_data=features_original, batch_data=features_batch ) data_collator = DataCollatorWithPadding(tokenizer, pad_to_multiple_of=8) self._validate_original_data_against_collated_data( collator=data_collator, original_data=features_original, batch_data=features_batch ) def test_for_token_classification_collator_immutability(self): tokenizer = BertTokenizer(self.vocab_file) features_base = [ {"input_ids": (0, 1, 2), "labels": (0, 1, 2)}, {"input_ids": (0, 1, 2, 3, 4, 5), "labels": (0, 1, 2, 3, 4, 5)}, ] token_classification_collators = [ DataCollatorForTokenClassification(tokenizer), DataCollatorForTokenClassification(tokenizer, padding="max_length", max_length=10), DataCollatorForTokenClassification(tokenizer, pad_to_multiple_of=8), DataCollatorForTokenClassification(tokenizer, label_pad_token_id=-1), ] for datatype_input, datatype_label in [(list, list), (torch.tensor, torch.tensor)]: for collator in token_classification_collators: self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( collator=collator, base_data=features_base, input_key="input_ids", input_datatype=datatype_input, label_key="labels", label_datatype=datatype_label, ) self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( collator=token_classification_collators[-1], base_data=features_base, input_key="input_ids", input_datatype=datatype_input, label_key="labels", label_datatype=datatype_label, ignore_label=True, ) def test_seq2seq_collator_immutability(self): tokenizer = BertTokenizer(self.vocab_file) features_base = [ {"input_ids": list(range(3)), "labels": list(range(3))}, {"input_ids": list(range(6)), "labels": list(range(6))}, ] seq2seq_collators = [ DataCollatorForSeq2Seq(tokenizer, padding=PaddingStrategy.LONGEST), DataCollatorForSeq2Seq(tokenizer, padding=PaddingStrategy.MAX_LENGTH, max_length=7), DataCollatorForSeq2Seq(tokenizer, padding=PaddingStrategy.LONGEST, pad_to_multiple_of=8), DataCollatorForSeq2Seq(tokenizer, padding=PaddingStrategy.LONGEST, label_pad_token_id=-1), ] for datatype_input, datatype_label in [(list, list), (torch.tensor, torch.tensor)]: for collator in seq2seq_collators: self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( collator=collator, base_data=features_base, input_key="input_ids", input_datatype=datatype_input, label_key="labels", label_datatype=datatype_label, ) self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( collator=seq2seq_collators[-1], base_data=features_base, input_key="input_ids", input_datatype=datatype_input, label_key="labels", label_datatype=datatype_label, ignore_label=True, ) features_base_no_pad = [ {"input_ids": list(range(3)), "labels": list(range(3))}, {"input_ids": list(range(3)), "labels": list(range(3))}, ] seq2seq_no_padding_collator = DataCollatorForSeq2Seq(tokenizer, padding=PaddingStrategy.DO_NOT_PAD) for datatype_input, datatype_label in [(list, list), (torch.tensor, torch.tensor)]: self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( collator=seq2seq_no_padding_collator, base_data=features_base_no_pad, input_key="input_ids", input_datatype=datatype_input, label_key="labels", label_datatype=datatype_label, ) def test_language_modelling_collator_immutability(self): tokenizer = BertTokenizer(self.vocab_file) features_base_no_pad = [ {"input_ids": tuple(range(10)), "labels": (1,)}, {"input_ids": tuple(range(10)), "labels": (1,)}, ] features_base_pad = [ {"input_ids": tuple(range(5)), "labels": (1,)}, {"input_ids": tuple(range(5)), "labels": (1,)}, ] lm_collators = [ DataCollatorForLanguageModeling(tokenizer, mlm=False), DataCollatorForLanguageModeling(tokenizer, mlm=False, pad_to_multiple_of=8), DataCollatorForLanguageModeling(tokenizer), DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8), ] for datatype_input, datatype_label in [(list, list), (torch.tensor, torch.tensor)]: for collator in lm_collators: self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( collator=collator, base_data=features_base_no_pad, input_key="input_ids", input_datatype=datatype_input, label_key="labels", label_datatype=datatype_label, ignore_label=True, ) self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( collator=collator, base_data=features_base_pad, input_key="input_ids", input_datatype=datatype_input, label_key="labels", label_datatype=datatype_label, ignore_label=True, ) def test_whole_world_masking_collator_immutability(self): tokenizer = BertTokenizer(self.vocab_file) features_base = [ {"input_ids": list(range(10)), "labels": (1,)}, {"input_ids": list(range(10)), "labels": (1,)}, ] whole_word_masking_collator = DataCollatorForWholeWordMask(tokenizer, return_tensors="pt") for datatype_input, datatype_label in [(list, list), (np.array, np.array)]: self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( collator=whole_word_masking_collator, base_data=features_base, input_key="input_ids", input_datatype=datatype_input, label_key="labels", label_datatype=datatype_label, ignore_label=True, ) def test_permutation_language_modelling_collator_immutability(self): tokenizer = BertTokenizer(self.vocab_file) plm_collator = DataCollatorForPermutationLanguageModeling(tokenizer) no_pad_features_original = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] no_pad_features_batch = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] self._validate_original_data_against_collated_data( collator=plm_collator, original_data=no_pad_features_original, batch_data=no_pad_features_batch ) pad_features_original = [{"input_ids": list(range(5))}, {"input_ids": list(range(10))}] pad_features_batch = [{"input_ids": list(range(5))}, {"input_ids": list(range(10))}] self._validate_original_data_against_collated_data( collator=plm_collator, original_data=pad_features_original, batch_data=pad_features_batch ) def test_next_sentence_prediction_collator_immutability(self): tokenizer = BertTokenizer(self.vocab_file) features_original = [ {"input_ids": [0, 1, 2, 3, 4], "token_type_ids": [0, 1, 2, 3, 4], "next_sentence_label": i} for i in range(2) ] features_batch = [ {"input_ids": [0, 1, 2, 3, 4], "token_type_ids": [0, 1, 2, 3, 4], "next_sentence_label": i} for i in range(2) ] nsp_collator = DataCollatorForLanguageModeling(tokenizer) self._validate_original_data_against_collated_data( collator=nsp_collator, original_data=features_original, batch_data=features_batch ) nsp_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8) self._validate_original_data_against_collated_data( collator=nsp_collator, original_data=features_original, batch_data=features_batch ) def test_sentence_order_prediction_collator_immutability(self): tokenizer = BertTokenizer(self.vocab_file) features_original = [ { "input_ids": torch.tensor([0, 1, 2, 3, 4]), "token_type_ids": torch.tensor([0, 1, 2, 3, 4]), "sentence_order_label": i, } for i in range(2) ] features_batch = [ { "input_ids": torch.tensor([0, 1, 2, 3, 4]), "token_type_ids": torch.tensor([0, 1, 2, 3, 4]), "sentence_order_label": i, } for i in range(2) ] sop_collator = DataCollatorForLanguageModeling(tokenizer) self._validate_original_data_against_collated_data( collator=sop_collator, original_data=features_original, batch_data=features_batch ) sop_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8) self._validate_original_data_against_collated_data( collator=sop_collator, original_data=features_original, batch_data=features_batch ) class NumpyDataCollatorIntegrationTest(unittest.TestCase): def setUp(self): self.tmpdirname = tempfile.mkdtemp() vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"] self.vocab_file = os.path.join(self.tmpdirname, "vocab.txt") with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) def tearDown(self): shutil.rmtree(self.tmpdirname) def test_default_with_dict(self): features = [{"label": i, "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)] batch = default_data_collator(features, return_tensors="np") self.assertEqual(batch["labels"].tolist(), list(range(8))) self.assertEqual(batch["labels"].dtype, np.int64) self.assertEqual(batch["inputs"].shape, (8, 6)) # With label_ids features = [{"label_ids": [0, 1, 2], "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)] batch = default_data_collator(features, return_tensors="np") self.assertEqual(batch["labels"].tolist(), [[0, 1, 2]] * 8) self.assertEqual(batch["labels"].dtype, np.int64) self.assertEqual(batch["inputs"].shape, (8, 6)) # Features can already be tensors features = [{"label": i, "inputs": np.random.randint(0, 10, [10])} for i in range(8)] batch = default_data_collator(features, return_tensors="np") self.assertEqual(batch["labels"].tolist(), list(range(8))) self.assertEqual(batch["labels"].dtype, np.int64) self.assertEqual(batch["inputs"].shape, (8, 10)) # Labels can already be tensors features = [{"label": np.array(i), "inputs": np.random.randint(0, 10, [10])} for i in range(8)] batch = default_data_collator(features, return_tensors="np") self.assertEqual(batch["labels"].dtype, np.int64) self.assertEqual(batch["labels"].tolist(), (list(range(8)))) self.assertEqual(batch["labels"].dtype, np.int64) self.assertEqual(batch["inputs"].shape, (8, 10)) def test_default_classification_and_regression(self): data_collator = default_data_collator features = [{"input_ids": [0, 1, 2, 3, 4], "label": i} for i in range(4)] batch = data_collator(features, return_tensors="np") self.assertEqual(batch["labels"].dtype, np.int64) features = [{"input_ids": [0, 1, 2, 3, 4], "label": float(i)} for i in range(4)] batch = data_collator(features, return_tensors="np") self.assertEqual(batch["labels"].dtype, np.float32) def test_default_with_no_labels(self): features = [{"label": None, "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)] batch = default_data_collator(features, return_tensors="np") self.assertTrue("labels" not in batch) self.assertEqual(batch["inputs"].shape, (8, 6)) # With label_ids features = [{"label_ids": None, "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)] batch = default_data_collator(features, return_tensors="np") self.assertTrue("labels" not in batch) self.assertEqual(batch["inputs"].shape, (8, 6)) def test_data_collator_with_padding(self): tokenizer = BertTokenizer(self.vocab_file) features = [{"input_ids": [0, 1, 2]}, {"input_ids": [0, 1, 2, 3, 4, 5]}] data_collator = DataCollatorWithPadding(tokenizer, return_tensors="np") batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, (2, 6)) self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) data_collator = DataCollatorWithPadding(tokenizer, padding="max_length", max_length=10, return_tensors="np") batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, (2, 10)) data_collator = DataCollatorWithPadding(tokenizer, pad_to_multiple_of=8, return_tensors="np") batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, (2, 8)) def test_data_collator_with_flattening(self): features = [ {"input_ids": [10, 11, 12]}, {"input_ids": [20, 21, 22, 23, 24, 25]}, {"input_ids": [30, 31, 32, 33, 34, 35, 36]}, ] data_collator = DataCollatorWithFlattening(return_tensors="np") batch = data_collator(features) for unexpected_key in [ "attention_mask", "cu_seq_lens_k", "cu_seq_lens_q", "max_length_k", "max_length_q", "seq_idx", ]: self.assertNotIn(unexpected_key, batch) self.assertIn("position_ids", batch) self.assertEqual(batch["input_ids"].shape, (1, 16)) self.assertEqual( batch["input_ids"][0].tolist(), [10, 11, 12, 20, 21, 22, 23, 24, 25, 30, 31, 32, 33, 34, 35, 36] ) self.assertEqual(batch["position_ids"].shape, (1, 16)) self.assertEqual(batch["position_ids"][0].tolist(), [0, 1, 2, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6]) def test_data_collator_with_flattening_flash_attn_kwargs(self): features = [ {"input_ids": [10, 11, 12]}, {"input_ids": [20, 21, 22, 23, 24, 25]}, {"input_ids": [30, 31, 32, 33, 34, 35, 36]}, ] data_collator = DataCollatorWithFlattening(return_tensors="np", return_flash_attn_kwargs=True) batch = data_collator(features) for unexpected_key in [ "attention_mask", "seq_idx", ]: self.assertNotIn(unexpected_key, batch) for expected_key in [ "position_ids", "cu_seq_lens_k", "cu_seq_lens_q", "max_length_k", "max_length_q", ]: self.assertIn(expected_key, batch) self.assertEqual(batch["input_ids"].shape, (1, 16)) self.assertEqual( batch["input_ids"][0].tolist(), [10, 11, 12, 20, 21, 22, 23, 24, 25, 30, 31, 32, 33, 34, 35, 36] ) self.assertEqual(batch["position_ids"].shape, (1, 16)) self.assertEqual(batch["position_ids"][0].tolist(), [0, 1, 2, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6]) self.assertEqual(batch["cu_seq_lens_k"].shape, (4,)) self.assertEqual(batch["cu_seq_lens_k"].tolist(), [0, 3, 9, 16]) self.assertEqual(batch["cu_seq_lens_q"].shape, (4,)) self.assertEqual(batch["cu_seq_lens_q"].tolist(), [0, 3, 9, 16]) # The flash attn max_length_{k,q} are simple python ints self.assertEqual(batch["max_length_k"], 7) self.assertEqual(batch["max_length_q"], 7) def test_data_collator_with_flattening_seq_idx(self): features = [ {"input_ids": [10, 11, 12]}, {"input_ids": [20, 21, 22, 23, 24, 25]}, {"input_ids": [30, 31, 32, 33, 34, 35, 36]}, ] data_collator = DataCollatorWithFlattening(return_tensors="np", return_seq_idx=True) batch = data_collator(features) for unexpected_key in [ "attention_mask", "cu_seq_lens_k", "cu_seq_lens_q", "max_length_k", "max_length_q", ]: self.assertNotIn(unexpected_key, batch) for expected_key in [ "position_ids", "seq_idx", ]: self.assertIn(expected_key, batch) self.assertEqual(batch["input_ids"].shape, (1, 16)) self.assertEqual( batch["input_ids"][0].tolist(), [10, 11, 12, 20, 21, 22, 23, 24, 25, 30, 31, 32, 33, 34, 35, 36] ) self.assertEqual(batch["position_ids"].shape, (1, 16)) self.assertEqual(batch["position_ids"][0].tolist(), [0, 1, 2, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6]) self.assertEqual(batch["seq_idx"].shape, batch["input_ids"].shape) self.assertEqual(batch["seq_idx"][0].tolist(), [0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]) def test_data_collator_for_token_classification(self): tokenizer = BertTokenizer(self.vocab_file) features = [ {"input_ids": [0, 1, 2], "labels": [0, 1, 2]}, {"input_ids": [0, 1, 2, 3, 4, 5], "labels": [0, 1, 2, 3, 4, 5]}, ] data_collator = DataCollatorForTokenClassification(tokenizer, return_tensors="np") batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, (2, 6)) self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) self.assertEqual(batch["labels"].shape, (2, 6)) self.assertEqual(batch["labels"][0].tolist(), [0, 1, 2] + [-100] * 3) data_collator = DataCollatorForTokenClassification( tokenizer, padding="max_length", max_length=10, return_tensors="np" ) batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, (2, 10)) self.assertEqual(batch["labels"].shape, (2, 10)) data_collator = DataCollatorForTokenClassification(tokenizer, pad_to_multiple_of=8, return_tensors="np") batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, (2, 8)) self.assertEqual(batch["labels"].shape, (2, 8)) data_collator = DataCollatorForTokenClassification(tokenizer, label_pad_token_id=-1, return_tensors="np") batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, (2, 6)) self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) self.assertEqual(batch["labels"].shape, (2, 6)) self.assertEqual(batch["labels"][0].tolist(), [0, 1, 2] + [-1] * 3) def test_data_collator_for_seq2seq(self): def create_features(): return [ {"input_ids": list(range(3)), "labels": list(range(3))}, {"input_ids": list(range(6)), "labels": list(range(6))}, ] tokenizer = BertTokenizer(self.vocab_file) features = create_features() data_collator = DataCollatorForSeq2Seq(tokenizer, padding=PaddingStrategy.LONGEST, return_tensors="np") batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, (2, 6)) self.assertEqual(batch["input_ids"][0].tolist(), list(range(3)) + [tokenizer.pad_token_id] * 3) self.assertEqual(batch["input_ids"][1].tolist(), list(range(6))) self.assertEqual(batch["labels"].shape, (2, 6)) self.assertEqual(batch["labels"][0].tolist(), list(range(3)) + [-100] * 3) self.assertEqual(batch["labels"][1].tolist(), list(range(6))) data_collator = DataCollatorForSeq2Seq( tokenizer, padding=PaddingStrategy.MAX_LENGTH, max_length=7, return_tensors="np" ) batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, (2, 7)) self.assertEqual(batch["input_ids"][0].tolist(), list(range(3)) + [tokenizer.pad_token_id] * 4) self.assertEqual(batch["input_ids"][1].tolist(), list(range(6)) + [tokenizer.pad_token_id] * 1) self.assertEqual(batch["labels"].shape, (2, 7)) self.assertEqual(batch["labels"][0].tolist(), list(range(3)) + [-100] * 4) self.assertEqual(batch["labels"][1].tolist(), list(range(6)) + [-100] * 1) data_collator = DataCollatorForSeq2Seq(tokenizer, padding=PaddingStrategy.DO_NOT_PAD, return_tensors="np") # numpy doesn't have issues handling unequal shapes via `dtype=object` # with self.assertRaises(ValueError): # data_collator(features) batch = data_collator([features[0], features[0]]) self.assertEqual(batch["input_ids"][0].tolist(), features[0]["input_ids"]) self.assertEqual(batch["input_ids"][1].tolist(), features[0]["input_ids"]) self.assertEqual(batch["labels"][0].tolist(), features[0]["labels"]) self.assertEqual(batch["labels"][1].tolist(), features[0]["labels"]) data_collator = DataCollatorForSeq2Seq( tokenizer, padding=PaddingStrategy.LONGEST, pad_to_multiple_of=8, return_tensors="np" ) batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, (2, 8)) self.assertEqual(batch["labels"].shape, (2, 8)) # side effects on labels cause mismatch on longest strategy features = create_features() data_collator = DataCollatorForSeq2Seq( tokenizer, padding=PaddingStrategy.LONGEST, label_pad_token_id=-1, return_tensors="np" ) batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, (2, 6)) self.assertEqual(batch["input_ids"][0].tolist(), list(range(3)) + [tokenizer.pad_token_id] * 3) self.assertEqual(batch["input_ids"][1].tolist(), list(range(6))) self.assertEqual(batch["labels"].shape, (2, 6)) self.assertEqual(batch["labels"][0].tolist(), list(range(3)) + [-1] * 3) self.assertEqual(batch["labels"][1].tolist(), list(range(6))) for feature in features: feature.pop("labels") batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, (2, 6)) self.assertEqual(batch["input_ids"][0].tolist(), list(range(3)) + [tokenizer.pad_token_id] * 3) def _test_no_pad_and_pad(self, no_pad_features, pad_features): tokenizer = BertTokenizer(self.vocab_file) data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False, return_tensors="np") batch = data_collator(no_pad_features) self.assertEqual(batch["input_ids"].shape, (2, 10)) self.assertEqual(batch["labels"].shape, (2, 10)) batch = data_collator(pad_features, return_tensors="np") self.assertEqual(batch["input_ids"].shape, (2, 10)) self.assertEqual(batch["labels"].shape, (2, 10)) data_collator = DataCollatorForLanguageModeling( tokenizer, mlm=False, pad_to_multiple_of=8, return_tensors="np" ) batch = data_collator(no_pad_features) self.assertEqual(batch["input_ids"].shape, (2, 16)) self.assertEqual(batch["labels"].shape, (2, 16)) batch = data_collator(pad_features, return_tensors="np") self.assertEqual(batch["input_ids"].shape, (2, 16)) self.assertEqual(batch["labels"].shape, (2, 16)) tokenizer.pad_token = None data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False, return_tensors="np") with self.assertRaises(ValueError): # Expect error due to padding token missing data_collator(pad_features) set_seed(42) # For reproducibility tokenizer = BertTokenizer(self.vocab_file) data_collator = DataCollatorForLanguageModeling(tokenizer, return_tensors="np") batch = data_collator(no_pad_features) self.assertEqual(batch["input_ids"].shape, (2, 10)) self.assertEqual(batch["labels"].shape, (2, 10)) masked_tokens = batch["input_ids"] == tokenizer.mask_token_id self.assertTrue(np.any(masked_tokens)) # self.assertTrue(all(x == -100 for x in batch["labels"][~masked_tokens].tolist())) batch = data_collator(pad_features) self.assertEqual(batch["input_ids"].shape, (2, 10)) self.assertEqual(batch["labels"].shape, (2, 10)) masked_tokens = batch["input_ids"] == tokenizer.mask_token_id self.assertTrue(np.any(masked_tokens)) # self.assertTrue(all(x == -100 for x in batch["labels"][~masked_tokens].tolist())) data_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8, return_tensors="np") batch = data_collator(no_pad_features) self.assertEqual(batch["input_ids"].shape, (2, 16)) self.assertEqual(batch["labels"].shape, (2, 16)) masked_tokens = batch["input_ids"] == tokenizer.mask_token_id self.assertTrue(np.any(masked_tokens)) # self.assertTrue(all(x == -100 for x in batch["labels"][~masked_tokens].tolist())) batch = data_collator(pad_features) self.assertEqual(batch["input_ids"].shape, (2, 16)) self.assertEqual(batch["labels"].shape, (2, 16)) masked_tokens = batch["input_ids"] == tokenizer.mask_token_id self.assertTrue(np.any(masked_tokens)) # self.assertTrue(all(x == -100 for x in batch["labels"][~masked_tokens].tolist())) def test_data_collator_for_language_modeling(self): no_pad_features = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] pad_features = [{"input_ids": list(range(5))}, {"input_ids": list(range(10))}] self._test_no_pad_and_pad(no_pad_features, pad_features) no_pad_features = [list(range(10)), list(range(10))] pad_features = [list(range(5)), list(range(10))] self._test_no_pad_and_pad(no_pad_features, pad_features) def test_data_collator_for_language_modeling_with_seed(self): tokenizer = BertTokenizer(self.vocab_file) features = [{"input_ids": list(range(1000))}, {"input_ids": list(range(1000))}] # check if seed is respected between two different DataCollatorForLanguageModeling instances data_collator = DataCollatorForLanguageModeling(tokenizer, seed=42, return_tensors="np") batch_1 = data_collator(features) self.assertEqual(batch_1["input_ids"].shape, (2, 1000)) self.assertEqual(batch_1["labels"].shape, (2, 1000)) data_collator = DataCollatorForLanguageModeling(tokenizer, seed=42, return_tensors="np") batch_2 = data_collator(features) self.assertEqual(batch_2["input_ids"].shape, (2, 1000)) self.assertEqual(batch_2["labels"].shape, (2, 1000)) self.assertTrue(np.all(batch_1["input_ids"] == batch_2["input_ids"])) self.assertTrue(np.all(batch_1["labels"] == batch_2["labels"])) data_collator = DataCollatorForLanguageModeling(tokenizer, seed=43, return_tensors="np") batch_3 = data_collator(features) self.assertEqual(batch_3["input_ids"].shape, (2, 1000)) self.assertEqual(batch_3["labels"].shape, (2, 1000)) self.assertFalse(np.all(batch_1["input_ids"] == batch_3["input_ids"])) self.assertFalse(np.all(batch_1["labels"] == batch_3["labels"])) def test_data_collator_for_whole_word_mask(self): tokenizer = BertTokenizer(self.vocab_file) data_collator = DataCollatorForWholeWordMask(tokenizer, return_tensors="np") features = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, (2, 10)) self.assertEqual(batch["labels"].shape, (2, 10)) # Features can already be tensors features = [{"input_ids": np.arange(10)}, {"input_ids": np.arange(10)}] batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, (2, 10)) self.assertEqual(batch["labels"].shape, (2, 10)) def test_data_collator_for_whole_word_mask_with_seed(self): tokenizer = BertTokenizer(self.vocab_file) features = [{"input_ids": list(range(1000))}, {"input_ids": list(range(1000))}] # check if seed is respected between two different DataCollatorForWholeWordMask instances data_collator = DataCollatorForWholeWordMask(tokenizer, seed=42, return_tensors="np") batch_1 = data_collator(features) self.assertEqual(batch_1["input_ids"].shape, (2, 1000)) self.assertEqual(batch_1["labels"].shape, (2, 1000)) data_collator = DataCollatorForWholeWordMask(tokenizer, seed=42, return_tensors="np") batch_2 = data_collator(features) self.assertEqual(batch_2["input_ids"].shape, (2, 1000)) self.assertEqual(batch_2["labels"].shape, (2, 1000)) self.assertTrue(np.all(batch_1["input_ids"] == batch_2["input_ids"])) self.assertTrue(np.all(batch_1["labels"] == batch_2["labels"])) data_collator = DataCollatorForWholeWordMask(tokenizer, seed=43, return_tensors="np") batch_3 = data_collator(features) self.assertEqual(batch_3["input_ids"].shape, (2, 1000)) self.assertEqual(batch_3["labels"].shape, (2, 1000)) self.assertFalse(np.all(batch_1["input_ids"] == batch_3["input_ids"])) self.assertFalse(np.all(batch_1["labels"] == batch_3["labels"])) def test_plm(self): tokenizer = BertTokenizer(self.vocab_file) no_pad_features = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] pad_features = [{"input_ids": list(range(5))}, {"input_ids": list(range(10))}] data_collator = DataCollatorForPermutationLanguageModeling(tokenizer, return_tensors="np") batch = data_collator(pad_features) self.assertIsInstance(batch, dict) self.assertEqual(batch["input_ids"].shape, (2, 10)) self.assertEqual(batch["perm_mask"].shape, (2, 10, 10)) self.assertEqual(batch["target_mapping"].shape, (2, 10, 10)) self.assertEqual(batch["labels"].shape, (2, 10)) batch = data_collator(no_pad_features) self.assertIsInstance(batch, dict) self.assertEqual(batch["input_ids"].shape, (2, 10)) self.assertEqual(batch["perm_mask"].shape, (2, 10, 10)) self.assertEqual(batch["target_mapping"].shape, (2, 10, 10)) self.assertEqual(batch["labels"].shape, (2, 10)) example = [np.random.randint(0, 5, [5])] with self.assertRaises(ValueError): # Expect error due to odd sequence length data_collator(example) def test_nsp(self): tokenizer = BertTokenizer(self.vocab_file) features = [ {"input_ids": [0, 1, 2, 3, 4], "token_type_ids": [0, 1, 2, 3, 4], "next_sentence_label": i} for i in range(2) ] data_collator = DataCollatorForLanguageModeling(tokenizer, return_tensors="np") batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, (2, 5)) self.assertEqual(batch["token_type_ids"].shape, (2, 5)) self.assertEqual(batch["labels"].shape, (2, 5)) self.assertEqual(batch["next_sentence_label"].shape, (2,)) data_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8, return_tensors="np") batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, (2, 8)) self.assertEqual(batch["token_type_ids"].shape, (2, 8)) self.assertEqual(batch["labels"].shape, (2, 8)) self.assertEqual(batch["next_sentence_label"].shape, (2,)) def test_sop(self): tokenizer = BertTokenizer(self.vocab_file) features = [ { "input_ids": np.array([0, 1, 2, 3, 4]), "token_type_ids": np.array([0, 1, 2, 3, 4]), "sentence_order_label": i, } for i in range(2) ] data_collator = DataCollatorForLanguageModeling(tokenizer, return_tensors="np") batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, (2, 5)) self.assertEqual(batch["token_type_ids"].shape, (2, 5)) self.assertEqual(batch["labels"].shape, (2, 5)) self.assertEqual(batch["sentence_order_label"].shape, (2,)) data_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8, return_tensors="np") batch = data_collator(features) self.assertEqual(batch["input_ids"].shape, (2, 8)) self.assertEqual(batch["token_type_ids"].shape, (2, 8)) self.assertEqual(batch["labels"].shape, (2, 8)) self.assertEqual(batch["sentence_order_label"].shape, (2,)) class NumpyDataCollatorImmutabilityTest(unittest.TestCase): def setUp(self): self.tmpdirname = tempfile.mkdtemp() vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"] self.vocab_file = os.path.join(self.tmpdirname, "vocab.txt") with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) def tearDown(self): shutil.rmtree(self.tmpdirname) def _turn_to_none(self, item): """used to convert `item` to `None` type""" return None def _validate_original_data_against_collated_data(self, collator, original_data, batch_data): # we only care about side effects, the results are tested elsewhere collator(batch_data) # we go through every item and convert to `primitive` datatypes if necessary # then compares for equivalence for the original data and the data that has been passed through the collator for original, batch in zip(original_data, batch_data): for original_val, batch_val in zip(original.values(), batch.values()): if isinstance(original_val, np.ndarray): self.assertEqual(original_val.tolist(), batch_val.tolist()) else: self.assertEqual(original_val, batch_val) def _validate_original_data_against_collated_data_on_specified_keys_and_datatypes( self, collator, base_data, input_key, input_datatype, label_key, label_datatype, ignore_label=False ): # using the arguments to recreate the features with their respective (potentially new) datatypes features_original = [ {label_key: label_datatype(sample[label_key]), input_key: input_datatype(sample[input_key])} for sample in base_data ] features_batch = [ {label_key: label_datatype(sample[label_key]), input_key: input_datatype(sample[input_key])} for sample in base_data ] # some collators do not use labels, or sometimes we want to check if the collator with labels can handle such cases if ignore_label: for original, batch in zip(features_original, features_batch): original.pop(label_key) batch.pop(label_key) self._validate_original_data_against_collated_data( collator=collator, original_data=features_original, batch_data=features_batch ) def test_default_collator_immutability(self): features_base_single_label = [{"label": i, "inputs": (0, 1, 2, 3, 4, 5)} for i in range(4)] features_base_multiple_labels = [{"label": (0, 1, 2), "inputs": (0, 1, 2, 3, 4, 5)} for i in range(4)] for datatype_input, datatype_label in [ (list, int), (list, float), (np.array, int), (np.array, np.array), (list, self._turn_to_none), ]: self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( collator=lambda x: default_data_collator(x, return_tensors="np"), base_data=features_base_single_label, input_key="inputs", input_datatype=datatype_input, label_key="label", label_datatype=datatype_label, ) for datatype_input, datatype_label in [(list, list), (list, self._turn_to_none)]: self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( collator=lambda x: default_data_collator(x, return_tensors="np"), base_data=features_base_multiple_labels, input_key="inputs", input_datatype=datatype_input, label_key="label", label_datatype=datatype_label, ) features_base_single_label_alt = [{"input_ids": (0, 1, 2, 3, 4), "label": float(i)} for i in range(4)] self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( collator=lambda x: default_data_collator(x, return_tensors="np"), base_data=features_base_single_label_alt, input_key="input_ids", input_datatype=list, label_key="label", label_datatype=float, ) def test_with_padding_collator_immutability(self): tokenizer = BertTokenizer(self.vocab_file) features_original = [{"input_ids": [0, 1, 2]}, {"input_ids": [0, 1, 2, 3, 4, 5]}] features_batch = [{"input_ids": [0, 1, 2]}, {"input_ids": [0, 1, 2, 3, 4, 5]}] data_collator = DataCollatorWithPadding(tokenizer, padding="max_length", max_length=10, return_tensors="np") self._validate_original_data_against_collated_data( collator=data_collator, original_data=features_original, batch_data=features_batch ) data_collator = DataCollatorWithPadding(tokenizer, pad_to_multiple_of=8, return_tensors="np") self._validate_original_data_against_collated_data( collator=data_collator, original_data=features_original, batch_data=features_batch ) def test_for_token_classification_collator_immutability(self): tokenizer = BertTokenizer(self.vocab_file) features_base = [ {"input_ids": (0, 1, 2), "labels": (0, 1, 2)}, {"input_ids": (0, 1, 2, 3, 4, 5), "labels": (0, 1, 2, 3, 4, 5)}, ] token_classification_collators = [ DataCollatorForTokenClassification(tokenizer, return_tensors="np"), DataCollatorForTokenClassification(tokenizer, padding="max_length", max_length=10, return_tensors="np"), DataCollatorForTokenClassification(tokenizer, pad_to_multiple_of=8, return_tensors="np"), DataCollatorForTokenClassification(tokenizer, label_pad_token_id=-1, return_tensors="np"), ] for datatype_input, datatype_label in [(list, list)]: for collator in token_classification_collators: self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( collator=collator, base_data=features_base, input_key="input_ids", input_datatype=datatype_input, label_key="labels", label_datatype=datatype_label, ) self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( collator=token_classification_collators[-1], base_data=features_base, input_key="input_ids", input_datatype=datatype_input, label_key="labels", label_datatype=datatype_label, ignore_label=True, ) def test_seq2seq_collator_immutability(self): tokenizer = BertTokenizer(self.vocab_file) features_base = [ {"input_ids": list(range(3)), "labels": list(range(3))}, {"input_ids": list(range(6)), "labels": list(range(6))}, ] seq2seq_collators = [ DataCollatorForSeq2Seq(tokenizer, padding=PaddingStrategy.LONGEST, return_tensors="np"), DataCollatorForSeq2Seq(tokenizer, padding=PaddingStrategy.MAX_LENGTH, max_length=7, return_tensors="np"), DataCollatorForSeq2Seq( tokenizer, padding=PaddingStrategy.LONGEST, pad_to_multiple_of=8, return_tensors="np" ), DataCollatorForSeq2Seq( tokenizer, padding=PaddingStrategy.LONGEST, label_pad_token_id=-1, return_tensors="np" ), ] for datatype_input, datatype_label in [(list, list)]: for collator in seq2seq_collators: self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( collator=collator, base_data=features_base, input_key="input_ids", input_datatype=datatype_input, label_key="labels", label_datatype=datatype_label, ) self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( collator=seq2seq_collators[-1], base_data=features_base, input_key="input_ids", input_datatype=datatype_input, label_key="labels", label_datatype=datatype_label, ignore_label=True, ) features_base_no_pad = [ {"input_ids": list(range(3)), "labels": list(range(3))}, {"input_ids": list(range(3)), "labels": list(range(3))}, ] seq2seq_no_padding_collator = DataCollatorForSeq2Seq( tokenizer, padding=PaddingStrategy.DO_NOT_PAD, return_tensors="np" ) for datatype_input, datatype_label in [(list, list)]: self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( collator=seq2seq_no_padding_collator, base_data=features_base_no_pad, input_key="input_ids", input_datatype=datatype_input, label_key="labels", label_datatype=datatype_label, ) def test_language_modelling_collator_immutability(self): tokenizer = BertTokenizer(self.vocab_file) features_base_no_pad = [ {"input_ids": tuple(range(10)), "labels": (1,)}, {"input_ids": tuple(range(10)), "labels": (1,)}, ] features_base_pad = [ {"input_ids": tuple(range(5)), "labels": (1,)}, {"input_ids": tuple(range(5)), "labels": (1,)}, ] lm_collators = [ DataCollatorForLanguageModeling(tokenizer, mlm=False, return_tensors="np"), DataCollatorForLanguageModeling(tokenizer, mlm=False, pad_to_multiple_of=8, return_tensors="np"), DataCollatorForLanguageModeling(tokenizer, return_tensors="np"), DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8, return_tensors="np"), ] for datatype_input, datatype_label in [(list, list)]: for collator in lm_collators: self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( collator=collator, base_data=features_base_no_pad, input_key="input_ids", input_datatype=datatype_input, label_key="labels", label_datatype=datatype_label, ignore_label=True, ) self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( collator=collator, base_data=features_base_pad, input_key="input_ids", input_datatype=datatype_input, label_key="labels", label_datatype=datatype_label, ignore_label=True, ) def test_whole_world_masking_collator_immutability(self): tokenizer = BertTokenizer(self.vocab_file) features_base = [ {"input_ids": list(range(10)), "labels": (1,)}, {"input_ids": list(range(10)), "labels": (1,)}, ] whole_word_masking_collator = DataCollatorForWholeWordMask(tokenizer, return_tensors="np") for datatype_input, datatype_label in [(list, list), (np.array, np.array)]: self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( collator=whole_word_masking_collator, base_data=features_base, input_key="input_ids", input_datatype=datatype_input, label_key="labels", label_datatype=datatype_label, ignore_label=True, ) def test_permutation_language_modelling_collator_immutability(self): tokenizer = BertTokenizer(self.vocab_file) plm_collator = DataCollatorForPermutationLanguageModeling(tokenizer, return_tensors="np") no_pad_features_original = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] no_pad_features_batch = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] self._validate_original_data_against_collated_data( collator=plm_collator, original_data=no_pad_features_original, batch_data=no_pad_features_batch ) pad_features_original = [{"input_ids": list(range(5))}, {"input_ids": list(range(10))}] pad_features_batch = [{"input_ids": list(range(5))}, {"input_ids": list(range(10))}] self._validate_original_data_against_collated_data( collator=plm_collator, original_data=pad_features_original, batch_data=pad_features_batch ) def test_next_sentence_prediction_collator_immutability(self): tokenizer = BertTokenizer(self.vocab_file) features_original = [ {"input_ids": [0, 1, 2, 3, 4], "token_type_ids": [0, 1, 2, 3, 4], "next_sentence_label": i} for i in range(2) ] features_batch = [ {"input_ids": [0, 1, 2, 3, 4], "token_type_ids": [0, 1, 2, 3, 4], "next_sentence_label": i} for i in range(2) ] nsp_collator = DataCollatorForLanguageModeling(tokenizer, return_tensors="np") self._validate_original_data_against_collated_data( collator=nsp_collator, original_data=features_original, batch_data=features_batch ) nsp_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8, return_tensors="np") self._validate_original_data_against_collated_data( collator=nsp_collator, original_data=features_original, batch_data=features_batch ) def test_sentence_order_prediction_collator_immutability(self): tokenizer = BertTokenizer(self.vocab_file) features_original = [ { "input_ids": np.array([0, 1, 2, 3, 4]), "token_type_ids": np.array([0, 1, 2, 3, 4]), "sentence_order_label": i, } for i in range(2) ] features_batch = [ { "input_ids": np.array([0, 1, 2, 3, 4]), "token_type_ids": np.array([0, 1, 2, 3, 4]), "sentence_order_label": i, } for i in range(2) ] sop_collator = DataCollatorForLanguageModeling(tokenizer, return_tensors="np") self._validate_original_data_against_collated_data( collator=sop_collator, original_data=features_original, batch_data=features_batch ) sop_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8, return_tensors="np") self._validate_original_data_against_collated_data( collator=sop_collator, original_data=features_original, batch_data=features_batch )
transformers/tests/trainer/test_data_collator.py/0
{ "file_path": "transformers/tests/trainer/test_data_collator.py", "repo_id": "transformers", "token_count": 40181 }
609
# Copyright 2020 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 unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from transformers.activations import gelu_new, gelu_python, get_activation @require_torch class TestActivations(unittest.TestCase): def test_gelu_versions(self): x = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100]) torch_builtin = get_activation("gelu") torch.testing.assert_close(gelu_python(x), torch_builtin(x)) self.assertFalse(torch.allclose(gelu_python(x), gelu_new(x))) def test_gelu_10(self): x = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100]) torch_builtin = get_activation("gelu") gelu10 = get_activation("gelu_10") y_gelu = torch_builtin(x) y_gelu_10 = gelu10(x) clipped_mask = torch.where(y_gelu_10 < 10.0, 1, 0) self.assertTrue(torch.max(y_gelu_10).item() == 10.0) torch.testing.assert_close(y_gelu * clipped_mask, y_gelu_10 * clipped_mask) def test_get_activation(self): get_activation("gelu") get_activation("gelu_10") get_activation("gelu_fast") get_activation("gelu_new") get_activation("gelu_python") get_activation("gelu_pytorch_tanh") get_activation("linear") get_activation("mish") get_activation("quick_gelu") get_activation("relu") get_activation("sigmoid") get_activation("silu") get_activation("swish") get_activation("tanh") with self.assertRaises(KeyError): get_activation("bogus") with self.assertRaises(KeyError): get_activation(None) def test_activations_are_distinct_objects(self): act1 = get_activation("gelu") act1.a = 1 act2 = get_activation("gelu") self.assertEqual(act1.a, 1) with self.assertRaises(AttributeError): _ = act2.a
transformers/tests/utils/test_activations.py/0
{ "file_path": "transformers/tests/utils/test_activations.py", "repo_id": "transformers", "token_count": 1055 }
610
# Copyright 2020 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 contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_torch from transformers.utils import ContextManagers, find_labels, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification MODEL_ID = DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co REVISION_ID_DEFAULT = "main" # Default branch name REVISION_ID_ONE_SPECIFIC_COMMIT = "f2c752cfc5c0ab6f4bdec59acea69eefbee381c2" # One particular commit (not the top of `main`) REVISION_ID_INVALID = "aaaaaaa" # This commit does not exist, so we should 404. PINNED_SHA1 = "d9e9f15bc825e4b2c9249e9578f884bbcb5e3684" # Sha-1 of config.json on the top of `main`, for checking purposes PINNED_SHA256 = "4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3" # Sha-256 of pytorch_model.bin on the top of `main`, for checking purposes # Dummy contexts to test `ContextManagers` @contextlib.contextmanager def context_en(): print("Welcome!") yield print("Bye!") @contextlib.contextmanager def context_fr(): print("Bonjour!") yield print("Au revoir!") class TestImportMechanisms(unittest.TestCase): def test_module_spec_available(self): # If the spec is missing, importlib would not be able to import the module dynamically. assert transformers.__spec__ is not None assert importlib.util.find_spec("transformers") is not None class GenericUtilTests(unittest.TestCase): @unittest.mock.patch("sys.stdout", new_callable=io.StringIO) def test_context_managers_no_context(self, mock_stdout): with ContextManagers([]): print("Transformers are awesome!") # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue(), "Transformers are awesome!\n") @unittest.mock.patch("sys.stdout", new_callable=io.StringIO) def test_context_managers_one_context(self, mock_stdout): with ContextManagers([context_en()]): print("Transformers are awesome!") # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue(), "Welcome!\nTransformers are awesome!\nBye!\n") @unittest.mock.patch("sys.stdout", new_callable=io.StringIO) def test_context_managers_two_context(self, mock_stdout): with ContextManagers([context_fr(), context_en()]): print("Transformers are awesome!") # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue(), "Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n") @require_torch def test_find_labels_pt(self): self.assertEqual(find_labels(BertForSequenceClassification), ["labels"]) self.assertEqual(find_labels(BertForPreTraining), ["labels", "next_sentence_label"]) self.assertEqual(find_labels(BertForQuestionAnswering), ["start_positions", "end_positions"]) # find_labels works regardless of the class name (it detects the framework through inheritance) class DummyModel(BertForSequenceClassification): pass self.assertEqual(find_labels(DummyModel), ["labels"])
transformers/tests/utils/test_file_utils.py/0
{ "file_path": "transformers/tests/utils/test_file_utils.py", "repo_id": "transformers", "token_count": 1449 }
611
# Copyright 2019-present, the HuggingFace Inc. team. # # 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. # # # # this test validates that we can stack skip decorators in groups and whether # they work correctly with other decorators # # since the decorators have already built their decision params (like checking # env[], we can't mock the env and test each of the combinations), so ideally # the following 4 should be run. But since we have different CI jobs running # different configs, all combinations should get covered # # RUN_SLOW=1 pytest -rA tests/test_skip_decorators.py # RUN_SLOW=1 CUDA_VISIBLE_DEVICES="" pytest -rA tests/test_skip_decorators.py # RUN_SLOW=0 pytest -rA tests/test_skip_decorators.py # RUN_SLOW=0 CUDA_VISIBLE_DEVICES="" pytest -rA tests/test_skip_decorators.py import os import unittest import pytest from parameterized import parameterized from transformers.testing_utils import require_torch, require_torch_accelerator, slow, torch_device # skipping in unittest tests params = [(1,)] # test that we can stack our skip decorators with 3rd party decorators def check_slow(): run_slow = bool(os.getenv("RUN_SLOW", "0")) if run_slow: assert True else: assert False, "should have been skipped" # test that we can stack our skip decorators def check_slow_torch_cuda(): run_slow = bool(os.getenv("RUN_SLOW", "0")) if run_slow and torch_device == "cuda": assert True else: assert False, "should have been skipped" def check_slow_torch_accelerator(): run_slow = bool(os.getenv("RUN_SLOW", "0")) assert run_slow and torch_device in ["cuda", "xpu"], "should have been skipped" @require_torch class SkipTester(unittest.TestCase): @slow @require_torch_accelerator def test_2_skips_slow_first(self): check_slow_torch_accelerator() @require_torch_accelerator @slow def test_2_skips_slow_last(self): check_slow_torch_accelerator() # The combination of any skip decorator, followed by parameterized fails to skip the tests # 1. @slow manages to correctly skip `test_param_slow_first` # 2. but then `parameterized` creates new tests, with a unique name for each parameter groups. # It has no idea that they are to be skipped and so they all run, ignoring @slow # Therefore skip decorators must come after `parameterized` # # @slow # @parameterized.expand(params) # def test_param_slow_first(self, param=None): # check_slow() # This works as expected: # 1. `parameterized` creates new tests with unique names # 2. each of them gets an opportunity to be skipped @parameterized.expand(params) @slow def test_param_slow_last(self, param=None): check_slow() # skipping in non-unittest tests # no problem at all here @slow @require_torch_accelerator def test_pytest_2_skips_slow_first(): check_slow_torch_accelerator() @require_torch_accelerator @slow def test_pytest_2_skips_slow_last(): check_slow_torch_accelerator() @slow @pytest.mark.parametrize("param", [1]) def test_pytest_param_slow_first(param): check_slow() @pytest.mark.parametrize("param", [1]) @slow def test_pytest_param_slow_last(param): check_slow()
transformers/tests/utils/test_skip_decorators.py/0
{ "file_path": "transformers/tests/utils/test_skip_decorators.py", "repo_id": "transformers", "token_count": 1288 }
612
# coding=utf-8 # Copyright 2020 The HuggingFace Inc. team. # # 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. """ Utility that checks the custom inits of Transformers are well-defined: Transformers uses init files that delay the import of an object to when it's actually needed. This is to avoid the main init importing all models, which would make the line `import transformers` very slow when the user has all optional dependencies installed. The inits with delayed imports have two halves: one defining a dictionary `_import_structure` which maps modules to the name of the objects in each module, and one in `TYPE_CHECKING` which looks like a normal init for type-checkers. The goal of this script is to check the objects defined in both halves are the same. This also checks the main init properly references all submodules, even if it doesn't import anything from them: every submodule should be defined as a key of `_import_structure`, with an empty list as value potentially, or the submodule won't be importable. Use from the root of the repo with: ```bash python utils/check_inits.py ``` for a check that will error in case of inconsistencies (used by `make repo-consistency`). There is no auto-fix possible here sadly :-( """ import collections import os import re from pathlib import Path from typing import Optional # Path is set with the intent you should run this script from the root of the repo. PATH_TO_TRANSFORMERS = "src/transformers" # Matches is_xxx_available() _re_backend = re.compile(r"is\_([a-z_]*)_available()") # Catches a one-line _import_struct = {xxx} _re_one_line_import_struct = re.compile(r"^_import_structure\s+=\s+\{([^\}]+)\}") # Catches a line with a key-values pattern: "bla": ["foo", "bar"] _re_import_struct_key_value = re.compile(r'\s+"\S*":\s+\[([^\]]*)\]') # Catches a line if not is_foo_available _re_test_backend = re.compile(r"^\s*if\s+not\s+is\_[a-z_]*\_available\(\)") # Catches a line _import_struct["bla"].append("foo") _re_import_struct_add_one = re.compile(r'^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] _re_import_struct_add_many = re.compile(r"^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]") # Catches a line with an object between quotes and a comma: "MyModel", _re_quote_object = re.compile(r'^\s+"([^"]+)",') # Catches a line with objects between brackets only: ["foo", "bar"], _re_between_brackets = re.compile(r"^\s+\[([^\]]+)\]") # Catches a line with from foo import bar, bla, boo _re_import = re.compile(r"\s+from\s+\S*\s+import\s+([^\(\s].*)\n") # Catches a line with try: _re_try = re.compile(r"^\s*try:") # Catches a line with else: _re_else = re.compile(r"^\s*else:") def find_backend(line: str) -> Optional[str]: """ Find one (or multiple) backend in a code line of the init. Args: line (`str`): A code line of the main init. Returns: Optional[`str`]: If one (or several) backend is found, returns it. In the case of multiple backends (the line contains `if is_xxx_available() and `is_yyy_available()`) returns all backends joined on `_and_` (so `xxx_and_yyy` for instance). """ if _re_test_backend.search(line) is None: return None backends = [b[0] for b in _re_backend.findall(line)] backends.sort() return "_and_".join(backends) def parse_init(init_file) -> Optional[tuple[dict[str, list[str]], dict[str, list[str]]]]: """ Read an init_file and parse (per backend) the `_import_structure` objects defined and the `TYPE_CHECKING` objects defined. Args: init_file (`str`): Path to the init file to inspect. Returns: `Optional[Tuple[Dict[str, List[str]], Dict[str, List[str]]]]`: A tuple of two dictionaries mapping backends to list of imported objects, one for the `_import_structure` part of the init and one for the `TYPE_CHECKING` part of the init. Returns `None` if the init is not a custom init. """ with open(init_file, "r", encoding="utf-8", newline="\n") as f: lines = f.readlines() # Get the to `_import_structure` definition. line_index = 0 while line_index < len(lines) and not lines[line_index].startswith("_import_structure = {"): line_index += 1 # If this is a traditional init, just return. if line_index >= len(lines): return None # First grab the objects without a specific backend in _import_structure objects = [] while not lines[line_index].startswith("if TYPE_CHECKING") and find_backend(lines[line_index]) is None: line = lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(line): content = _re_one_line_import_struct.search(line).groups()[0] imports = re.findall(r"\[([^\]]+)\]", content) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(", ")]) line_index += 1 continue single_line_import_search = _re_import_struct_key_value.search(line) if single_line_import_search is not None: imports = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(", ") if len(obj) > 0] objects.extend(imports) elif line.startswith(" " * 8 + '"'): objects.append(line[9:-3]) line_index += 1 # Those are stored with the key "none". import_dict_objects = {"none": objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith("if TYPE_CHECKING"): # If the line is an if not is_backend_available, we grab all objects associated. backend = find_backend(lines[line_index]) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1]) is None: backend = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index]) is None: line_index += 1 line_index += 1 objects = [] # Until we unindent, add backend objects to the list while len(lines[line_index]) <= 1 or lines[line_index].startswith(" " * 4): line = lines[line_index] if _re_import_struct_add_one.search(line) is not None: objects.append(_re_import_struct_add_one.search(line).groups()[0]) elif _re_import_struct_add_many.search(line) is not None: imports = _re_import_struct_add_many.search(line).groups()[0].split(", ") imports = [obj[1:-1] for obj in imports if len(obj) > 0] objects.extend(imports) elif _re_between_brackets.search(line) is not None: imports = _re_between_brackets.search(line).groups()[0].split(", ") imports = [obj[1:-1] for obj in imports if len(obj) > 0] objects.extend(imports) elif _re_quote_object.search(line) is not None: objects.append(_re_quote_object.search(line).groups()[0]) elif line.startswith(" " * 8 + '"'): objects.append(line[9:-3]) elif line.startswith(" " * 12 + '"'): objects.append(line[13:-3]) line_index += 1 import_dict_objects[backend] = objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend objects = [] while ( line_index < len(lines) and find_backend(lines[line_index]) is None and not lines[line_index].startswith("else") ): line = lines[line_index] single_line_import_search = _re_import.search(line) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(", ")) elif line.startswith(" " * 8): objects.append(line[8:-2]) line_index += 1 type_hint_objects = {"none": objects} # Let's continue with backend-specific objects while line_index < len(lines): # If the line is an if is_backend_available, we grab all objects associated. backend = find_backend(lines[line_index]) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1]) is None: backend = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index]) is None: line_index += 1 line_index += 1 objects = [] # Until we unindent, add backend objects to the list while len(lines[line_index]) <= 1 or lines[line_index].startswith(" " * 8): line = lines[line_index] single_line_import_search = _re_import.search(line) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(", ")) elif line.startswith(" " * 12): objects.append(line[12:-2]) line_index += 1 type_hint_objects[backend] = objects else: line_index += 1 return import_dict_objects, type_hint_objects def analyze_results(import_dict_objects: dict[str, list[str]], type_hint_objects: dict[str, list[str]]) -> list[str]: """ Analyze the differences between _import_structure objects and TYPE_CHECKING objects found in an init. Args: import_dict_objects (`Dict[str, List[str]]`): A dictionary mapping backend names (`"none"` for the objects independent of any specific backend) to list of imported objects. type_hint_objects (`Dict[str, List[str]]`): A dictionary mapping backend names (`"none"` for the objects independent of any specific backend) to list of imported objects. Returns: `List[str]`: The list of errors corresponding to mismatches. """ def find_duplicates(seq): return [k for k, v in collections.Counter(seq).items() if v > 1] # If one backend is missing from the other part of the init, error early. if list(import_dict_objects.keys()) != list(type_hint_objects.keys()): return ["Both sides of the init do not have the same backends!"] errors = [] # Find all errors. for key in import_dict_objects: # Duplicate imports in any half. duplicate_imports = find_duplicates(import_dict_objects[key]) if duplicate_imports: errors.append(f"Duplicate _import_structure definitions for: {duplicate_imports}") duplicate_type_hints = find_duplicates(type_hint_objects[key]) if duplicate_type_hints: errors.append(f"Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}") # Missing imports in either part of the init. if sorted(set(import_dict_objects[key])) != sorted(set(type_hint_objects[key])): name = "base imports" if key == "none" else f"{key} backend" errors.append(f"Differences for {name}:") for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(f" {a} in TYPE_HINT but not in _import_structure.") for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(f" {a} in _import_structure but not in TYPE_HINT.") return errors def get_transformers_submodules() -> list[str]: """ Returns the list of Transformers submodules. """ submodules = [] for path, directories, files in os.walk(PATH_TO_TRANSFORMERS): for folder in directories: # Ignore private modules if folder.startswith("_"): directories.remove(folder) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(path) / folder).glob("*.py"))) == 0: continue short_path = str((Path(path) / folder).relative_to(PATH_TO_TRANSFORMERS)) submodule = short_path.replace(os.path.sep, ".") submodules.append(submodule) for fname in files: if fname == "__init__.py": continue short_path = str((Path(path) / fname).relative_to(PATH_TO_TRANSFORMERS)) submodule = short_path.replace(".py", "").replace(os.path.sep, ".") if len(submodule.split(".")) == 1: submodules.append(submodule) return submodules IGNORE_SUBMODULES = [ "convert_pytorch_checkpoint_to_tf2", "modeling_flax_pytorch_utils", "models.esm.openfold_utils", "modeling_attn_mask_utils", "safetensors_conversion", "modeling_gguf_pytorch_utils", "kernels.falcon_mamba", "kernels", ] def check_submodules(): """ Check all submodules of Transformers are properly registered in the main init. Error otherwise. """ # This is to make sure the transformers module imported is the one in the repo. from transformers.utils import direct_transformers_import transformers = direct_transformers_import(PATH_TO_TRANSFORMERS) import_structure_keys = set(transformers._import_structure.keys()) # This contains all the base keys of the _import_structure object defined in the init, but if the user is missing # some optional dependencies, they may not have all of them. Thus we read the init to read all additions and # (potentiall re-) add them. with open(os.path.join(PATH_TO_TRANSFORMERS, "__init__.py"), "r") as f: init_content = f.read() import_structure_keys.update(set(re.findall(r"import_structure\[\"([^\"]*)\"\]", init_content))) module_not_registered = [ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in import_structure_keys ] if len(module_not_registered) > 0: list_of_modules = "\n".join(f"- {module}" for module in module_not_registered) raise ValueError( "The following submodules are not properly registered in the main init of Transformers:\n" f"{list_of_modules}\n" "Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value." ) if __name__ == "__main__": # This entire files needs an overhaul pass
transformers/utils/check_inits.py/0
{ "file_path": "transformers/utils/check_inits.py", "repo_id": "transformers", "token_count": 6227 }
613
from huggingface_hub import hf_hub_download from transformers.testing_utils import _run_pipeline_tests if __name__ == "__main__": if _run_pipeline_tests: import datasets _ = datasets.load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") _ = datasets.load_dataset("hf-internal-testing/fixtures_image_utils", split="test", revision="refs/pr/1") _ = hf_hub_download(repo_id="nateraw/video-demo", filename="archery.mp4", repo_type="dataset")
transformers/utils/fetch_hub_objects_for_ci.py/0
{ "file_path": "transformers/utils/fetch_hub_objects_for_ci.py", "repo_id": "transformers", "token_count": 203 }
614
# Copyright 2024 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. """ This script is used to get the models for which to run slow CI. A new model added in a pull request will be included, as well as models specified in a GitHub pull request's comment with a prefix `run-slow`, `run_slow` or `run slow`. For example, the commit message `run_slow: bert, gpt2` will give `bert` and `gpt2`. Usage: ```bash python utils/pr_slow_ci_models.py ``` """ import argparse import os.path import re import string from pathlib import Path from git import Repo PATH_TO_REPO = Path(__file__).parent.parent.resolve() def get_new_python_files_between_commits(base_commit: str, commits: list[str]) -> list[str]: """ Get the list of added python files between a base commit and one or several commits. Args: repo (`git.Repo`): A git repository (for instance the Transformers repo). base_commit (`str`): The commit reference of where to compare for the diff. This is the current commit, not the branching point! commits (`List[str]`): The list of commits with which to compare the repo at `base_commit` (so the branching point). Returns: `List[str]`: The list of python files added between a base commit and one or several commits. """ code_diff = [] for commit in commits: for diff_obj in commit.diff(base_commit): # We always add new python files if diff_obj.change_type == "A" and diff_obj.b_path.endswith(".py"): code_diff.append(diff_obj.b_path) return code_diff def get_new_python_files(diff_with_last_commit=False) -> list[str]: """ Return a list of python files that have been added between the current head and the main branch. Returns: `List[str]`: The list of python files added. """ repo = Repo(PATH_TO_REPO) try: # For the cases where the main branch exists locally main = repo.refs.main except AttributeError: # On GitHub Actions runners, it doesn't have local main branch main = repo.remotes.origin.refs.main if not diff_with_last_commit: print(f"main is at {main.commit}") print(f"Current head is at {repo.head.commit}") commits = repo.merge_base(main, repo.head) for commit in commits: print(f"Branching commit: {commit}") else: print(f"main is at {main.commit}") commits = main.commit.parents for commit in commits: print(f"Parent commit: {commit}") return get_new_python_files_between_commits(repo.head.commit, commits) def get_new_model(diff_with_last_commit=False): new_files = get_new_python_files(diff_with_last_commit) reg = re.compile(r"src/transformers/models/(.*)/modeling_.*\.py") new_model = "" for x in new_files: find_new_model = reg.findall(x) if len(find_new_model) > 0: new_model = find_new_model[0] # It's unlikely we have 2 new modeling files in a pull request. break return new_model def parse_message(message: str) -> str: """ Parses a GitHub pull request's comment to find the models specified in it to run slow CI. Args: message (`str`): The body of a GitHub pull request's comment. Returns: `str`: The substring in `message` after `run-slow`, run_slow` or run slow`. If no such prefix is found, the empty string is returned. """ if message is None: return "" message = message.strip().lower() # run-slow: model_1, model_2 if not message.startswith(("run-slow", "run_slow", "run slow")): return "" message = message[len("run slow") :] # remove leading `:` while message.strip().startswith(":"): message = message.strip()[1:] return message def get_models(message: str): models = parse_message(message) return models.replace(",", " ").split() def check_model_names(model_name: str): allowed = string.ascii_letters + string.digits + "_" return not (model_name.startswith("_") or model_name.endswith("_")) and all(c in allowed for c in model_name) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--message", type=str, default="", help="The content of a comment.") parser.add_argument("--quantization", action="store_true", help="If we collect quantization tests") args = parser.parse_args() new_model = get_new_model() specified_models = get_models(args.message) models = ([] if new_model == "" else [new_model]) + specified_models # a guard for strange model names models = [model for model in models if check_model_names(model)] # Add prefix final_list = [] for model in models: if not args.quantization: if os.path.isdir(f"tests/models/{model}"): final_list.append(f"models/{model}") elif os.path.isdir(f"tests/{model}") and model != "quantization": final_list.append(model) elif os.path.isdir(f"tests/quantization/{model}"): final_list.append(f"quantization/{model}") print(sorted(set(final_list)))
transformers/utils/pr_slow_ci_models.py/0
{ "file_path": "transformers/utils/pr_slow_ci_models.py", "repo_id": "transformers", "token_count": 2151 }
615
import torch from transformers import PreTrainedModel from .custom_configuration import CustomConfig class CustomModel(PreTrainedModel): config_class = CustomConfig def __init__(self, config): super().__init__(config) self.linear = torch.nn.Linear(config.hidden_size, config.hidden_size) def forward(self, x): return self.linear(x) def _init_weights(self, module): pass
transformers/utils/test_module/custom_modeling.py/0
{ "file_path": "transformers/utils/test_module/custom_modeling.py", "repo_id": "transformers", "token_count": 154 }
616
#!/bin/bash # This script runs an SFT example end-to-end on a tiny model using different possible configurations # but defaults to QLoRA + PEFT OUTPUT_DIR="test_dpo/" MODEL_NAME="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" DATASET_NAME="trl-internal-testing/hh-rlhf-helpful-base-trl-style" MAX_STEPS=5 BATCH_SIZE=2 SEQ_LEN=128 # Handle extra arguments in case one passes accelerate configs. EXTRA_ACCELERATE_ARGS="" EXTRA_TRAINING_ARGS="""--use_peft \ --load_in_4bit """ # This is a hack to get the number of available GPUs NUM_GPUS=2 if [[ "${TRL_ACCELERATE_CONFIG}" == "" ]]; then EXTRA_ACCELERATE_ARGS="" else EXTRA_ACCELERATE_ARGS="--config_file $TRL_ACCELERATE_CONFIG" # For DeepSpeed configs we need to set the `--fp16` flag to comply with our configs exposed # on `examples/accelerate_configs` and our runners do not support bf16 mixed precision training. if [[ $TRL_ACCELERATE_CONFIG == *"deepspeed"* ]]; then EXTRA_TRAINING_ARGS="--fp16" else echo "Keeping QLoRA + PEFT" fi fi CMD=""" accelerate launch $EXTRA_ACCELERATE_ARGS \ --num_processes $NUM_GPUS \ --mixed_precision 'fp16' \ `pwd`/trl/scripts/dpo.py \ --model_name_or_path $MODEL_NAME \ --dataset_name $DATASET_NAME \ --output_dir $OUTPUT_DIR \ --max_steps $MAX_STEPS \ --per_device_train_batch_size $BATCH_SIZE \ --max_length $SEQ_LEN \ $EXTRA_TRAINING_ARGS """ echo "Starting program..." { # try echo $CMD eval "$CMD" } || { # catch # save log for exception echo "Operation Failed!" exit 1 } exit 0
trl/commands/run_dpo.sh/0
{ "file_path": "trl/commands/run_dpo.sh", "repo_id": "trl", "token_count": 646 }
617
# DeepSpeed Integration <Tip warning={true}> Section under construction. Feel free to contribute! </Tip> TRL supports training with DeepSpeed, a library that implements advanced training optimization techniques. These include optimizer state partitioning, offloading, gradient partitioning, and more. DeepSpeed integrates the [Zero Redundancy Optimizer (ZeRO)](https://huggingface.co/papers/1910.02054), which allows to scale the model size proportional to the number of devices with sustained high efficiency. ![ZeRO Stages](https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/zero_stages.png) ## Installation To use DeepSpeed with TRL, install it using the following command: ```bash pip install deepspeed ``` ## Running Training Scripts with DeepSpeed No modifications to your training script are required. Simply run it with the DeepSpeed configuration file: ```bash accelerate launch --config_file <ACCELERATE_WITH_DEEPSPEED_CONFIG_FILE.yaml> train.py ``` We provide ready-to-use DeepSpeed configuration files in the [`examples/accelerate_configs`](https://github.com/huggingface/trl/tree/main/examples/accelerate_configs) directory. For example, to run training with ZeRO Stage 2, use the following command: ```bash accelerate launch --config_file examples/accelerate_configs/deepspeed_zero2.yaml train.py ``` ## Additional Resources Consult the 🤗 Accelerate [documentation](https://huggingface.co/docs/accelerate/usage_guides/deepspeed) for more information about the DeepSpeed plugin.
trl/docs/source/deepspeed_integration.md/0
{ "file_path": "trl/docs/source/deepspeed_integration.md", "repo_id": "trl", "token_count": 434 }
618
# Models With the `AutoModelForCausalLMWithValueHead` class TRL supports all decoder model architectures in transformers such as GPT-2, OPT, and GPT-Neo. In addition, with `AutoModelForSeq2SeqLMWithValueHead` you can use encoder-decoder architectures such as T5. TRL also requires reference models which are frozen copies of the model that is trained. With `create_reference_model` you can easily create a frozen copy and also share layers between the two models to save memory. ## PreTrainedModelWrapper [[autodoc]] PreTrainedModelWrapper ## AutoModelForCausalLMWithValueHead [[autodoc]] AutoModelForCausalLMWithValueHead - __init__ - forward - generate - _init_weights ## AutoModelForSeq2SeqLMWithValueHead [[autodoc]] AutoModelForSeq2SeqLMWithValueHead - __init__ - forward - generate - _init_weights ## create_reference_model [[autodoc]] create_reference_model
trl/docs/source/models.md/0
{ "file_path": "trl/docs/source/models.md", "repo_id": "trl", "token_count": 283 }
619
# Sentiment Tuning Examples The notebooks and scripts in this examples show how to fine-tune a model with a sentiment classifier (such as `lvwerra/distilbert-imdb`). Here's an overview of the notebooks and scripts in the [trl repository](https://github.com/huggingface/trl/tree/main/examples): | File | Description | |------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------| | [`examples/scripts/ppo.py`](https://github.com/huggingface/trl/blob/main/examples/scripts/ppo.py) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/trl/blob/main/examples/sentiment/notebooks/gpt2-sentiment.ipynb) | This script shows how to use the `PPOTrainer` to fine-tune a sentiment analysis model using IMDB dataset | | [`examples/notebooks/gpt2-sentiment.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/gpt2-sentiment.ipynb) | This notebook demonstrates how to reproduce the GPT2 imdb sentiment tuning example on a jupyter notebook. | | [`examples/notebooks/gpt2-control.ipynb`](https://github.com/huggingface/trl/tree/main/examples/notebooks/gpt2-control.ipynb) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/trl/blob/main/examples/sentiment/notebooks/gpt2-sentiment-control.ipynb) | This notebook demonstrates how to reproduce the GPT2 sentiment control example on a jupyter notebook. ## Usage ```bash # 1. run directly python examples/scripts/ppo.py # 2. run via `accelerate` (recommended), enabling more features (e.g., multiple GPUs, deepspeed) accelerate config # will prompt you to define the training configuration accelerate launch examples/scripts/ppo.py # launches training # 3. get help text and documentation python examples/scripts/ppo.py --help # 4. configure logging with wandb and, say, mini_batch_size=1 and gradient_accumulation_steps=16 python examples/scripts/ppo.py --log_with wandb --mini_batch_size 1 --gradient_accumulation_steps 16 ``` Note: if you don't want to log with `wandb` remove `log_with="wandb"` in the scripts/notebooks. You can also replace it with your favourite experiment tracker that's [supported by `accelerate`](https://huggingface.co/docs/accelerate/usage_guides/tracking). ## Few notes on multi-GPU To run in multi-GPU setup with DDP (distributed Data Parallel) change the `device_map` value to `device_map={"": Accelerator().process_index}` and make sure to run your script with `accelerate launch yourscript.py`. If you want to apply naive pipeline parallelism you can use `device_map="auto"`.
trl/docs/source/sentiment_tuning.md/0
{ "file_path": "trl/docs/source/sentiment_tuning.md", "repo_id": "trl", "token_count": 1080 }
620
# This is an example configuration file of TRL CLI, you can use it for # SFT like that: `trl sft --config config.yaml --output_dir test-sft` # The YAML file supports environment variables by adding an `env` field # as below # env: # CUDA_VISIBLE_DEVICES: 0 model_name_or_path: Qwen/Qwen2.5-0.5B dataset_name: stanfordnlp/imdb report_to: none learning_rate: 0.0001 lr_scheduler_type: cosine
trl/examples/cli_configs/example_config.yaml/0
{ "file_path": "trl/examples/cli_configs/example_config.yaml", "repo_id": "trl", "token_count": 158 }
621
# Research projects that use TRL Welcome to the research projects folder! Here you can find the scripts used for some research projects that used TRL and maintained by the developers and the community (LM de-toxification, Stack-Llama, etc.). Check out the READMEs in the subfolders for more information! - [De-detoxifying language models](https://github.com/huggingface/trl/tree/main/examples/research_projects/toxicity) - [Stack-Llama](https://github.com/huggingface/trl/tree/main/examples/research_projects/stack_llama) - [Stack-Llama-2](https://github.com/huggingface/trl/tree/main/examples/research_projects/stack_llama_2)
trl/examples/research_projects/README.md/0
{ "file_path": "trl/examples/research_projects/README.md", "repo_id": "trl", "token_count": 189 }
622
# 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 argparse import csv import evaluate import numpy as np import torch from datasets import load_dataset from tqdm import tqdm from transformers import AutoModelForCausalLM, AutoTokenizer, is_torch_npu_available, is_torch_xpu_available toxicity = evaluate.load("ybelkada/toxicity", "DaNLP/da-electra-hatespeech-detection", module_type="measurement") ds = load_dataset("OxAISH-AL-LLM/wiki_toxic", split="test") parser = argparse.ArgumentParser(description="Evaluate de-toxified models") parser.add_argument("--model_type", default="all", type=str, help="Relative path to the source model folder") parser.add_argument("--output_file", default="toxicity.csv", type=str, help="Relative path to the source model folder") parser.add_argument("--batch_size", default=64, type=int, help="Batch size") parser.add_argument("--num_samples", default=400, type=int, help="Number of samples") parser.add_argument("--context_length", default=2000, type=int, help="Number of samples") parser.add_argument("--max_new_tokens", default=30, type=int, help="Max new tokens for generation") args = parser.parse_args() if args.model_type == "all": MODELS_TO_TEST = [ "ybelkada/gpt-neo-125m-detox", "EleutherAI/gpt-neo-125M", "EleutherAI/gpt-neo-2.7B", "ybelkada/gpt-neo-2.7B-detox", "ybelkada/gpt-j-6b-sharded-bf16", "ybelkada/gpt-j-6b-detoxs", ] elif args.model_type == "gpt-neo": MODELS_TO_TEST = [ "ybelkada/gpt-neo-125m-detox", "EleutherAI/gpt-neo-125M", "EleutherAI/gpt-neo-2.7B", "ybelkada/gpt-neo-2.7B-detox", ] elif args.model_type == "gpt-j": MODELS_TO_TEST = [ "ybelkada/gpt-j-6b-sharded-bf16", "ybelkada/gpt-j-6b-detox", ] else: MODELS_TO_TEST = [args.model_type] NUM_SAMPLES = args.num_samples BATCH_SIZE = args.batch_size output_file = args.output_file max_new_tokens = args.max_new_tokens context_length = args.context_length if is_torch_xpu_available(): device = torch.xpu.current_device() elif is_torch_npu_available(): device = torch.npu.current_device() else: device = torch.cuda.current_device() if torch.cuda.is_available() else "cpu" # consider only toxic prompts ds = ds.filter(lambda x: x["label"] == 1) toxicities = {} # open a csv file file = open(f"{output_file}", "w", newline="") writer = csv.writer(file) # add first rows writer.writerow(["model_id", "mean_toxicity", "std_toxicity"]) for model_id in tqdm(MODELS_TO_TEST): model = AutoModelForCausalLM.from_pretrained(model_id, device_map={"": device}, torch_dtype=torch.bfloat16) tokenizer = AutoTokenizer.from_pretrained(model_id) tokenizer.pad_token = tokenizer.eos_token tokenizer.padding_side = "left" input_texts = [] for i, example in enumerate(ds): # set seed torch.manual_seed(42) input_text = example["comment_text"] input_texts.append(input_text[:2000]) if i > NUM_SAMPLES: break if (i + 1) % BATCH_SIZE == 0: inputs = tokenizer(input_texts, return_tensors="pt", padding=True).to(device) inputs.input_ids = inputs.input_ids[:context_length] inputs.attention_mask = inputs.attention_mask[:context_length] outputs = model.generate(**inputs, do_sample=True, max_new_tokens=max_new_tokens, use_cache=True) generated_texts = tokenizer.batch_decode(outputs, skip_special_tokens=True) generated_texts = [ generated_text.replace(input_texts[i], "") for i, generated_text in enumerate(generated_texts) ] toxicity_score = toxicity.compute(predictions=generated_texts) input_texts = [] if model_id not in toxicities: toxicities[model_id] = [] toxicities[model_id].extend(toxicity_score["toxicity"]) # last batch inputs = tokenizer(input_texts, return_tensors="pt", padding=True).to(device) outputs = model.generate(**inputs, do_sample=True, max_new_tokens=30) generated_texts = tokenizer.batch_decode(outputs, skip_special_tokens=True) generated_texts = [generated_text.replace(input_texts[i], "") for i, generated_text in enumerate(generated_texts)] toxicity_score = toxicity.compute(predictions=generated_texts) toxicities[model_id].extend(toxicity_score["toxicity"]) # compute mean & std using np mean = np.mean(toxicities[model_id]) std = np.std(toxicities[model_id]) # save to file writer.writerow([model_id, mean, std]) # print print(f"Model: {model_id} - Mean: {mean} - Std: {std}") model = None if is_torch_xpu_available(): torch.xpu.empty_cache() elif is_torch_npu_available(): torch.npu.empty_cache() else: torch.cuda.empty_cache() # close file file.close()
trl/examples/research_projects/toxicity/scripts/evaluate-toxicity.py/0
{ "file_path": "trl/examples/research_projects/toxicity/scripts/evaluate-toxicity.py", "repo_id": "trl", "token_count": 2225 }
623
# 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 os import warnings import numpy as np import pytest import torch from accelerate.utils.memory import release_memory from datasets import Dataset, Features, Image, Value, load_dataset from parameterized import parameterized from transformers import ( AutoModelForCausalLM, AutoModelForImageTextToText, AutoProcessor, AutoTokenizer, BitsAndBytesConfig, ) from transformers.testing_utils import ( backend_empty_cache, require_bitsandbytes, require_flash_attn, require_liger_kernel, require_peft, require_torch_accelerator, torch_device, ) from transformers.utils import is_peft_available from trl import GRPOConfig, GRPOTrainer from trl.trainer.utils import get_kbit_device_map from ..testing_utils import TrlTestCase, require_vllm from .testing_constants import MODELS_TO_TEST if is_peft_available(): from peft import LoraConfig, PeftModel @pytest.mark.slow @require_torch_accelerator class GRPOTrainerSlowTester(TrlTestCase): def setUp(self): super().setUp() self.train_dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") self.eval_dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="test") self.max_length = 128 def tearDown(self): gc.collect() backend_empty_cache(torch_device) gc.collect() super().tearDown() @parameterized.expand(MODELS_TO_TEST) @require_liger_kernel def test_training_with_liger_grpo_loss(self, model_name): training_args = GRPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=3, num_generations=3, use_liger_loss=True, max_completion_length=self.max_length, report_to="none", logging_strategy="no", ) model = AutoModelForCausalLM.from_pretrained(model_name) tokenizer = AutoTokenizer.from_pretrained(model_name) tokenizer.pad_token = tokenizer.eos_token if tokenizer.pad_token is None else tokenizer.pad_token trainer = GRPOTrainer( model=model, reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", args=training_args, train_dataset=self.train_dataset, eval_dataset=self.eval_dataset, processing_class=tokenizer, ) from liger_kernel.chunked_loss import LigerFusedLinearGRPOLoss assert isinstance(trainer.liger_grpo_loss, LigerFusedLinearGRPOLoss) previous_trainable_params = {n: param.clone() for n, param in model.named_parameters()} trainer.train() for n, param in previous_trainable_params.items(): new_param = model.get_parameter(n) self.assertFalse(torch.equal(param, new_param), f"Parameter {n} has not changed.") release_memory(model, trainer) @parameterized.expand(MODELS_TO_TEST) @require_liger_kernel @require_peft def test_training_with_liger_grpo_loss_and_peft(self, model_name): from peft import LoraConfig, TaskType training_args = GRPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=3, num_generations=3, use_liger_loss=True, max_completion_length=self.max_length, report_to="none", logging_strategy="no", ) model = AutoModelForCausalLM.from_pretrained(model_name) tokenizer = AutoTokenizer.from_pretrained(model_name) tokenizer.pad_token = tokenizer.eos_token if tokenizer.pad_token is None else tokenizer.pad_token # Configure PEFT with LoRA peft_config = LoraConfig( task_type=TaskType.CAUSAL_LM, inference_mode=False, r=8, lora_alpha=32, lora_dropout=0.1, target_modules=["q_proj", "v_proj"], ) trainer = GRPOTrainer( model=model, reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", args=training_args, train_dataset=self.train_dataset, eval_dataset=self.eval_dataset, processing_class=tokenizer, peft_config=peft_config, ) from liger_kernel.chunked_loss import LigerFusedLinearGRPOLoss assert isinstance(trainer.liger_grpo_loss, LigerFusedLinearGRPOLoss) # Verify PEFT adapter is properly initialized from peft import PeftModel self.assertTrue(isinstance(trainer.model, PeftModel), "Model should be wrapped with PEFT") # Store adapter weights before training previous_trainable_params = { n: param.clone() for n, param in trainer.model.named_parameters() if param.requires_grad } self.assertTrue(len(previous_trainable_params) > 0, "No trainable parameters found in PEFT model") trainer.train() # Verify adapter weights have changed after training for n, param in previous_trainable_params.items(): new_param = trainer.model.get_parameter(n) self.assertFalse(torch.equal(param, new_param), f"Parameter {n} has not changed.") release_memory(model, trainer) @parameterized.expand(MODELS_TO_TEST) def test_training_with_transformers_paged(self, model_name): """Test that training works with transformers paged implementation (requires GPU).""" training_args = GRPOConfig( output_dir=self.tmp_dir, learning_rate=0.1, # increase the learning rate to speed up the test per_device_train_batch_size=3, # reduce the batch size to reduce memory usage num_generations=3, # reduce the number of generations to reduce memory usage max_completion_length=8, # reduce the completion length to reduce memory usage use_transformers_paged=True, # Enable transformers paged implementation report_to="none", logging_strategy="no", ) model = AutoModelForCausalLM.from_pretrained(model_name) trainer = GRPOTrainer( model=model, reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", args=training_args, train_dataset=self.train_dataset, ) previous_trainable_params = {n: param.clone() for n, param in model.named_parameters()} trainer.train() self.assertIsNotNone(trainer.state.log_history[-1]["train_loss"]) # Check that the params have changed for n, param in previous_trainable_params.items(): new_param = model.get_parameter(n) self.assertFalse(torch.equal(param, new_param), f"Parameter {n} has not changed.") release_memory(model, trainer) @require_flash_attn @require_bitsandbytes @require_peft @parameterized.expand( [ ("HuggingFaceTB/SmolVLM-Instruct",), # Only test the smaller model to avoid OOM ] ) def test_vlm_training(self, model_name): """ Test VLM training with aggressive memory optimization. This test uses multiple memory reduction techniques: - 4-bit quantization with double quantization - LoRA with very low rank (r=4) - Minimal batch size (1) with gradient accumulation - Small images (64x64 instead of 224x224) - Short sequences (max_completion_length=8) - Only 4 training samples - Only 1 training step - Gradient checkpointing and bfloat16 """ # Create processor once outside the data generator processor = AutoProcessor.from_pretrained(model_name, use_fast=True, padding_side="left") conversation = [ { "role": "user", "content": [ {"type": "image"}, {"type": "text", "text": "What is in the image?"}, ], }, ] prompt = processor.apply_chat_template(conversation, add_generation_prompt=True) def data_gen(num_samples): for _ in range(num_samples): yield { "prompt": prompt, "image": np.random.uniform(low=0.0, high=255.0, size=(64, 64, 3)).astype( np.uint8 ), # Much smaller images } dataset = Dataset.from_generator( data_gen, gen_kwargs={"num_samples": 4}, features=Features(image=Image(), prompt=Value(dtype="string")) ) # reduce memory requirements as much as possible quantization_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_compute_dtype="bfloat16", bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True, bnb_4bit_quant_storage="bfloat16", ) model = AutoModelForImageTextToText.from_pretrained( model_name, attn_implementation="flash_attention_2", torch_dtype="bfloat16", device_map=get_kbit_device_map(), quantization_config=quantization_config, ) def reward_func(prompts, completions, **kwargs): # simple nonsensical reward return [-((len(c) - 25) ** 2) + 100 for c in completions] training_args = GRPOConfig( output_dir=self.tmp_dir, learning_rate=0.1, per_device_train_batch_size=1, # Minimal batch size gradient_accumulation_steps=2, # Maintain effective batch size num_generations=2, max_completion_length=8, # Much shorter completions max_prompt_length=None, # Don't limit prompt length for VLM bf16=True, # Use bfloat16 precision max_steps=1, # Only do 1 training step to save time and memory report_to="none", logging_strategy="no", ) lora_config = LoraConfig( task_type="CAUSAL_LM", r=4, # Much lower rank for minimal memory lora_alpha=8, # Reduced alpha proportionally lora_dropout=0.1, target_modules=["q_proj", "v_proj"], # Minimal target modules # For VLM models, we typically want to freeze the vision encoder # and only adapt the language model parameters modules_to_save=None, ) try: trainer = GRPOTrainer( model=model, processing_class=processor, reward_funcs=[reward_func], args=training_args, train_dataset=dataset, peft_config=lora_config, ) self.assertIsInstance(trainer.model, PeftModel) previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} trainer.train() self.assertIsNotNone(trainer.state.log_history[-1]["train_loss"]) # Check that LoRA parameters have changed # For VLM models, we're more permissive about which parameters can change lora_params_changed = False for n, param in previous_trainable_params.items(): new_param = trainer.model.get_parameter(n) if "lora" in n.lower(): # LoRA parameters should change if not torch.equal(param, new_param): lora_params_changed = True # At least some LoRA parameters should have changed during training self.assertTrue(lora_params_changed, "No LoRA parameters were updated during training.") except torch.OutOfMemoryError as e: self.skipTest(f"Skipping VLM training test due to insufficient GPU memory: {e}") except Exception as e: # Check for other memory-related errors if any(keyword in str(e).lower() for keyword in ["memory", "cuda", "out of memory", "insufficient"]): self.skipTest(f"Skipping VLM training test due to hardware constraints: {e}") else: raise release_memory(model, trainer) @require_vllm @require_bitsandbytes @require_peft def test_vlm_processor_vllm_colocate_mode(self): """ Test that VLM processors work with vLLM in colocate mode. This test uses multiple memory optimization techniques to ensure it runs on limited hardware: - LoRA (Low-Rank Adaptation) with minimal rank (r=4) - 4-bit quantization with BitsAndBytesConfig - Gradient checkpointing - bfloat16 precision - Minimal batch sizes and sequence lengths - Very low GPU memory utilization (5%) """ dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") config = GRPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=1, # Minimal batch size gradient_accumulation_steps=2, # Make effective batch size 2, divisible by num_generations num_generations=2, max_completion_length=4, # Very short completions to reduce memory max_prompt_length=32, # Very short prompts to reduce memory use_vllm=True, # Enable vLLM vllm_mode="colocate", # Use colocate mode to avoid server dependency vllm_gpu_memory_utilization=0.05, # Use minimal GPU memory (5%) gradient_checkpointing=True, # Enable gradient checkpointing to save memory bf16=True, # Use bfloat16 to reduce memory report_to="none", logging_strategy="no", ) # Create a VLM processor processor = AutoProcessor.from_pretrained("HuggingFaceTB/SmolVLM-Instruct", use_fast=True, padding_side="left") # Verify processor has both required attributes for VLM detection self.assertTrue(hasattr(processor, "tokenizer")) self.assertTrue(hasattr(processor, "image_processor")) def dummy_reward_func(completions, **kwargs): return [1.0] * len(completions) # Use LoRA configuration for memory efficiency lora_config = LoraConfig( r=4, # Very low rank for minimal memory lora_alpha=8, target_modules=["q_proj", "v_proj"], # Minimal target modules lora_dropout=0.1, bias="none", task_type="CAUSAL_LM", ) # Use 4-bit quantization for further memory reduction quantization_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True, ) original_env = {} required_env_vars = { "RANK": "0", "LOCAL_RANK": "0", "WORLD_SIZE": "1", "LOCAL_WORLD_SIZE": "1", "MASTER_ADDR": "localhost", "MASTER_PORT": "12355", } for key, value in required_env_vars.items(): original_env[key] = os.environ.get(key) os.environ[key] = value try: # Test VLM processor with vLLM colocate mode with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") try: # Load model with quantization for memory efficiency model = AutoModelForCausalLM.from_pretrained( "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", quantization_config=quantization_config, torch_dtype=torch.bfloat16, ) trainer = GRPOTrainer( model=model, reward_funcs=dummy_reward_func, args=config, train_dataset=dataset, processing_class=processor, # VLM processor peft_config=lora_config, # Use LoRA for memory efficiency ) # Should detect VLM processor correctly and allow vLLM self.assertTrue(trainer.use_vllm, "vLLM should be enabled for VLM processors in colocate mode") self.assertEqual(trainer.vllm_mode, "colocate", "Should use colocate mode") # Check if signature columns were set properly if trainer._signature_columns is not None: # Should include 'image' in signature columns for VLM processors self.assertIn( "image", trainer._signature_columns, "Should include 'image' in signature columns for VLM", ) # Should not emit any warnings about VLM incompatibility incompatibility_warnings = [ str(w_item.message) for w_item in w if "does not support VLMs" in str(w_item.message) or "not compatible" in str(w_item.message).lower() ] self.assertEqual( len(incompatibility_warnings), 0, f"Should not emit VLM incompatibility warnings, but got: {incompatibility_warnings}", ) # Test passes if we get this far without exceptions except Exception as e: # If vLLM fails to initialize due to hardware constraints or other issues, that's expected if any( keyword in str(e).lower() for keyword in [ "outofmemoryerror", "cuda", "memory", "insufficient", "no such device", "free memory", "gpu memory utilization", "decrease gpu memory", ] ): self.skipTest(f"Skipping vLLM colocate test due to hardware constraints: {e}") elif "KeyError" in str(e) and "RANK" in str(e): self.skipTest(f"Skipping vLLM colocate test due to environment setup issues: {e}") elif "ValueError" in str(e) and "memory" in str(e).lower(): self.skipTest(f"Skipping vLLM colocate test due to memory constraints: {e}") else: raise finally: # Restore original environment variables for key, original_value in original_env.items(): if original_value is None: os.environ.pop(key, None) else: os.environ[key] = original_value release_memory(model, trainer) @require_vllm def test_training_vllm(self): """Test that training works with vLLM for generation.""" dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only", split="train") training_args = GRPOConfig( output_dir=self.tmp_dir, learning_rate=0.1, # increase the learning rate to speed up the test per_device_train_batch_size=3, # reduce the batch size to reduce memory usage num_generations=3, # reduce the number of generations to reduce memory usage max_completion_length=8, # reduce the completion length to reduce memory usage report_to="none", logging_strategy="no", use_vllm=True, ) try: trainer = GRPOTrainer( model="Qwen/Qwen2.5-0.5B-Instruct", # tiny models are too small for vLLM reward_funcs="trl-internal-testing/tiny-Qwen2ForSequenceClassification-2.5", args=training_args, train_dataset=dataset, ) previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} trainer.train() self.assertIsNotNone(trainer.state.log_history[-1]["train_loss"]) # Check that the params have changed for n, param in previous_trainable_params.items(): new_param = trainer.model.get_parameter(n) self.assertFalse(torch.equal(param, new_param), f"Parameter {n} has not changed.") except Exception as e: # If vLLM fails to initialize due to hardware constraints or other issues, that's expected if any( keyword in str(e).lower() for keyword in [ "outofmemoryerror", "cuda", "memory", "insufficient", "no such device", "free memory", "gpu memory utilization", "decrease gpu memory", ] ): self.skipTest(f"Skipping vLLM training test due to hardware constraints: {e}") elif "KeyError" in str(e) and "RANK" in str(e): self.skipTest(f"Skipping vLLM training test due to environment setup issues: {e}") elif "ValueError" in str(e) and "memory" in str(e).lower(): self.skipTest(f"Skipping vLLM training test due to memory constraints: {e}") else: raise release_memory(trainer.model, trainer)
trl/tests/slow/test_grpo_slow.py/0
{ "file_path": "trl/tests/slow/test_grpo_slow.py", "repo_id": "trl", "token_count": 10560 }
624
# 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 import unittest from unittest.mock import MagicMock import numpy as np import torch from datasets import Dataset, features, load_dataset from parameterized import parameterized from transformers import ( AutoModelForCausalLM, AutoModelForImageTextToText, AutoModelForSeq2SeqLM, AutoProcessor, AutoTokenizer, PreTrainedTokenizerBase, is_vision_available, ) from transformers.testing_utils import ( get_device_properties, require_liger_kernel, require_peft, require_torch_gpu_if_bnb_not_multi_backend_enabled, require_vision, ) from trl import DPOConfig, DPOTrainer, FDivergenceType from .testing_utils import TrlTestCase, require_bitsandbytes, require_no_wandb if is_vision_available(): from PIL import Image class TestTokenizeRow(TrlTestCase): def setUp(self): super().setUp() # Set up the mock tokenizer with specific behaviors self.tokenizer = MagicMock(spec=PreTrainedTokenizerBase) self.tokenizer.bos_token_id = 0 self.tokenizer.eos_token_id = 2 # Define mock return values for the tokenizer's 'input_ids' for the different text inputs self.tokenizer.return_value = { "input_ids": {"The sky is": [464, 6766, 318], " blue": [4171], " green": [4077]} } # Define tokenizer behavior when called def mock_tokenizer_call(text, add_special_tokens): token_map = { "The sky is": {"input_ids": [464, 6766, 318]}, " blue": {"input_ids": [4171]}, " green": {"input_ids": [4077]}, } return token_map[text] self.tokenizer.side_effect = mock_tokenizer_call def test_tokenize_row_no_truncation_no_special_tokens(self): # Define the input features features = {"prompt": "The sky is", "chosen": " blue", "rejected": " green"} # Call the method with no truncation and no special tokens result = DPOTrainer.tokenize_row( features=features, processing_class=self.tokenizer, max_prompt_length=None, max_completion_length=None, add_special_tokens=False, ) # Assert the correct output without truncation or special tokens self.assertEqual( result, { "prompt_input_ids": [464, 6766, 318], "chosen_input_ids": [4171, 2], # eos_token added "rejected_input_ids": [4077, 2], # eos_token added }, ) def test_tokenize_row_with_truncation(self): # Define the input features features = {"prompt": "The sky is", "chosen": " blue", "rejected": " green"} # Call the method with truncation result = DPOTrainer.tokenize_row( features=features, processing_class=self.tokenizer, max_prompt_length=2, max_completion_length=1, add_special_tokens=False, ) # Assert the correct output with truncation applied self.assertEqual( result, { "prompt_input_ids": [6766, 318], # truncated to the last 2 tokens "chosen_input_ids": [4171], # truncated to 1 token "rejected_input_ids": [4077], # truncated to 1 token }, ) def test_tokenize_row_with_special_tokens(self): # Define the input features features = {"prompt": "The sky is", "chosen": " blue", "rejected": " green"} # Call the method with special tokens result = DPOTrainer.tokenize_row( features=features, processing_class=self.tokenizer, max_prompt_length=None, max_completion_length=None, add_special_tokens=True, ) # Assert the correct output with special tokens added self.assertEqual( result, { "prompt_input_ids": [0, 464, 6766, 318, 2], # bos_token and eos_token added "chosen_input_ids": [4171, 2], # eos_token added "rejected_input_ids": [4077, 2], # eos_token added }, ) def test_tokenize_row_with_truncation_and_special_tokens(self): # Define the input features features = {"prompt": "The sky is", "chosen": " blue", "rejected": " green"} # Call the method with both truncation and special tokens result = DPOTrainer.tokenize_row( features=features, processing_class=self.tokenizer, max_prompt_length=4, max_completion_length=1, add_special_tokens=True, ) # Assert the correct output with both truncation and special tokens self.assertEqual( result, { "prompt_input_ids": [464, 6766, 318, 2], # truncated to 4 tokens with bos_token and eos_token "chosen_input_ids": [4171], # truncated to 1 token "rejected_input_ids": [4077], # truncated to 1 token }, ) class DPOTrainerTester(TrlTestCase): def setUp(self): super().setUp() self.model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" self.model = AutoModelForCausalLM.from_pretrained(self.model_id) self.ref_model = AutoModelForCausalLM.from_pretrained(self.model_id) self.tokenizer = AutoTokenizer.from_pretrained(self.model_id) self.tokenizer.pad_token = self.tokenizer.eos_token # get t5 as seq2seq example: model_id = "trl-internal-testing/tiny-T5ForConditionalGeneration" self.t5_model = AutoModelForSeq2SeqLM.from_pretrained(model_id) self.t5_ref_model = AutoModelForSeq2SeqLM.from_pretrained(model_id) self.t5_tokenizer = AutoTokenizer.from_pretrained(model_id) def test_train(self): model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") tokenizer = AutoTokenizer.from_pretrained(model_id) training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, learning_rate=9e-1, report_to="none", ) trainer = DPOTrainer( model=model_id, args=training_args, processing_class=tokenizer, train_dataset=dataset, ) previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} trainer.train() self.assertIsNotNone(trainer.state.log_history[-1]["train_loss"]) # Check that the parameters have changed for n, param in previous_trainable_params.items(): new_param = trainer.model.get_parameter(n) if param.sum() != 0: # ignore 0 biases self.assertFalse(torch.allclose(param, new_param, rtol=1e-12, atol=1e-12)) @parameterized.expand( [ ("sigmoid",), ("hinge",), ("ipo",), ("exo_pair",), ("nca_pair",), ("robust",), ("bco_pair",), ("sppo_hard",), ("aot",), ("aot_pair",), ("discopop",), ("apo_zero",), ("apo_down",), ] ) def test_train_loss_types(self, loss_type): model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") tokenizer = AutoTokenizer.from_pretrained(model_id) training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, learning_rate=9e-1, loss_type=loss_type, report_to="none", ) trainer = DPOTrainer( model=model_id, args=training_args, processing_class=tokenizer, train_dataset=dataset, ) previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} trainer.train() self.assertIsNotNone(trainer.state.log_history[-1]["train_loss"]) # Check that the parameters have changed for n, param in previous_trainable_params.items(): new_param = trainer.model.get_parameter(n) if param.sum() != 0: # ignore 0 biases self.assertFalse(torch.allclose(param, new_param, rtol=1e-12, atol=1e-12)) def test_dpo_trainer_with_weighting(self): dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, learning_rate=9e-1, use_weighting=True, report_to="none", ) trainer = DPOTrainer( model=self.model, args=training_args, processing_class=self.tokenizer, train_dataset=dataset, ) previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} trainer.train() self.assertIsNotNone(trainer.state.log_history[-1]["train_loss"]) # Check that the parameters have changed for n, param in previous_trainable_params.items(): new_param = trainer.model.get_parameter(n) if param.sum() != 0: # ignore 0 biases self.assertFalse(torch.allclose(param, new_param, rtol=1e-12, atol=1e-12)) def test_train_with_multiple_loss_types(self): """ Tests multi-loss combinations, loss type inference, and weight configuration. MPO combines DPO (sigmoid), BCO (bco_pair), and SFT (sft) losses. """ model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") tokenizer = AutoTokenizer.from_pretrained(model_id) training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, learning_rate=9e-1, loss_type=["sigmoid", "bco_pair", "sft"], loss_weights=[0.8, 0.2, 1.0], report_to="none", ) trainer = DPOTrainer( model=model_id, args=training_args, processing_class=tokenizer, train_dataset=dataset, ) # Test that training works trainer.train() self.assertIsNotNone(trainer.state.log_history[-1]["train_loss"]) # Verify SFT loss is computed in the first test too with torch.no_grad(): batch = next(iter(trainer.get_train_dataloader())) loss, metrics = trainer.get_batch_loss_metrics(trainer.model, batch) self.assertIn("nll_loss", metrics) # SFT loss should be computed def test_wrong_loss_weights_length(self): with self.assertRaises(ValueError) as context: DPOConfig( output_dir=self.tmp_dir, loss_type=["sigmoid", "bco_pair"], loss_weights=[1.0, 0.5, 0.1], # Wrong length ) self.assertIn("Length of loss_weights list", str(context.exception)) @parameterized.expand([(None,), (0.5,)]) def test_dpo_trainer_without_providing_ref_model(self, rpo_alpha): training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=3, remove_unused_columns=False, gradient_accumulation_steps=4, learning_rate=9e-1, eval_strategy="steps", beta=0.1, precompute_ref_log_probs=True, rpo_alpha=rpo_alpha, report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_preference") trainer = DPOTrainer( model=self.model, ref_model=None, args=training_args, processing_class=self.tokenizer, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], ) previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} trainer.train() self.assertIsNotNone(trainer.state.log_history[-1]["train_loss"]) # Check that the parameters have changed for n, param in previous_trainable_params.items(): new_param = trainer.model.get_parameter(n) if param.sum() != 0: # ignore 0 biases self.assertFalse(torch.equal(param, new_param)) def test_dpo_trainer_with_ref_model_is_model(self): training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=3, report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_preference") with self.assertRaises(ValueError): DPOTrainer( model=self.model, ref_model=self.model, # ref_model can't be the same as model args=training_args, processing_class=self.tokenizer, train_dataset=dummy_dataset["train"], ) def test_precompute_ref_batch_size(self): training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, precompute_ref_log_probs=True, precompute_ref_batch_size=4, report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_preference") trainer = DPOTrainer( model=self.model, ref_model=self.ref_model, args=training_args, processing_class=self.tokenizer, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], ) previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} trainer.train() self.assertIsNotNone(trainer.state.log_history[-1]["train_loss"]) # Check that the parameters have changed for n, param in previous_trainable_params.items(): new_param = trainer.model.get_parameter(n) if param.sum() != 0: # ignore 0 biases self.assertFalse(torch.allclose(param, new_param, rtol=1e-12, atol=1e-12)) @require_peft def test_dpo_trainer_without_providing_ref_model_with_lora(self): from peft import LoraConfig lora_config = LoraConfig( r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM", ) training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=3, remove_unused_columns=False, gradient_accumulation_steps=4, learning_rate=9e-1, eval_strategy="steps", beta=0.1, precompute_ref_log_probs=True, report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_preference") trainer = DPOTrainer( model=self.model, ref_model=None, args=training_args, processing_class=self.tokenizer, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], peft_config=lora_config, ) previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} trainer.train() self.assertIsNotNone(trainer.state.log_history[-1]["train_loss"]) # Check that the parameters have changed for n, param in previous_trainable_params.items(): if "lora" in n: new_param = trainer.model.get_parameter(n) if param.sum() != 0: # ignore 0 biases self.assertFalse(torch.equal(param, new_param)) def test_dpo_trainer_padding_token_is_none(self): training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=3, remove_unused_columns=False, gradient_accumulation_steps=1, learning_rate=9e-1, eval_strategy="steps", beta=0.1, report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_preference") tokenizer = AutoTokenizer.from_pretrained(self.model_id) tokenizer.pad_token = None with self.assertRaisesRegex( ValueError, expected_regex=r"`padding_value` is not specified in `DPOConfig`, and `pad_token_id` is missing in " r"the `processing_class`. Please either set the `padding_value` argument in `DPOConfig`, or set " r"`tokenizer.pad_token` \(e.g., `tokenizer.pad_token = tokenizer.eos_token`\) before instantiating " r"the trainer.", ): trainer = DPOTrainer( model=self.model, ref_model=None, args=training_args, processing_class=tokenizer, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], ) trainer.train() def test_dpo_trainer_w_dataset_num_proc(self): training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=3, remove_unused_columns=False, gradient_accumulation_steps=1, learning_rate=9e-1, eval_strategy="steps", beta=0.1, dataset_num_proc=2, report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_preference") tokenizer = AutoTokenizer.from_pretrained(self.model_id) trainer = DPOTrainer( model=self.model, args=training_args, processing_class=tokenizer, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], ) trainer.train() def test_tr_dpo_trainer(self): training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=3, remove_unused_columns=False, gradient_accumulation_steps=4, learning_rate=9e-1, eval_strategy="steps", precompute_ref_log_probs=False, sync_ref_model=True, ref_model_mixup_alpha=0.5, ref_model_sync_steps=1, report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_preference") trainer = DPOTrainer( model=self.model, ref_model=self.ref_model, args=training_args, processing_class=self.tokenizer, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], ) # params of the ref model as its the same as the model previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} trainer.train() self.assertIsNotNone(trainer.state.log_history[-1]["train_loss"]) # Check that the parameters have changed for n, param in previous_trainable_params.items(): new_param = trainer.ref_model.get_parameter(n) if param.sum() != 0: # ignore 0 biases self.assertFalse(torch.equal(param, new_param)) @require_no_wandb def test_dpo_trainer_generate_during_eval_no_wandb(self): training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=3, remove_unused_columns=False, gradient_accumulation_steps=1, learning_rate=9e-1, eval_strategy="steps", beta=0.1, generate_during_eval=True, report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_preference") with self.assertRaisesRegex( ValueError, expected_regex="`generate_during_eval=True` requires Weights and Biases, MLFlow or Comet to be installed." " Please install `wandb`, `mlflow` or `comet-ml` to resolve.", ): DPOTrainer( model=self.model, ref_model=None, args=training_args, processing_class=self.tokenizer, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], ) @require_peft def test_dpo_lora_save(self): from peft import LoraConfig, get_peft_model lora_config = LoraConfig( r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM", ) # lora model model = AutoModelForCausalLM.from_pretrained(self.model_id) model_peft = get_peft_model(model, lora_config) training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=3, remove_unused_columns=False, gradient_accumulation_steps=4, learning_rate=9e-1, eval_strategy="steps", beta=0.1, precompute_ref_log_probs=True, report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_preference") # dpo train lora model with a lora config trainer = DPOTrainer( model=model_peft, ref_model=None, args=training_args, processing_class=self.tokenizer, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], peft_config=lora_config, ) # train the model trainer.train() # save peft adapter trainer.save_model() try: AutoModelForCausalLM.from_pretrained(self.tmp_dir) except OSError: self.fail("Loading the saved peft adapter failed") @require_peft @require_torch_gpu_if_bnb_not_multi_backend_enabled def test_dpo_lora_bf16_autocast_llama(self): # Note this test only works on compute capability > 7 GPU devices from peft import LoraConfig model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" tokenizer = AutoTokenizer.from_pretrained(model_id) lora_config = LoraConfig( r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM", ) # lora model model = AutoModelForCausalLM.from_pretrained(model_id, load_in_4bit=True) training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=3, remove_unused_columns=False, gradient_accumulation_steps=4, learning_rate=9e-1, eval_strategy="steps", bf16=True, beta=0.1, report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_preference") # dpo train lora model with a lora config trainer = DPOTrainer( model=model, ref_model=None, args=training_args, processing_class=tokenizer, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], peft_config=lora_config, ) # train the model trainer.train() # save peft adapter trainer.save_model() @parameterized.expand( [ ("sigmoid", False, False), ("sigmoid", False, True), ("sigmoid", True, False), ("sigmoid", True, True), ("ipo", False, False), ("ipo", False, True), ("ipo", True, False), ("ipo", True, True), ("aot_pair", False, False), ("aot_pair", False, True), ("aot_pair", True, False), ("aot_pair", True, True), ("aot", False, False), ("aot", False, True), ("aot", True, False), ("aot", True, True), ("bco_pair", False, False), ("bco_pair", False, True), ("bco_pair", True, False), ("bco_pair", True, True), ("robust", False, False), ("robust", False, True), ("robust", True, False), ("robust", True, True), ] ) @require_bitsandbytes @require_peft @unittest.skipIf( get_device_properties()[0] == "cuda" and get_device_properties()[1] < 8, "Skipping because bf16 not supported on CUDA GPU with capability < 8.0", ) def test_dpo_lora_bf16_autocast(self, loss_type, pre_compute, gen_during_eval): from peft import LoraConfig lora_config = LoraConfig( r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM", ) # lora model model = AutoModelForCausalLM.from_pretrained(self.model_id, load_in_4bit=True) training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=3, remove_unused_columns=False, gradient_accumulation_steps=4, learning_rate=9e-1, eval_strategy="steps", bf16=True, beta=0.1, generate_during_eval=gen_during_eval, loss_type=loss_type, precompute_ref_log_probs=pre_compute, report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_preference") # dpo train lora model with a lora config trainer = DPOTrainer( model=model, ref_model=None, args=training_args, processing_class=self.tokenizer, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], peft_config=lora_config, ) # train the model trainer.train() # save peft adapter trainer.save_model() @require_peft def test_dpo_lora_tags(self): from peft import LoraConfig model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" tokenizer = AutoTokenizer.from_pretrained(model_id) lora_config = LoraConfig( r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM", ) # lora model model = AutoModelForCausalLM.from_pretrained(model_id) training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=3, remove_unused_columns=False, gradient_accumulation_steps=4, learning_rate=9e-1, eval_strategy="steps", beta=0.1, report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_preference") # dpo train lora model with a lora config trainer = DPOTrainer( model=model, ref_model=None, args=training_args, processing_class=tokenizer, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], peft_config=lora_config, ) for tag in ["dpo", "trl"]: self.assertIn(tag, trainer.model.model_tags) @require_peft def test_dpo_tags(self): model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" tokenizer = AutoTokenizer.from_pretrained(model_id) # lora model model = AutoModelForCausalLM.from_pretrained(model_id) training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=3, remove_unused_columns=False, gradient_accumulation_steps=4, learning_rate=9e-1, eval_strategy="steps", beta=0.1, report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_preference") # dpo train lora model with a lora config trainer = DPOTrainer( model=model, ref_model=None, args=training_args, processing_class=tokenizer, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], ) for tag in ["dpo", "trl"]: self.assertIn(tag, trainer.model.model_tags) @require_peft def test_dpo_lora_force_use_ref(self): from peft import LoraConfig, get_peft_model lora_config = LoraConfig( r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM", ) # lora model model = AutoModelForCausalLM.from_pretrained(self.model_id) model_peft = get_peft_model(model, lora_config) ref_model = AutoModelForCausalLM.from_pretrained(self.model_id) training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=3, remove_unused_columns=False, gradient_accumulation_steps=4, learning_rate=9e-1, eval_strategy="steps", beta=0.1, report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_preference") with self.assertRaises(ValueError): # passing a peft_model as model and ref_model should error out, # unless you pass `force_use_ref_model` trainer = DPOTrainer( model=model_peft, ref_model=ref_model, args=training_args, processing_class=self.tokenizer, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], peft_config=lora_config, ) training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=3, remove_unused_columns=False, gradient_accumulation_steps=4, learning_rate=9e-1, eval_strategy="steps", beta=0.1, force_use_ref_model=True, report_to="none", ) trainer = DPOTrainer( model=model_peft, ref_model=ref_model, args=training_args, processing_class=self.tokenizer, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], peft_config=lora_config, ) # train the model trainer.train() def test_dpo_trainer_torch_dtype(self): # See https://github.com/huggingface/trl/issues/1751 dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_preference") training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=1, model_init_kwargs={"torch_dtype": "float16"}, ref_model_init_kwargs={"torch_dtype": "float16"}, report_to="none", ) trainer = DPOTrainer( model=self.model_id, ref_model=self.model_id, processing_class=self.tokenizer, args=training_args, train_dataset=dummy_dataset["train"], ) self.assertEqual(trainer.model.config.torch_dtype, torch.float16) self.assertEqual(trainer.ref_model.config.torch_dtype, torch.float16) # Now test when `torch_dtype` is provided but is wrong to either the model or the ref_model training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=1, model_init_kwargs={"torch_dtype": -1}, report_to="none", ) with self.assertRaises(ValueError) as context: _ = DPOTrainer( model=self.model_id, processing_class=self.tokenizer, args=training_args, train_dataset=dummy_dataset["train"], ) self.assertIn( "Invalid `torch_dtype` passed to `DPOConfig`. Expected either 'auto' or a string representing a `torch.dtype` (e.g., 'float32'), but got -1.", str(context.exception), ) training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=1, ref_model_init_kwargs={"torch_dtype": -1}, report_to="none", ) with self.assertRaises(ValueError) as context: _ = DPOTrainer( model=self.model_id, ref_model=self.model_id, processing_class=self.tokenizer, args=training_args, train_dataset=dummy_dataset["train"], ) self.assertIn( "Invalid `torch_dtype` passed to `DPOConfig`. Expected either 'auto' or a string representing a `torch.dtype` (e.g., 'float32'), but got -1.", str(context.exception), ) def test_dpo_loss_alpha_div_f(self): model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" tokenizer = AutoTokenizer.from_pretrained(model_id) # lora model model = AutoModelForCausalLM.from_pretrained(model_id) training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=3, remove_unused_columns=False, gradient_accumulation_steps=4, learning_rate=9e-1, eval_strategy="steps", f_divergence_type=FDivergenceType.ALPHA_DIVERGENCE.value, f_alpha_divergence_coef=0.5, report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_preference") # dpo train lora model with a lora config trainer = DPOTrainer( model=model, ref_model=None, args=training_args, processing_class=tokenizer, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], ) # Fake chosen and rejected log probs policy_chosen_logps = torch.FloatTensor([410.0, 0.1]) policy_rejected_logps = torch.FloatTensor([810.5, 0.2]) reference_chosen_logps = torch.FloatTensor([-610.0, -0.1]) reference_rejected_logps = torch.FloatTensor([110.6, 0.5]) losses, _, _ = trainer.dpo_loss( policy_chosen_logps, policy_rejected_logps, reference_chosen_logps, reference_rejected_logps ) self.assertTrue(torch.isfinite(losses).cpu().numpy().all()) def test_dpo_loss_js_div_f(self): model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" tokenizer = AutoTokenizer.from_pretrained(model_id) # lora model model = AutoModelForCausalLM.from_pretrained(model_id) training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=3, remove_unused_columns=False, gradient_accumulation_steps=4, learning_rate=9e-1, eval_strategy="steps", f_divergence_type=FDivergenceType.JS_DIVERGENCE.value, f_alpha_divergence_coef=0.5, report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_preference") # dpo train lora model with a lora config trainer = DPOTrainer( model=model, ref_model=None, args=training_args, processing_class=tokenizer, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], ) # Fake chosen and rejected log probs policy_chosen_logps = torch.FloatTensor([410.0, 0.1]) policy_rejected_logps = torch.FloatTensor([95.5, 0.2]) reference_chosen_logps = torch.FloatTensor([-610.0, -0.1]) reference_rejected_logps = torch.FloatTensor([5.5, 0.5]) losses, _, _ = trainer.dpo_loss( policy_chosen_logps, policy_rejected_logps, reference_chosen_logps, reference_rejected_logps ) self.assertTrue(torch.isfinite(losses).cpu().numpy().all()) def test_dpo_trainer_use_logits_to_keep(self): model_id = "trl-internal-testing/tiny-LlamaForCausalLM-3.2" tokenizer = AutoTokenizer.from_pretrained(model_id) tokenizer.pad_token = tokenizer.eos_token model = AutoModelForCausalLM.from_pretrained(model_id) training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=3, remove_unused_columns=False, gradient_accumulation_steps=1, learning_rate=9e-1, eval_strategy="steps", beta=0.1, use_logits_to_keep=True, rpo_alpha=0.5, report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_preference") # dpo train lora model with a lora config trainer = DPOTrainer( model=model, ref_model=None, args=training_args, processing_class=tokenizer, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], ) training_args.use_logits_to_keep = False trainer2 = DPOTrainer( model=model, ref_model=None, args=training_args, processing_class=tokenizer, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], ) # Fake batch prompt_input_ids = torch.randint(1, 1000, (2, 10)) chosen_input_ids = torch.randint(1, 1000, (2, 5)) rejected_input_ids = torch.randint(1, 1000, (2, 7)) prompt_attention_mask = torch.ones_like(prompt_input_ids) chosen_attention_mask = torch.ones_like(chosen_input_ids) rejected_attention_mask = torch.ones_like(rejected_input_ids) batch = { "prompt_input_ids": prompt_input_ids.to(model.device), "chosen_input_ids": chosen_input_ids.to(model.device), "rejected_input_ids": rejected_input_ids.to(model.device), "prompt_attention_mask": prompt_attention_mask.to(model.device), "chosen_attention_mask": chosen_attention_mask.to(model.device), "rejected_attention_mask": rejected_attention_mask.to(model.device), } output = trainer.concatenated_forward(model, batch) output2 = trainer2.concatenated_forward(model, batch) np.testing.assert_allclose(output["nll_loss"].item(), output2["nll_loss"].item(), atol=1e-5) np.testing.assert_allclose( output["mean_chosen_logits"].item(), output2["mean_chosen_logits"].item(), atol=1e-5 ) np.testing.assert_allclose( output["mean_rejected_logits"].item(), output2["mean_rejected_logits"].item(), atol=1e-5 ) for i in range(output["chosen_logps"].shape[0]): np.testing.assert_allclose(output["chosen_logps"][i].item(), output2["chosen_logps"][i].item(), atol=1e-5) np.testing.assert_allclose( output["rejected_logps"][i].item(), output2["rejected_logps"][i].item(), atol=1e-5 ) trainer.train() def test_dpo_trainer_with_tools(self): model_id = "trl-internal-testing/tiny-LlamaForCausalLM-3.2" tokenizer = AutoTokenizer.from_pretrained(model_id) tokenizer.pad_token = tokenizer.eos_token model = AutoModelForCausalLM.from_pretrained(model_id) # Define dummy test tools def get_current_temperature(location: str): """ Gets the temperature at a given location. Args: location: The location to get the temperature for """ return 22.0 training_args = DPOConfig( output_dir=self.tmp_dir, tools=[get_current_temperature], ) dummy_dataset = load_dataset("trl-internal-testing/zen", "conversational_preference") trainer = DPOTrainer( model=model, ref_model=None, args=training_args, processing_class=tokenizer, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], ) # We don't run the training, but at this stage, the dataset is supposed to be pre-processed. When # pre-processing, we expect the available tools to be explicitly mentioned in the system prompt. That's # what we're checking here self.assertIn("get_current_temperature", tokenizer.decode(trainer.train_dataset["prompt_input_ids"][0])) def test_padding_free(self): model_id = "trl-internal-testing/tiny-LlamaForCausalLM-3.2" tokenizer = AutoTokenizer.from_pretrained(model_id) tokenizer.pad_token = tokenizer.eos_token # Normally, we need `attn_implementation="flash_attention_2"` to that the model returns correct logits. # Without it, the logits may be incorrect, but that's fine here. This test focuses only on the inner logic # of padding_free. model = AutoModelForCausalLM.from_pretrained(model_id) training_args = DPOConfig( output_dir=self.tmp_dir, learning_rate=9e-1, per_device_train_batch_size=2, padding_free=True, report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_preference") trainer = DPOTrainer( model=model, args=training_args, processing_class=tokenizer, train_dataset=dummy_dataset["train"], ) previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} trainer.train() # Check that the parameters have changed for n, param in previous_trainable_params.items(): new_param = trainer.model.get_parameter(n) if param.sum() != 0: # ignore 0 biases self.assertFalse(torch.allclose(param, new_param, rtol=1e-12, atol=1e-12)) def test_compute_metrics(self): model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5") ref_model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5") tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5") tokenizer.pad_token = tokenizer.eos_token dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_preference") def dummy_compute_metrics(*args, **kwargs): return {"test": 0.0} training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, do_eval=True, eval_strategy="steps", eval_steps=3, per_device_eval_batch_size=2, report_to="none", ) trainer = DPOTrainer( model=model, ref_model=ref_model, args=training_args, processing_class=tokenizer, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], compute_metrics=dummy_compute_metrics, ) trainer.train() self.assertEqual(trainer.state.log_history[-2]["eval_test"], 0.0) def test_train_with_length_desensitization(self): model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") tokenizer = AutoTokenizer.from_pretrained(model_id) training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, learning_rate=9e-1, ld_alpha=0.5, report_to="none", ) trainer = DPOTrainer( model=model_id, args=training_args, processing_class=tokenizer, train_dataset=dataset, ) previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} trainer.train() self.assertIsNotNone(trainer.state.log_history[-1]["train_loss"]) # Check that the parameters have changed for n, param in previous_trainable_params.items(): new_param = trainer.model.get_parameter(n) if param.sum() != 0: # ignore 0 biases self.assertFalse(torch.allclose(param, new_param, rtol=1e-12, atol=1e-12)) @unittest.skipUnless(sys.version_info >= (3, 10), "Liger kernel is not supported on Python 3.9") @parameterized.expand([(0.1,), (0.5,)]) @require_liger_kernel def test_dpo_trainer_with_liger(self, beta): """Test DPO trainer with Liger loss enabled. This test verifies that: 1. Training runs successfully with Liger loss 2. Model parameters update as expected 3. Loss values are reasonable and finite 4. Training works with both default and custom beta values """ training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, do_eval=True, eval_steps=1, learning_rate=9e-1, eval_strategy="steps", beta=beta, use_liger_loss=True, # Enable Liger loss report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_preference") trainer = DPOTrainer( model=self.model, ref_model=self.ref_model, # Add reference model args=training_args, processing_class=self.tokenizer, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], ) # Store initial parameters previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} # Train the model train_output = trainer.train() # Verify training completed successfully self.assertIsNotNone(train_output) self.assertIsNotNone(trainer.state.log_history[-1]["train_loss"]) # Verify loss is finite self.assertTrue(np.isfinite(trainer.state.log_history[-1]["train_loss"])) # Check parameters have been updated for n, param in previous_trainable_params.items(): new_param = trainer.model.get_parameter(n) # Only check non-zero parameters if param.sum() != 0: self.assertFalse(torch.equal(param, new_param)) # Verify new parameters are finite self.assertTrue(torch.isfinite(new_param).all()) # Verify model can still do forward pass after training dummy_batch = next(iter(trainer.get_train_dataloader())) model_inputs = { "input_ids": dummy_batch["prompt_input_ids"], "attention_mask": dummy_batch["prompt_attention_mask"], } with torch.no_grad(): output = trainer.model(**model_inputs) self.assertIsNotNone(output) self.assertFalse("loss" in output.keys()) def test_train_with_iterable_dataset(self): model_id = "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5" dataset = load_dataset( "trl-internal-testing/zen", "standard_preference", split="train", streaming=True, ) tokenizer = AutoTokenizer.from_pretrained(model_id) training_args = DPOConfig( output_dir=self.tmp_dir, max_steps=3, report_to="none", ) trainer = DPOTrainer( model=model_id, args=training_args, processing_class=tokenizer, train_dataset=dataset, ) previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} trainer.train() self.assertIsNotNone(trainer.state.log_history[-1]["train_loss"]) # Check that the parameters have changed for n, param in previous_trainable_params.items(): new_param = trainer.model.get_parameter(n) if param.sum() != 0: # ignore 0 biases self.assertFalse(torch.allclose(param, new_param, rtol=1e-12, atol=1e-12)) @require_vision class DPOVisionTrainerTester(TrlTestCase): @parameterized.expand( [ # ("trl-internal-testing/tiny-Idefics2ForConditionalGeneration",), device issue from transformers, see https://github.com/huggingface/transformers/pull/39975 # ("trl-internal-testing/tiny-PaliGemmaForConditionalGeneration",), ("trl-internal-testing/tiny-LlavaForConditionalGeneration",), ("trl-internal-testing/tiny-LlavaNextForConditionalGeneration",), ] ) def test_vdpo_trainer(self, model_id): # fmt: off dataset_dict = { "prompt": [ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "Describe the image in great detail."}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "Is this bus in the USA?"}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "Give a thorough description of the image."}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "Who are the people in the image?"}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is written?"}]}], ], "chosen": [ [{"role": "assistant", "content": [{"type": "text", "text": "The image features a modern, multi-colored train."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Yes, it can be assumed that this bus is in the USA."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "The image features a forest path."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "There are two individuals, possibly girls or women."}]}], [{"role": "assistant", "content": [{"type": "text", "text": '"ccpb".'}]}], ], "rejected": [ [{"role": "assistant", "content": [{"type": "text", "text": "The image features a modern, colorful train."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "No, it's not in the USA."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "The image features a forest path surrounded by trees."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "In the image, there are two individuals."}]}], [{"role": "assistant", "content": [{"type": "text", "text": '"ccpb".'}]}], ], "images": [ [Image.fromarray(np.random.randint(0, 255, (92, 33, 3), dtype=np.uint8))], [Image.fromarray(np.random.randint(0, 255, (64, 48, 3), dtype=np.uint8))], [Image.fromarray(np.random.randint(0, 255, (80, 152, 3), dtype=np.uint8))], [Image.fromarray(np.random.randint(0, 255, (57, 24, 3), dtype=np.uint8))], [Image.fromarray(np.random.randint(0, 255, (102, 48, 3), dtype=np.uint8))], ], } # fmt: on dataset = Dataset.from_dict(dataset_dict) dataset = dataset.cast_column("images", features.Sequence(features.Image())) # Instantiate the model and processor model = AutoModelForImageTextToText.from_pretrained(model_id) ref_model = AutoModelForImageTextToText.from_pretrained(model_id) processor = AutoProcessor.from_pretrained(model_id) training_args = DPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, remove_unused_columns=False, learning_rate=0.01, # increase learning rate to speed up test max_prompt_length=None, # don't truncate to avoid issues with patch tokens max_length=None, report_to="none", ) trainer = DPOTrainer( model=model, ref_model=ref_model, args=training_args, processing_class=processor, train_dataset=dataset, eval_dataset=dataset, ) # Save the initial weights, so we can check if they have changed after training previous_trainable_params = {n: param.clone() for n, param in trainer.model.named_parameters()} trainer.train() self.assertIsNotNone(trainer.state.log_history[-1]["train_loss"]) # Check that the trainable params have changed for n, param in previous_trainable_params.items(): new_param = trainer.model.get_parameter(n) if param.sum() != 0: # ignore 0 biases if model_id in [ "trl-internal-testing/tiny-LlavaForConditionalGeneration", "trl-internal-testing/tiny-LlavaNextForConditionalGeneration", ] and ( "vision_tower.vision_model.encoder.layers.1" in n or "vision_tower.vision_model.post_layernorm.weight" in n ): # For some reason, these params are not updated. This is probably not related to TRL, but to # the model itself. We should investigate this further, but for now we just skip these params. continue self.assertFalse(torch.allclose(param, new_param, rtol=1e-12, atol=1e-12), f"Param {n} is not updated") if __name__ == "__main__": unittest.main()
trl/tests/test_dpo_trainer.py/0
{ "file_path": "trl/tests/test_dpo_trainer.py", "repo_id": "trl", "token_count": 27353 }
625
# 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 torch import torch.nn as nn from datasets import Dataset from transformers import Trainer, TrainingArguments from trl.trainer.callbacks import RichProgressCallback from .testing_utils import TrlTestCase, require_rich class DummyModel(nn.Module): def __init__(self): super().__init__() self.a = nn.Parameter(torch.tensor(1.0)) def forward(self, x): return self.a * x @require_rich class TestRichProgressCallback(TrlTestCase): def setUp(self): super().setUp() self.dummy_model = DummyModel() self.dummy_train_dataset = Dataset.from_list([{"x": 1.0, "y": 2.0}] * 5) self.dummy_val_dataset = Dataset.from_list([{"x": 1.0, "y": 2.0}] * 101) def test_rich_progress_callback_logging(self): training_args = TrainingArguments( output_dir=self.tmp_dir, per_device_eval_batch_size=2, per_device_train_batch_size=2, num_train_epochs=4, eval_strategy="steps", eval_steps=1, logging_strategy="steps", logging_steps=1, save_strategy="no", report_to="none", disable_tqdm=True, ) callbacks = [RichProgressCallback()] trainer = Trainer( model=self.dummy_model, train_dataset=self.dummy_train_dataset, eval_dataset=self.dummy_val_dataset, args=training_args, callbacks=callbacks, ) trainer.train() trainer.train()
trl/tests/test_rich_progress_callback.py/0
{ "file_path": "trl/tests/test_rich_progress_callback.py", "repo_id": "trl", "token_count": 900 }
626
# 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 torch import torch.nn as nn from transformers import AutoModelForCausalLM, AutoModelForSeq2SeqLM, is_torch_npu_available, is_torch_xpu_available from .modeling_base import PreTrainedModelWrapper class ValueHead(nn.Module): r""" The ValueHead class implements a head for GPT2 that returns a scalar for each output token. """ def __init__(self, config, **kwargs): super().__init__() if not hasattr(config, "summary_dropout_prob"): summary_dropout_prob = kwargs.pop("summary_dropout_prob", 0.1) else: summary_dropout_prob = config.summary_dropout_prob self.dropout = nn.Dropout(summary_dropout_prob) if summary_dropout_prob else nn.Identity() # some models such as OPT have a projection layer before the word embeddings - e.g. OPT-350m if hasattr(config, "hidden_size"): hidden_size = config.hidden_size if hasattr(config, "word_embed_proj_dim"): hidden_size = config.word_embed_proj_dim elif hasattr(config, "is_encoder_decoder"): if config.is_encoder_decoder and hasattr(config, "decoder"): if hasattr(config.decoder, "hidden_size"): hidden_size = config.decoder.hidden_size self.summary = nn.Linear(hidden_size, 1) self.flatten = nn.Flatten() def forward(self, hidden_states): output = self.dropout(hidden_states) # For now force upcast in fp32 if needed. Let's keep the # output in fp32 for numerical stability. if output.dtype != self.summary.weight.dtype: output = output.to(self.summary.weight.dtype) output = self.summary(output) return output class AutoModelForCausalLMWithValueHead(PreTrainedModelWrapper): r""" An autoregressive model with a value head in addition to the language model head. This class inherits from `~trl.PreTrainedModelWrapper` and wraps a `transformers.PreTrainedModel` class. The wrapper class supports classic functions such as `from_pretrained`, `push_to_hub` and `generate`. To call a method of the wrapped model, simply manipulate the `pretrained_model` attribute of this class. Class attributes: - **transformers_parent_class** (`transformers.PreTrainedModel`) -- The parent class of the wrapped model. This should be set to `transformers.AutoModelForCausalLM` for this class. - **supported_args** (`tuple`) -- A tuple of strings that are used to identify the arguments that are supported by the `ValueHead` class. Currently, the supported args are: - **summary_dropout_prob** (`float`, `optional`, defaults to `None`) -- The dropout probability for the `ValueHead` class. - **v_head_initializer_range** (`float`, `optional`, defaults to `0.2`) -- The initializer range for the `ValueHead` if a specific initialization strategy is selected. - **v_head_init_strategy** (`str`, `optional`, defaults to `None`) -- The initialization strategy for the `ValueHead`. Currently, the supported strategies are: - **`None`** -- Initializes the weights of the `ValueHead` with a random distribution. This is the default strategy. - **"normal"** -- Initializes the weights of the `ValueHead` with a normal distribution. """ transformers_parent_class = AutoModelForCausalLM supported_args = ( "summary_dropout_prob", "v_head_initializer_range", "v_head_init_strategy", ) def __init__(self, pretrained_model, **kwargs): r""" Initializes the model. Args: pretrained_model (`transformers.PreTrainedModel`): The model to wrap. It should be a causal language model such as GPT2. or any model mapped inside the `AutoModelForCausalLM` class. kwargs (`dict`, `optional`): Additional keyword arguments, that are passed to the `ValueHead` class. """ super().__init__(pretrained_model, **kwargs) v_head_kwargs, _, _ = self._split_kwargs(kwargs) self.v_head = ValueHead(self.pretrained_model.config, **v_head_kwargs) self._init_weights(**v_head_kwargs) def _init_weights(self, **kwargs): r""" Initializes the weights of the value head. The default initialization strategy is random. Users can pass a different initialization strategy by passing the `v_head_init_strategy` argument when calling `.from_pretrained`. Supported strategies are: - `normal`: initializes the weights with a normal distribution. Args: **kwargs (`dict`, `optional`): Additional keyword arguments, that are passed to the `ValueHead` class. These arguments can contain the `v_head_init_strategy` argument as well as the `v_head_initializer_range` argument. """ initializer_range = kwargs.pop("v_head_initializer_range", 0.2) # random init by default init_strategy = kwargs.pop("v_head_init_strategy", None) if init_strategy is None: # do nothing pass elif init_strategy == "normal": self.v_head.summary.weight.data.normal_(mean=0.0, std=initializer_range) self.v_head.summary.bias.data.zero_() def forward( self, input_ids=None, past_key_values=None, attention_mask=None, return_past_key_values=False, **kwargs, ): r""" Applies a forward pass to the wrapped model and returns the logits of the value head. Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. past_key_values (`tuple(tuple(torch.FloatTensor))`, `optional`): Contains pre-computed hidden-states (key and values in the attention blocks) as computed by the model (see `past_key_values` input) to speed up sequential decoding. attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, `optional`): Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. return_past_key_values (bool): A flag indicating if the computed hidden-states should be returned. kwargs (`dict`, `optional`): Additional keyword arguments, that are passed to the wrapped model. """ kwargs["output_hidden_states"] = True # this had already been set in the LORA / PEFT examples kwargs["past_key_values"] = past_key_values if self.is_peft_model and self.pretrained_model.active_peft_config.peft_type == "PREFIX_TUNING": kwargs.pop("past_key_values") base_model_output = self.pretrained_model( input_ids=input_ids, attention_mask=attention_mask, **kwargs, ) last_hidden_state = base_model_output.hidden_states[-1] lm_logits = base_model_output.logits loss = base_model_output.loss if last_hidden_state.device != self.v_head.summary.weight.device: last_hidden_state = last_hidden_state.to(self.v_head.summary.weight.device) value = self.v_head(last_hidden_state).squeeze(-1) # force upcast in fp32 if logits are in half-precision if lm_logits.dtype != torch.float32: lm_logits = lm_logits.float() if return_past_key_values: return (lm_logits, loss, value, base_model_output.past_key_values) else: return (lm_logits, loss, value) def generate(self, *args, **kwargs): r""" A simple wrapper around the `generate` method of the wrapped model. Please refer to the [`generate`](https://huggingface.co/docs/transformers/internal/generation_utils) method of the wrapped model for more information about the supported arguments. Args: *args (`list`, *optional*): Positional arguments passed to the `generate` method of the wrapped model. **kwargs (`dict`, *optional*): Keyword arguments passed to the `generate` method of the wrapped model. """ return self.pretrained_model.generate(*args, **kwargs) def state_dict(self, *args, **kwargs): r""" Returns the state dictionary of the model. We add the state dictionary of the value head to the state dictionary of the wrapped model by prepending the key with `v_head.`. """ if not self.is_peft_model: pretrained_model_state_dict = self.pretrained_model.state_dict(*args, **kwargs) else: # if it is a peft model, only save the v_head pretrained_model_state_dict = {} v_head_state_dict = self.v_head.state_dict(*args, **kwargs) for k, v in v_head_state_dict.items(): pretrained_model_state_dict[f"v_head.{k}"] = v return pretrained_model_state_dict def push_to_hub(self, *args, **kwargs): self.pretrained_model.v_head = self.v_head return self.pretrained_model.push_to_hub(*args, **kwargs) def post_init(self, state_dict): r""" We add the state dictionary of the value head to the state dictionary of the wrapped model by prepending the key with `v_head.`. This function removes the `v_head.` prefix from the keys of the value head state dictionary. """ for k in list(state_dict.keys()): if "v_head." in k: state_dict[k.replace("v_head.", "")] = state_dict.pop(k) self.v_head.load_state_dict(state_dict, strict=False) del state_dict if hasattr(self.pretrained_model, "hf_device_map"): if ( "cpu" in self.pretrained_model.hf_device_map.values() or "disk" in self.pretrained_model.hf_device_map.values() ): raise ValueError( "The model is offloaded on CPU or disk - CPU & disk offloading is not supported for ValueHead models." ) first_device = list(set(self.pretrained_model.hf_device_map.values()))[0] if isinstance(first_device, int): if is_torch_npu_available(): first_device = f"npu:{first_device}" elif is_torch_xpu_available(): first_device = f"xpu:{first_device}" else: first_device = f"cuda:{first_device}" self.v_head = self.v_head.to(first_device) def set_device_hook(module, input, outputs): new_output = () for output in outputs: if isinstance(output, torch.Tensor): new_output += (output.to(first_device),) else: new_output += (output,) return new_output self.register_forward_hook(set_device_hook) self.is_sequential_parallel = True class AutoModelForSeq2SeqLMWithValueHead(PreTrainedModelWrapper): r""" A seq2seq model with a value head in addition to the language model head. This class inherits from `~trl.PreTrainedModelWrapper` and wraps a `transformers.PreTrainedModel` class. The wrapper class supports classic functions such as `from_pretrained` and `push_to_hub` and also provides some additional functionalities such as `generate`. Args: pretrained_model (`transformers.PreTrainedModel`): The model to wrap. It should be a causal language model such as GPT2. or any model mapped inside the `AutoModelForSeq2SeqLM` class. kwargs: Additional keyword arguments passed along to the `ValueHead` class. """ transformers_parent_class = AutoModelForSeq2SeqLM lm_head_namings = ["lm_head", "embed_out", "output_projection"] supported_args = ( "summary_dropout_prob", "v_head_initializer_range", "v_head_init_strategy", ) def __init__(self, pretrained_model, **kwargs): super().__init__(pretrained_model, **kwargs) v_head_kwargs, _, _ = self._split_kwargs(kwargs) self.is_encoder_decoder = True if not self._has_lm_head(): raise ValueError("The model does not have a language model head, please use a model that has one.") self.v_head = ValueHead(self.pretrained_model.config, **v_head_kwargs) self._init_weights(**v_head_kwargs) def _has_lm_head(self): # check module names of all modules inside `pretrained_model` to find the language model head for name, _module in self.pretrained_model.named_modules(): if any(attribute in name for attribute in self.lm_head_namings): return True return False def post_init(self, state_dict): r""" We add the state dictionary of the value head to the state dictionary of the wrapped model by prepending the key with `v_head.`. This function removes the `v_head.` prefix from the keys of the value head state dictionary. """ for k in list(state_dict.keys()): if "v_head." in k: state_dict[k.replace("v_head.", "")] = state_dict.pop(k) self.v_head.load_state_dict(state_dict, strict=False) del state_dict if hasattr(self.pretrained_model, "hf_device_map"): if ( "cpu" in self.pretrained_model.hf_device_map.values() or "disk" in self.pretrained_model.hf_device_map.values() ): raise ValueError( "The model is offloaded on CPU or disk - CPU & disk offloading is not supported for ValueHead models." ) # get the lm_head device for name, module in self.pretrained_model.named_modules(): if any(attribute in name for attribute in self.lm_head_namings): lm_head_device = module.weight.device break # put v_head on the same device as the lm_head to avoid issues self.v_head = self.v_head.to(lm_head_device) def set_device_hook(module, input, outputs): r""" A hook that sets the device of the output of the model to the device of the first parameter of the model. Args: module (`nn.Module`): The module to which the hook is attached. input (`tuple`): The input to the module. outputs (`tuple`): The output of the module. """ new_output = () for output in outputs: if isinstance(output, torch.Tensor): new_output += (output.to(lm_head_device),) else: new_output += (output,) return new_output self.register_forward_hook(set_device_hook) self.is_sequential_parallel = True def state_dict(self, *args, **kwargs): r""" Returns the state dictionary of the model. We add the state dictionary of the value head to the state dictionary of the wrapped model by prepending the key with `v_head.`. """ if not self.is_peft_model: pretrained_model_state_dict = self.pretrained_model.state_dict(*args, **kwargs) else: # if it is a peft model, only save the v_head pretrained_model_state_dict = {} v_head_state_dict = self.v_head.state_dict(*args, **kwargs) for k, v in v_head_state_dict.items(): pretrained_model_state_dict[f"v_head.{k}"] = v return pretrained_model_state_dict def push_to_hub(self, *args, **kwargs): self.pretrained_model.v_head = self.v_head return self.pretrained_model.push_to_hub(*args, **kwargs) def _init_weights(self, **kwargs): r""" We initialize the weights of the value head. """ initializer_range = kwargs.pop("v_head_initializer_range", 0.2) # random init by default init_strategy = kwargs.pop("v_head_init_strategy", None) if init_strategy is None: # do nothing pass elif init_strategy == "normal": self.v_head.summary.weight.data.normal_(mean=0.0, std=initializer_range) self.v_head.summary.bias.data.zero_() def forward( self, input_ids=None, past_key_values=None, attention_mask=None, return_past_key_values=False, **kwargs, ): kwargs["past_key_values"] = past_key_values if self.is_peft_model and self.pretrained_model.active_peft_config.peft_type == "PREFIX_TUNING": kwargs.pop("past_key_values") base_model_output = self.pretrained_model( input_ids=input_ids, attention_mask=attention_mask, output_hidden_states=True, # We force the model to output hidden states **kwargs, ) last_hidden_state = base_model_output.decoder_hidden_states[-1] lm_logits = base_model_output.logits loss = base_model_output.loss value = self.v_head(last_hidden_state).squeeze(-1) # force upcast in fp32 if logits are in half-precision if lm_logits.dtype != torch.float32: lm_logits = lm_logits.float() if return_past_key_values: return (lm_logits, loss, value, base_model_output.past_key_values) else: return (lm_logits, loss, value) def generate(self, *args, **kwargs): r""" We call `generate` on the wrapped model. """ return self.pretrained_model.generate(*args, **kwargs)
trl/trl/models/modeling_value_head.py/0
{ "file_path": "trl/trl/models/modeling_value_head.py", "repo_id": "trl", "token_count": 8181 }
627
# 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 typing import TYPE_CHECKING from ..import_utils import OptionalDependencyNotAvailable, _LazyModule, is_diffusers_available _import_structure = { "alignprop_config": ["AlignPropConfig"], "alignprop_trainer": ["AlignPropTrainer"], "bco_config": ["BCOConfig"], "bco_trainer": ["BCOTrainer"], "callbacks": [ "BEMACallback", "LogCompletionsCallback", "MergeModelCallback", "RichProgressCallback", "SyncRefModelCallback", "WinRateCallback", ], "cpo_config": ["CPOConfig"], "cpo_trainer": ["CPOTrainer"], "ddpo_config": ["DDPOConfig"], "dpo_config": ["DPOConfig", "FDivergenceConstants", "FDivergenceType"], "dpo_trainer": ["DPOTrainer"], "gkd_config": ["GKDConfig"], "gkd_trainer": ["GKDTrainer"], "grpo_config": ["GRPOConfig"], "grpo_trainer": ["GRPOTrainer"], "iterative_sft_config": ["IterativeSFTConfig"], "iterative_sft_trainer": ["IterativeSFTTrainer"], "judges": [ "AllTrueJudge", "BaseBinaryJudge", "BaseJudge", "BasePairwiseJudge", "BaseRankJudge", "HfPairwiseJudge", "OpenAIPairwiseJudge", "PairRMJudge", ], "kto_config": ["KTOConfig"], "kto_trainer": ["KTOTrainer"], "model_config": ["ModelConfig"], "nash_md_config": ["NashMDConfig"], "nash_md_trainer": ["NashMDTrainer"], "online_dpo_config": ["OnlineDPOConfig"], "online_dpo_trainer": ["OnlineDPOTrainer"], "orpo_config": ["ORPOConfig"], "orpo_trainer": ["ORPOTrainer"], "ppo_config": ["PPOConfig"], "ppo_trainer": ["PPOTrainer"], "prm_config": ["PRMConfig"], "prm_trainer": ["PRMTrainer"], "reward_config": ["RewardConfig"], "reward_trainer": ["RewardTrainer"], "rloo_config": ["RLOOConfig"], "rloo_trainer": ["RLOOTrainer"], "sft_config": ["SFTConfig"], "sft_trainer": ["SFTTrainer"], "utils": [ "RunningMoments", "compute_accuracy", "disable_dropout_in_model", "empty_cache", "peft_module_casting_to_bf16", ], "xpo_config": ["XPOConfig"], "xpo_trainer": ["XPOTrainer"], } try: if not is_diffusers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _import_structure["ddpo_trainer"] = ["DDPOTrainer"] if TYPE_CHECKING: from .alignprop_config import AlignPropConfig from .alignprop_trainer import AlignPropTrainer from .bco_config import BCOConfig from .bco_trainer import BCOTrainer from .callbacks import ( BEMACallback, LogCompletionsCallback, MergeModelCallback, RichProgressCallback, SyncRefModelCallback, WinRateCallback, ) from .cpo_config import CPOConfig from .cpo_trainer import CPOTrainer from .ddpo_config import DDPOConfig from .dpo_config import DPOConfig, FDivergenceConstants, FDivergenceType from .dpo_trainer import DPOTrainer from .gkd_config import GKDConfig from .gkd_trainer import GKDTrainer from .grpo_config import GRPOConfig from .grpo_trainer import GRPOTrainer from .iterative_sft_trainer import IterativeSFTConfig, IterativeSFTTrainer from .judges import ( AllTrueJudge, BaseBinaryJudge, BaseJudge, BasePairwiseJudge, BaseRankJudge, HfPairwiseJudge, OpenAIPairwiseJudge, PairRMJudge, ) from .kto_config import KTOConfig from .kto_trainer import KTOTrainer from .model_config import ModelConfig from .nash_md_config import NashMDConfig from .nash_md_trainer import NashMDTrainer from .online_dpo_config import OnlineDPOConfig from .online_dpo_trainer import OnlineDPOTrainer from .orpo_config import ORPOConfig from .orpo_trainer import ORPOTrainer from .ppo_config import PPOConfig from .ppo_trainer import PPOTrainer from .prm_config import PRMConfig from .prm_trainer import PRMTrainer from .reward_config import RewardConfig from .reward_trainer import RewardTrainer from .rloo_config import RLOOConfig from .rloo_trainer import RLOOTrainer from .sft_config import SFTConfig from .sft_trainer import SFTTrainer from .utils import ( RunningMoments, compute_accuracy, disable_dropout_in_model, empty_cache, peft_module_casting_to_bf16, ) from .xpo_config import XPOConfig from .xpo_trainer import XPOTrainer try: if not is_diffusers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .ddpo_trainer import DDPOTrainer else: import sys sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
trl/trl/trainer/__init__.py/0
{ "file_path": "trl/trl/trainer/__init__.py", "repo_id": "trl", "token_count": 2220 }
628
# 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 IterativeSFTConfig(TrainingArguments): r""" Configuration class for the [`IterativeSFTTrainer`]. <Tip warning={true}> The [`IterativeSFTTrainer`] is deprecated and will be removed in version 0.24.0. Please use the [`SFTTrainer`]. </Tip> This class includes only the parameters that are specific to Iterative 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 [`IterativeSFTTrainer`] is provided as a string. > Parameters that control the data preprocessing max_length (`int` or `None`, *optional*, defaults to `None`): Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated. truncation_mode (`str`, *optional*, defaults to `"keep_end"`): The truncation mode to use, either `"keep_end"` or `"keep_start"`. optimize_device_cache (`bool`, *optional*, defaults to `False`): Whether to optimize accelerator cache for slightly more memory-efficient training. """ _VALID_DICT_FIELDS = TrainingArguments._VALID_DICT_FIELDS + ["model_init_kwargs"] # Parameters whose default values are overridden from TrainingArguments 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." }, ) # 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 `IterativeSFTTrainer` is provided as a string." }, ) # Parameters that control the data preprocessing max_length: Optional[int] = field( default=None, metadata={ "help": "Maximum length of the tokenized sequence. Sequences longer than `max_length` are truncated." }, ) truncation_mode: str = field( default="keep_end", metadata={"help": "The truncation mode to use, either 'keep_end' or 'keep_start'."}, ) optimize_device_cache: bool = field( default=False, metadata={"help": "Whether to optimize accelerator cache for slightly more memory-efficient training."}, ) def __post_init__(self): self.bf16 = not (self.fp16) if self.bf16 is None else self.bf16 super().__post_init__() if self.truncation_mode not in ["keep_end", "keep_start"]: raise ValueError(f"truncation_mode must be either 'keep_end' or 'keep_start', got {self.truncation_mode}")
trl/trl/trainer/iterative_sft_config.py/0
{ "file_path": "trl/trl/trainer/iterative_sft_config.py", "repo_id": "trl", "token_count": 1665 }
629
# What is Function Calling? Function-calling is a **way for an LLM to take actions on its environment**. It was first [introduced in GPT-4](https://openai.com/index/function-calling-and-other-api-updates/), and was later reproduced in other models. Just like the tools of an Agent, function-calling gives the model the capacity to **take an action on its environment**. However, the function calling capacity **is learned by the model**, and relies **less on prompting than other agents techniques**. During Unit 1, the Agent **didn't learn to use the Tools**, we just provided the list, and we relied on the fact that the model **was able to generalize on defining a plan using these Tools**. While here, **with function-calling, the Agent is fine-tuned (trained) to use Tools**. ## How does the model "learn" to take an action? In Unit 1, we explored the general workflow of an agent. Once the user has given some tools to the agent and prompted it with a query, the model will cycle through: 1. *Think* : What action(s) do I need to take in order to fulfill the objective. 2. *Act* : Format the action with the correct parameter and stop the generation. 3. *Observe* : Get back the result from the execution. In a "typical" conversation with a model through an API, the conversation will alternate between user and assistant messages like this: ```python conversation = [ {"role": "user", "content": "I need help with my order"}, {"role": "assistant", "content": "I'd be happy to help. Could you provide your order number?"}, {"role": "user", "content": "It's ORDER-123"}, ] ``` Function-calling brings **new roles to the conversation**! 1. One new role for an **Action** 2. One new role for an **Observation** If we take the [Mistral API](https://docs.mistral.ai/capabilities/function_calling/) as an example, it would look like this: ```python conversation = [ { "role": "user", "content": "What's the status of my transaction T1001?" }, { "role": "assistant", "content": "", "function_call": { "name": "retrieve_payment_status", "arguments": "{\"transaction_id\": \"T1001\"}" } }, { "role": "tool", "name": "retrieve_payment_status", "content": "{\"status\": \"Paid\"}" }, { "role": "assistant", "content": "Your transaction T1001 has been successfully paid." } ] ``` > ... But you said there's a new role for function calls? **Yes and no**, in this case and in a lot of other APIs, the model formats the action to take as an "assistant" message. The chat template will then represent this as **special tokens** for function-calling. - `[AVAILABLE_TOOLS]` – Start the list of available tools - `[/AVAILABLE_TOOLS]` – End the list of available tools - `[TOOL_CALLS]` – Make a call to a tool (i.e., take an "Action") - `[TOOL_RESULTS]` – "Observe" the result of the action - `[/TOOL_RESULTS]` – End of the observation (i.e., the model can decode again) We'll talk again about function-calling in this course, but if you want to dive deeper you can check [this excellent documentation section](https://docs.mistral.ai/capabilities/function_calling/). --- Now that we learned what function-calling is and how it works, let's **add some function-calling capabilities to a model that does not have those capacities yet**: [google/gemma-2-2b-it](https://huggingface.co/google/gemma-2-2b-it), by appending some new special tokens to the model. To be able to do that, **we need first to understand fine-tuning and LoRA**.
agents-course/units/en/bonus-unit1/what-is-function-calling.mdx/0
{ "file_path": "agents-course/units/en/bonus-unit1/what-is-function-calling.mdx", "repo_id": "agents-course", "token_count": 1138 }
0
# Actions: Enabling the Agent to Engage with Its Environment <Tip> In this section, we explore the concrete steps an AI agent takes to interact with its environment. We’ll cover how actions are represented (using JSON or code), the importance of the stop and parse approach, and introduce different types of agents. </Tip> Actions are the concrete steps an **AI agent takes to interact with its environment**. Whether it’s browsing the web for information or controlling a physical device, each action is a deliberate operation executed by the agent. For example, an agent assisting with customer service might retrieve customer data, offer support articles, or transfer issues to a human representative. ## Types of Agent Actions There are multiple types of Agents that take actions differently: | Type of Agent | Description | |------------------------|--------------------------------------------------------------------------------------------------| | JSON Agent | The Action to take is specified in JSON format. | | Code Agent | The Agent writes a code block that is interpreted externally. | | Function-calling Agent | It is a subcategory of the JSON Agent which has been fine-tuned to generate a new message for each action. | Actions themselves can serve many purposes: | Type of Action | Description | |--------------------------|------------------------------------------------------------------------------------------| | Information Gathering | Performing web searches, querying databases, or retrieving documents. | | Tool Usage | Making API calls, running calculations, and executing code. | | Environment Interaction | Manipulating digital interfaces or controlling physical devices. | | Communication | Engaging with users via chat or collaborating with other agents. | The LLM only handles text and uses it to describe the action it wants to take and the parameters to supply to the tool. For an agent to work properly, the LLM must STOP generating new tokens after emitting all the tokens to define a complete Action. This passes control from the LLM back to the agent and ensures the result is parseable - whether the intended format is JSON, code, or function-calling. ## The Stop and Parse Approach One key method for implementing actions is the **stop and parse approach**. This method ensures that the agent’s output is structured and predictable: 1. **Generation in a Structured Format**: The agent outputs its intended action in a clear, predetermined format (JSON or code). 2. **Halting Further Generation**: Once the text defining the action has been emitted, **the LLM stops generating additional tokens**. This prevents extra or erroneous output. 3. **Parsing the Output**: An external parser reads the formatted action, determines which Tool to call, and extracts the required parameters. For example, an agent needing to check the weather might output: ```json Thought: I need to check the current weather for New York. Action : { "action": "get_weather", "action_input": {"location": "New York"} } ``` The framework can then easily parse the name of the function to call and the arguments to apply. This clear, machine-readable format minimizes errors and enables external tools to accurately process the agent’s command. Note: Function-calling agents operate similarly by structuring each action so that a designated function is invoked with the correct arguments. We'll dive deeper into those types of Agents in a future Unit. ## Code Agents An alternative approach is using *Code Agents*. The idea is: **instead of outputting a simple JSON object**, a Code Agent generates an **executable code block—typically in a high-level language like Python**. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/code-vs-json-actions.png" alt="Code Agents" /> This approach offers several advantages: - **Expressiveness:** Code can naturally represent complex logic, including loops, conditionals, and nested functions, providing greater flexibility than JSON. - **Modularity and Reusability:** Generated code can include functions and modules that are reusable across different actions or tasks. - **Enhanced Debuggability:** With a well-defined programming syntax, code errors are often easier to detect and correct. - **Direct Integration:** Code Agents can integrate directly with external libraries and APIs, enabling more complex operations such as data processing or real-time decision making. You must keep in mind that executing LLM-generated code may pose security risks, from prompt injection to the execution of harmful code. That's why it's recommended to use AI agent frameworks like `smolagents` that integrate default safeguards. If you want to know more about the risks and how to mitigate them, [please have a look at this dedicated section](https://huggingface.co/docs/smolagents/tutorials/secure_code_execution). For example, a Code Agent tasked with fetching the weather might generate the following Python snippet: ```python # Code Agent Example: Retrieve Weather Information def get_weather(city): import requests api_url = f"https://api.weather.com/v1/location/{city}?apiKey=YOUR_API_KEY" response = requests.get(api_url) if response.status_code == 200: data = response.json() return data.get("weather", "No weather information available") else: return "Error: Unable to fetch weather data." # Execute the function and prepare the final answer result = get_weather("New York") final_answer = f"The current weather in New York is: {result}" print(final_answer) ``` In this example, the Code Agent: - Retrieves weather data **via an API call**, - Processes the response, - And uses the print() function to output a final answer. This method **also follows the stop and parse approach** by clearly delimiting the code block and signaling when execution is complete (here, by printing the final_answer). --- We learned that Actions bridge an agent's internal reasoning and its real-world interactions by executing clear, structured tasks—whether through JSON, code, or function calls. This deliberate execution ensures that each action is precise and ready for external processing via the stop and parse approach. In the next section, we will explore Observations to see how agents capture and integrate feedback from their environment. After this, we will **finally be ready to build our first Agent!**
agents-course/units/en/unit1/actions.mdx/0
{ "file_path": "agents-course/units/en/unit1/actions.mdx", "repo_id": "agents-course", "token_count": 1912 }
1
# Building Blocks of LangGraph To build applications with LangGraph, you need to understand its core components. Let's explore the fundamental building blocks that make up a LangGraph application. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/LangGraph/Building_blocks.png" alt="Building Blocks" width="70%"/> An application in LangGraph starts from an **entrypoint**, and depending on the execution, the flow may go to one function or another until it reaches the END. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/LangGraph/application.png" alt="Application"/> ## 1. State **State** is the central concept in LangGraph. It represents all the information that flows through your application. ```python from typing_extensions import TypedDict class State(TypedDict): graph_state: str ``` The state is **User defined**, hence the fields should carefully be crafted to contain all data needed for decision-making process! > 💡 **Tip:** Think carefully about what information your application needs to track between steps. ## 2. Nodes **Nodes** are python functions. Each node: - Takes the state as input - Performs some operation - Returns updates to the state ```python def node_1(state): print("---Node 1---") return {"graph_state": state['graph_state'] +" I am"} def node_2(state): print("---Node 2---") return {"graph_state": state['graph_state'] +" happy!"} def node_3(state): print("---Node 3---") return {"graph_state": state['graph_state'] +" sad!"} ``` For example, Nodes can contain: - **LLM calls**: Generate text or make decisions - **Tool calls**: Interact with external systems - **Conditional logic**: Determine next steps - **Human intervention**: Get input from users > 💡 **Info:** Some nodes necessary for the whole workflow like START and END exist from langGraph directly. ## 3. Edges **Edges** connect nodes and define the possible paths through your graph: ```python import random from typing import Literal def decide_mood(state) -> Literal["node_2", "node_3"]: # Often, we will use state to decide on the next node to visit user_input = state['graph_state'] # Here, let's just do a 50 / 50 split between nodes 2, 3 if random.random() < 0.5: # 50% of the time, we return Node 2 return "node_2" # 50% of the time, we return Node 3 return "node_3" ``` Edges can be: - **Direct**: Always go from node A to node B - **Conditional**: Choose the next node based on the current state ## 4. StateGraph The **StateGraph** is the container that holds your entire agent workflow: ```python from IPython.display import Image, display from langgraph.graph import StateGraph, START, END # Build graph builder = StateGraph(State) builder.add_node("node_1", node_1) builder.add_node("node_2", node_2) builder.add_node("node_3", node_3) # Logic builder.add_edge(START, "node_1") builder.add_conditional_edges("node_1", decide_mood) builder.add_edge("node_2", END) builder.add_edge("node_3", END) # Add graph = builder.compile() ``` Which can then be visualized! ```python # View display(Image(graph.get_graph().draw_mermaid_png())) ``` <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/LangGraph/basic_graph.jpeg" alt="Graph Visualization"/> But most importantly, invoked: ```python graph.invoke({"graph_state" : "Hi, this is Lance."}) ``` output : ``` ---Node 1--- ---Node 3--- {'graph_state': 'Hi, this is Lance. I am sad!'} ``` ## What's Next? In the next section, we'll put these concepts into practice by building our first graph. This graph lets Alfred take in your e-mails, classify them, and craft a preliminary answer if they are genuine.
agents-course/units/en/unit2/langgraph/building_blocks.mdx/0
{ "file_path": "agents-course/units/en/unit2/langgraph/building_blocks.mdx", "repo_id": "agents-course", "token_count": 1207 }
2
# Creating agentic workflows in LlamaIndex A workflow in LlamaIndex provides a structured way to organize your code into sequential and manageable steps. Such a workflow is created by defining `Steps` which are triggered by `Events`, and themselves emit `Events` to trigger further steps. Let's take a look at Alfred showing a LlamaIndex workflow for a RAG task. ![Workflow Schematic](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/llama-index/workflows.png) **Workflows offer several key benefits:** - Clear organization of code into discrete steps - Event-driven architecture for flexible control flow - Type-safe communication between steps - Built-in state management - Support for both simple and complex agent interactions As you might have guessed, **workflows strike a great balance between the autonomy of agents while maintaining control over the overall workflow.** So, let's learn how to create a workflow ourselves! ## Creating Workflows <Tip> You can follow the code in <a href="https://huggingface.co/agents-course/notebooks/blob/main/unit2/llama-index/workflows.ipynb" target="_blank">this notebook</a> that you can run using Google Colab. </Tip> ### Basic Workflow Creation <details> <summary>Install the Workflow package</summary> As introduced in the <a href="./llama-hub">section on the LlamaHub</a>, we can install the Workflow package with the following command: ```python pip install llama-index-utils-workflow ``` </details> We can create a single-step workflow by defining a class that inherits from `Workflow` and decorating your functions with `@step`. We will also need to add `StartEvent` and `StopEvent`, which are special events that are used to indicate the start and end of the workflow. ```python from llama_index.core.workflow import StartEvent, StopEvent, Workflow, step class MyWorkflow(Workflow): @step async def my_step(self, ev: StartEvent) -> StopEvent: # do something here return StopEvent(result="Hello, world!") w = MyWorkflow(timeout=10, verbose=False) result = await w.run() ``` As you can see, we can now run the workflow by calling `w.run()`. ### Connecting Multiple Steps To connect multiple steps, we **create custom events that carry data between steps.** To do so, we need to add an `Event` that is passed between the steps and transfers the output of the first step to the second step. ```python from llama_index.core.workflow import Event class ProcessingEvent(Event): intermediate_result: str class MultiStepWorkflow(Workflow): @step async def step_one(self, ev: StartEvent) -> ProcessingEvent: # Process initial data return ProcessingEvent(intermediate_result="Step 1 complete") @step async def step_two(self, ev: ProcessingEvent) -> StopEvent: # Use the intermediate result final_result = f"Finished processing: {ev.intermediate_result}" return StopEvent(result=final_result) w = MultiStepWorkflow(timeout=10, verbose=False) result = await w.run() result ``` The type hinting is important here, as it ensures that the workflow is executed correctly. Let's complicate things a bit more! ### Loops and Branches The type hinting is the most powerful part of workflows because it allows us to create branches, loops, and joins to facilitate more complex workflows. Let's show an example of **creating a loop** by using the union operator `|`. In the example below, we see that the `LoopEvent` is taken as input for the step and can also be returned as output. ```python from llama_index.core.workflow import Event import random class ProcessingEvent(Event): intermediate_result: str class LoopEvent(Event): loop_output: str class MultiStepWorkflow(Workflow): @step async def step_one(self, ev: StartEvent | LoopEvent) -> ProcessingEvent | LoopEvent: if random.randint(0, 1) == 0: print("Bad thing happened") return LoopEvent(loop_output="Back to step one.") else: print("Good thing happened") return ProcessingEvent(intermediate_result="First step complete.") @step async def step_two(self, ev: ProcessingEvent) -> StopEvent: # Use the intermediate result final_result = f"Finished processing: {ev.intermediate_result}" return StopEvent(result=final_result) w = MultiStepWorkflow(verbose=False) result = await w.run() result ``` ### Drawing Workflows We can also draw workflows. Let's use the `draw_all_possible_flows` function to draw the workflow. This stores the workflow in an HTML file. ```python from llama_index.utils.workflow import draw_all_possible_flows w = ... # as defined in the previous section draw_all_possible_flows(w, "flow.html") ``` ![workflow drawing](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/llama-index/workflow-draw.png) There is one last cool trick that we will cover in the course, which is the ability to add state to the workflow. ### State Management State management is useful when you want to keep track of the state of the workflow, so that every step has access to the same state. We can do this by using the `Context` type hint on top of a parameter in the step function. ```python from llama_index.core.workflow import Context, StartEvent, StopEvent @step async def query(self, ctx: Context, ev: StartEvent) -> StopEvent: # store query in the context await ctx.store.set("query", "What is the capital of France?") # do something with context and event val = ... # retrieve query from the context query = await ctx.store.get("query") return StopEvent(result=val) ``` Great! Now you know how to create basic workflows in LlamaIndex! <Tip>There are some more complex nuances to workflows, which you can learn about in <a href="https://docs.llamaindex.ai/en/stable/understanding/workflows/">the LlamaIndex documentation</a>.</Tip> However, there is another way to create workflows, which relies on the `AgentWorkflow` class. Let's take a look at how we can use this to create a multi-agent workflow. ## Automating workflows with Multi-Agent Workflows Instead of manual workflow creation, we can use the **`AgentWorkflow` class to create a multi-agent workflow**. The `AgentWorkflow` uses Workflow Agents to allow you to create a system of one or more agents that can collaborate and hand off tasks to each other based on their specialized capabilities. This enables building complex agent systems where different agents handle different aspects of a task. Instead of importing classes from `llama_index.core.agent`, we will import the agent classes from `llama_index.core.agent.workflow`. One agent must be designated as the root agent in the `AgentWorkflow` constructor. When a user message comes in, it is first routed to the root agent. Each agent can then: - Handle the request directly using their tools - Handoff to another agent better suited for the task - Return a response to the user Let's see how to create a multi-agent workflow. ```python from llama_index.core.agent.workflow import AgentWorkflow, ReActAgent from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI # Define some tools def add(a: int, b: int) -> int: """Add two numbers.""" return a + b def multiply(a: int, b: int) -> int: """Multiply two numbers.""" return a * b llm = HuggingFaceInferenceAPI(model_name="Qwen/Qwen2.5-Coder-32B-Instruct") # we can pass functions directly without FunctionTool -- the fn/docstring are parsed for the name/description multiply_agent = ReActAgent( name="multiply_agent", description="Is able to multiply two integers", system_prompt="A helpful assistant that can use a tool to multiply numbers.", tools=[multiply], llm=llm, ) addition_agent = ReActAgent( name="add_agent", description="Is able to add two integers", system_prompt="A helpful assistant that can use a tool to add numbers.", tools=[add], llm=llm, ) # Create the workflow workflow = AgentWorkflow( agents=[multiply_agent, addition_agent], root_agent="multiply_agent", ) # Run the system response = await workflow.run(user_msg="Can you add 5 and 3?") ``` Agent tools can also modify the workflow state we mentioned earlier. Before starting the workflow, we can provide an initial state dict that will be available to all agents. The state is stored in the state key of the workflow context. It will be injected into the state_prompt which augments each new user message. Let's inject a counter to count function calls by modifying the previous example: ```python from llama_index.core.workflow import Context # Define some tools async def add(ctx: Context, a: int, b: int) -> int: """Add two numbers.""" # update our count cur_state = await ctx.store.get("state") cur_state["num_fn_calls"] += 1 await ctx.store.set("state", cur_state) return a + b async def multiply(ctx: Context, a: int, b: int) -> int: """Multiply two numbers.""" # update our count cur_state = await ctx.store.get("state") cur_state["num_fn_calls"] += 1 await ctx.store.set("state", cur_state) return a * b ... workflow = AgentWorkflow( agents=[multiply_agent, addition_agent], root_agent="multiply_agent", initial_state={"num_fn_calls": 0}, state_prompt="Current state: {state}. User message: {msg}", ) # run the workflow with context ctx = Context(workflow) response = await workflow.run(user_msg="Can you add 5 and 3?", ctx=ctx) # pull out and inspect the state state = await ctx.store.get("state") print(state["num_fn_calls"]) ``` Congratulations! You have now mastered the basics of Agents in LlamaIndex! 🎉 Let's continue with one final quiz to solidify your knowledge! 🚀
agents-course/units/en/unit2/llama-index/workflows.mdx/0
{ "file_path": "agents-course/units/en/unit2/llama-index/workflows.mdx", "repo_id": "agents-course", "token_count": 2976 }
3
# Conclusion In this unit, we've learned how to create an agentic RAG system to help Alfred, our friendly neighborhood agent, prepare for and manage an extravagant gala. The combination of RAG with agentic capabilities demonstrates how powerful AI assistants can become when they have: - Access to structured knowledge (guest information) - Ability to retrieve real-time information (web search) - Domain-specific tools (weather information, Hub stats) - Memory of past interactions With these capabilities, Alfred is now well-equipped to be the perfect host, able to answer questions about guests, provide up-to-date information, and ensure the gala runs smoothly—even managing the perfect timing for the fireworks display! <Tip> Now that you've built a complete agent, you might want to explore: - Creating more specialized tools for your own use cases - Implementing more sophisticated RAG systems with embeddings - Building multi-agent systems where agents can collaborate - Deploying your agent as a service that others can interact with </Tip>
agents-course/units/en/unit3/agentic-rag/conclusion.mdx/0
{ "file_path": "agents-course/units/en/unit3/agentic-rag/conclusion.mdx", "repo_id": "agents-course", "token_count": 231 }
4
<CourseFloatingBanner chapter={2} classNames="absolute z-10 right-0 top-0" notebooks={[ {label: "Google Colab", value: "https://colab.research.google.com/#fileId=https://huggingface.co/agents-course/notebooks/blob/main/bonus-unit2/monitoring-and-evaluating-agents.ipynb"}, ]} /> # Unidad Extra 2: Observabilidad y Evaluación de Agentes <Tip> Puedes seguir el código en <a href="https://huggingface.co/agents-course/notebooks/blob/main/bonus-unit2/monitoring-and-evaluating-agents-notebook.ipynb" target="_blank">este notebook</a> que puedes ejecutar usando Google Colab. </Tip> En este notebook, aprenderemos cómo **monitorear los pasos internos (trazos) de nuestro agente de IA** y **evaluar su rendimiento** utilizando herramientas de observabilidad de código abierto. La capacidad de observar y evaluar el comportamiento de un agente es esencial para: - Depurar problemas cuando las tareas fallan o producen resultados subóptimos - Monitorear costos y rendimiento en tiempo real - Mejorar la fiabilidad y seguridad a través de retroalimentación continua ## Requisitos del Ejercicio 🏗️ Antes de ejecutar este notebook, asegúrate de que has: 🔲 📚 **Estudiado** [Introducción a los Agentes](https://huggingface.co/learn/agents-course/unit1/introduction) 🔲 📚 **Estudiado** [El framework smolagents](https://huggingface.co/learn/agents-course/unit2/smolagents/introduction) ## Paso 0: Instalar las Librerías Necesarias Necesitaremos algunas librerías que nos permitan ejecutar, monitorear y evaluar nuestros agentes: ```python %pip install 'smolagents[telemetry]' %pip install opentelemetry-sdk opentelemetry-exporter-otlp openinference-instrumentation-smolagents %pip install langfuse datasets 'smolagents[gradio]' ``` ## Paso 1: Instrumentar tu Agente En este notebook, utilizaremos [Langfuse](https://langfuse.com/) como nuestra herramienta de observabilidad, pero puedes usar **cualquier otro servicio compatible con OpenTelemetry**. El código a continuación muestra cómo configurar variables de entorno para Langfuse (o cualquier endpoint OTel) y cómo instrumentar tu smolagent. **Nota:** Si estás utilizando LlamaIndex o LangGraph, puedes encontrar documentación sobre cómo instrumentarlos [aquí](https://langfuse.com/docs/integrations/llama-index/workflows) y [aquí](https://langfuse.com/docs/integrations/langchain/example-python-langgraph). Primero, vamos a configurar la variable de entorno correcta para establecer la conexión con el endpoint OpenTelemetry de Langfuse. ```python import os import base64 # Obtén tus propias claves desde https://cloud.langfuse.com LANGFUSE_PUBLIC_KEY = = "pk-lf-..." LANGFUSE_SECRET_KEY = "sk-lf-..." os.environ["LANGFUSE_PUBLIC_KEY"] = LANGFUSE_PUBLIC_KEY os.environ["LANGFUSE_SECRET_KEY"] = LANGFUSE_SECRET_KEY os.environ["LANGFUSE_HOST"] = "https://cloud.langfuse.com" # 🇪🇺 ejemplo de región EU # os.environ["LANGFUSE_HOST"] = "https://us.cloud.langfuse.com" # 🇺🇸 ejemplo de región US LANGFUSE_AUTH = base64.b64encode( f"{LANGFUSE_PUBLIC_KEY}:{LANGFUSE_SECRET_KEY}".encode() ).decode() os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = os.environ.get("LANGFUSE_HOST") + "/api/public/otel" os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = f"Authorization=Basic {LANGFUSE_AUTH}" ``` También necesitamos configurar nuestro token de Hugging Face para las llamadas de inferencia. ```python # Configura tu token de Hugging Face y otros tokens/secretos como variables de entorno os.environ["HF_TOKEN"] = "hf_..." ``` A continuación, podemos configurar un proveedor de trazoss para nuestro OpenTelemetry configurado. ```python from opentelemetry.sdk.trace import TracerProvider from openinference.instrumentation.smolagents import SmolagentsInstrumentor from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter from opentelemetry.sdk.trace.export import SimpleSpanProcessor # Crear un TracerProvider para OpenTelemetry trace_provider = TracerProvider() # Añadir un SimpleSpanProcessor con el OTLPSpanExporter para enviar trazoss trace_provider.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter())) # Establecer el proveedor de trazas predeterminado global from opentelemetry import trace trace.set_tracer_provider(trace_provider) tracer = trace.get_tracer(__name__) # Instrumentar smolagents con el proveedor configurado SmolagentsInstrumentor().instrument(tracer_provider=trace_provider) ``` ## Paso 2: Probar tu Instrumentación Aquí hay un simple CodeAgent de smolagents que calcula `1+1`. Lo ejecutamos para confirmar que la instrumentación está funcionando correctamente. Si todo está configurado correctamente, verás registros/spans en tu panel de observabilidad. ```python from smolagents import InferenceClientModel, CodeAgent # Crear un agente simple para probar la instrumentación agent = CodeAgent( tools=[], model=InferenceClientModel() ) agent.run("1+1=") ``` Revisa tu [Panel de rastros de Langfuse](https://cloud.langfuse.com/traces) (o tu herramienta de observabilidad elegida) para confirmar que los spans y registros han sido grabados. Captura de pantalla de ejemplo de Langfuse: ![Ejemplo de rastros en Langfuse](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/first-example-trace.png) _[Enlace a los rastros](https://cloud.langfuse.com/project/cloramnkj0002jz088vzn1ja4/traces/1b94d6888258e0998329cdb72a371155?timestamp=2025-03-10T11%3A59%3A41.743Z)_ ## Paso 3: Observar y Evaluar un Agente Más Complejo Ahora que has confirmado que tu instrumentación funciona, probemos una consulta más compleja para ver cómo se rastrean las métricas avanzadas (uso de tokens, latencia, costos, etc.). ```python from smolagents import (CodeAgent, DuckDuckGoSearchTool, InferenceClientModel) search_tool = DuckDuckGoSearchTool() agent = CodeAgent(tools=[search_tool], model=InferenceClientModel()) agent.run("¿Cuántos cubos de Rubik podrías meter dentro de la Catedral de Notre Dame?") ``` ### Estructura de Rastros La mayoría de las herramientas de observabilidad registran una **rastro** que contiene **spans**, que representan cada paso de la lógica de tu agente. Aquí, el rastro contiene la ejecución general del agente y sub-spans para: - Las llamadas a herramientas (DuckDuckGoSearchTool) - Las llamadas al LLM (InferenceClientModel) Puedes inspeccionarlos para ver precisamente dónde se gasta el tiempo, cuántos tokens se utilizan, etc.: ![Árbol de rastros en Langfuse](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/trace-tree.png) _[Enlace a los rastros](https://cloud.langfuse.com/project/cloramnkj0002jz088vzn1ja4/traces/1ac33b89ffd5e75d4265b62900c348ed?timestamp=2025-03-07T13%3A45%3A09.149Z&display=preview)_ ## Evaluación en Línea En la sección anterior, aprendimos sobre la diferencia entre evaluación en línea y fuera de línea. Ahora, veremos cómo monitorear tu agente en producción y evaluarlo en vivo. ### Métricas Comunes para Seguir en Producción 1. **Costos** — La instrumentación de smolagents captura el uso de tokens, que puedes transformar en costos aproximados asignando un precio por token. 2. **Latencia** — Observa el tiempo que toma completar cada paso, o la ejecución completa. 3. **Retroalimentación del Usuario** — Los usuarios pueden proporcionar retroalimentación directa (pulgar arriba/abajo) para ayudar a refinar o corregir el agente. 4. **LLM-como-Juez** — Utiliza un LLM separado para evaluar la salida de tu agente en tiempo casi real (por ejemplo, verificando toxicidad o corrección). A continuación, mostramos ejemplos de estas métricas. #### 1. Costos A continuación se muestra una captura de pantalla que muestra el uso para llamadas a `Qwen2.5-Coder-32B-Instruct`. Esto es útil para ver pasos costosos y optimizar tu agente. ![Costos](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/smolagents-costs.png) _[Enlace a los rastros](https://cloud.langfuse.com/project/cloramnkj0002jz088vzn1ja4/traces/1ac33b89ffd5e75d4265b62900c348ed?timestamp=2025-03-07T13%3A45%3A09.149Z&display=preview)_ #### 2. Latencia También podemos ver cuánto tiempo tomó completar cada paso. En el ejemplo a continuación, toda la conversación tomó 32 segundos, que puedes desglosar por paso. Esto te ayuda a identificar cuellos de botella y optimizar tu agente. ![Latencia](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/smolagents-latency.png) _[Enlace a los rastros](https://cloud.langfuse.com/project/cloramnkj0002jz088vzn1ja4/traces/1ac33b89ffd5e75d4265b62900c348ed?timestamp=2025-03-07T13%3A45%3A09.149Z&display=preview)_ #### 3. Atributos Adicionales También puedes pasar atributos adicionales, como IDs de usuario, IDs de sesión o etiquetas, configurándolos en los spans. Por ejemplo, la instrumentación de smolagents utiliza OpenTelemetry para adjuntar atributos como `langfuse.user.id` o etiquetas personalizadas. ```python from smolagents import (CodeAgent, DuckDuckGoSearchTool, InferenceClientModel) from opentelemetry import trace search_tool = DuckDuckGoSearchTool() agent = CodeAgent( tools=[search_tool], model=InferenceClientModel() ) with tracer.start_as_current_span("Smolagent-Trace") as span: span.set_attribute("langfuse.user.id", "smolagent-user-123") span.set_attribute("langfuse.session.id", "smolagent-session-123456789") span.set_attribute("langfuse.tags", ["city-question", "testing-agents"]) agent.run("¿Cuál es la capital de Alemania?") ``` ![Mejorando las ejecuciones de agentes con métricas adicionales](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/smolagents-attributes.png) #### 4. Retroalimentación del Usuario Si tu agente está integrado en una interfaz de usuario, puedes registrar la retroalimentación directa del usuario (como un pulgar arriba/abajo en una interfaz de chat). A continuación se muestra un ejemplo utilizando [Gradio](https://gradio.app/) para integrar un chat con un mecanismo de retroalimentación simple. En el fragmento de código a continuación, cuando un usuario envía un mensaje de chat, capturamos el ID de traza de OpenTelemetry. Si al usuario le gusta/no le gusta la última respuesta, adjuntamos una puntuación a la traza. ```python import gradio as gr from opentelemetry.trace import format_trace_id from smolagents import (CodeAgent, InferenceClientModel) from langfuse import Langfuse langfuse = Langfuse() model = InferenceClientModel() agent = CodeAgent(tools=[], model=model, add_base_tools=True) formatted_trace_id = None # Almacenaremos el trace_id actual globalmente para demostración def respond(prompt, history): with trace.get_tracer(__name__).start_as_current_span("Smolagent-Trace") as span: output = agent.run(prompt) current_span = trace.get_current_span() span_context = current_span.get_span_context() trace_id = span_context.trace_id global formatted_trace_id formatted_trace_id = str(format_trace_id(trace_id)) langfuse.trace(id=formatted_trace_id, input=prompt, output=output) history.append({"role": "assistant", "content": str(output)}) return history def handle_like(data: gr.LikeData): # Para demostración, mapeamos la retroalimentación del usuario a un 1 (me gusta) o 0 (no me gusta) if data.liked: langfuse.score( value=1, name="user-feedback", trace_id=formatted_trace_id ) else: langfuse.score( value=0, name="user-feedback", trace_id=formatted_trace_id ) with gr.Blocks() as demo: chatbot = gr.Chatbot(label="Chat", type="messages") prompt_box = gr.Textbox(placeholder="Escribe tu mensaje...", label="Tu mensaje") # Cuando el usuario presiona 'Enter' en el prompt, ejecutamos 'respond' prompt_box.submit( fn=respond, inputs=[prompt_box, chatbot], outputs=chatbot ) # Cuando el usuario hace clic en un botón de 'me gusta' en un mensaje, ejecutamos 'handle_like' chatbot.like(handle_like, None, None) demo.launch() ``` La retroalimentación del usuario se captura entonces en tu herramienta de observabilidad: ![La retroalimentación del usuario se captura en Langfuse](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/user-feedback-gradio.png) #### 5. LLM-como-Juez LLM-como-Juez es otra forma de evaluar automáticamente la salida de tu agente. Puedes configurar una llamada LLM separada para medir la corrección, toxicidad, estilo o cualquier otro criterio que te importe. **Flujo de trabajo**: 1. Defines una **Plantilla de Evaluación**, por ejemplo, "Verifica si el texto es tóxico". 2. Cada vez que tu agente genera una salida, pasas esa salida a tu LLM "juez" con la plantilla. 3. El LLM juez responde con una calificación o etiqueta que registras en tu herramienta de observabilidad. Ejemplo de Langfuse: ![Plantilla de Evaluación LLM-como-Juez](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/evaluator-template.png) ![Evaluador LLM-como-Juez](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/evaluator.png) ```python # Ejemplo: Verificar si la salida del agente es tóxica o no. from smolagents import (CodeAgent, DuckDuckGoSearchTool, InferenceClientModel) search_tool = DuckDuckGoSearchTool() agent = CodeAgent(tools=[search_tool], model=InferenceClientModel()) agent.run("¿Puede comer zanahorias mejorar tu visión?") ``` Puedes ver que la respuesta de este ejemplo se juzga como "no tóxica". ![Puntuación de Evaluación LLM-como-Juez](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/llm-as-a-judge-score.png) #### 6. Resumen de Métricas de Observabilidad Todas estas métricas pueden visualizarse juntas en paneles. Esto te permite ver rápidamente cómo se desempeña tu agente a través de muchas sesiones y te ayuda a seguir las métricas de calidad a lo largo del tiempo. ![Resumen de métricas de observabilidad](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/langfuse-dashboard.png) ## Evaluación fuera de línea La evaluación en línea es esencial para la retroalimentación en vivo, pero también necesitas **evaluación fuera de línea**—verificaciones sistemáticas antes o durante el desarrollo. Esto ayuda a mantener la calidad y fiabilidad antes de implementar cambios en producción. ### Evaluación con Conjuntos de Datos En la evaluación fuera de línea, típicamente: 1. Tienes un conjunto de datos de referencia (con pares de prompt y salida esperada) 2. Ejecutas tu agente en ese conjunto de datos 3. Comparas las salidas con los resultados esperados o utilizas un mecanismo de puntuación adicional A continuación, demostramos este enfoque con el [conjunto de datos GSM8K](https://huggingface.co/datasets/gsm8k), que contiene preguntas matemáticas y soluciones. ```python import pandas as pd from datasets import load_dataset # Obtener GSM8K desde Hugging Face dataset = load_dataset("openai/gsm8k", 'main', split='train') df = pd.DataFrame(dataset) print("Primeras filas del conjunto de datos GSM8K:") print(df.head()) ``` A continuación, creamos una entidad de conjunto de datos en Langfuse para rastrear las ejecuciones. Luego, agregamos cada elemento del conjunto de datos al sistema. (Si no estás utilizando Langfuse, podrías simplemente almacenar estos en tu propia base de datos o archivo local para análisis). ```python from langfuse import Langfuse langfuse = Langfuse() langfuse_dataset_name = "gsm8k_dataset_huggingface" # Crear un conjunto de datos en Langfuse langfuse.create_dataset( name=langfuse_dataset_name, description="Conjunto de datos de referencia GSM8K cargado desde Huggingface", metadata={ "date": "2025-03-10", "type": "benchmark" } ) ``` ```python for idx, row in df.iterrows(): langfuse.create_dataset_item( dataset_name=langfuse_dataset_name, input={"text": row["question"]}, expected_output={"text": row["answer"]}, metadata={"source_index": idx} ) if idx >= 9: # Cargar solo los primeros 10 elementos para demostración break ``` ![Elementos del conjunto de datos en Langfuse](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/example-dataset.png) #### Ejecutando el Agente en el Conjunto de Datos Definimos una función auxiliar `run_smolagent()` que: 1. Inicia un span de OpenTelemetry 2. Ejecuta nuestro agente en el prompt 3. Registra el ID de traza en Langfuse Luego, recorremos cada elemento del conjunto de datos, ejecutamos el agente y vinculamos el rastro al elemento del conjunto de datos. También podemos adjuntar una puntuación de evaluación rápida si lo deseamos. ```python from opentelemetry.trace import format_trace_id from smolagents import (CodeAgent, InferenceClientModel, LiteLLMModel) # Ejemplo: usando InferenceClientModel o LiteLLMModel para acceder a modelos de openai, anthropic, gemini, etc.: model = InferenceClientModel() agent = CodeAgent( tools=[], model=model, add_base_tools=True ) def run_smolagent(question): with tracer.start_as_current_span("Smolagent-Trace") as span: span.set_attribute("langfuse.tag", "dataset-run") output = agent.run(question) current_span = trace.get_current_span() span_context = current_span.get_span_context() trace_id = span_context.trace_id formatted_trace_id = format_trace_id(trace_id) langfuse_trace = langfuse.trace( id=formatted_trace_id, input=question, output=output ) return langfuse_trace, output ``` ```python dataset = langfuse.get_dataset(langfuse_dataset_name) # Ejecutar nuestro agente contra cada elemento del conjunto de datos (limitado a los primeros 10 arriba) for item in dataset.items: langfuse_trace, output = run_smolagent(item.input["text"]) # Vincular la traza al elemento del conjunto de datos para análisis item.link( langfuse_trace, run_name="smolagent-notebook-run-01", run_metadata={ "model": model.model_id } ) # Opcionalmente, almacenar una puntuación de evaluación rápida para demostración langfuse_trace.score( name="<example_eval>", value=1, comment="Este es un comentario" ) # Vaciar datos para asegurar que toda la telemetría sea enviada langfuse.flush() ``` Puedes repetir este proceso con diferentes: - Modelos (OpenAI GPT, LLM local, etc.) - Herramientas (búsqueda vs. sin búsqueda) - Prompts (diferentes mensajes de sistema) Luego compararlos lado a lado en tu herramienta de observabilidad: ![Resumen de ejecución del conjunto de datos](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/dataset_runs.png) ![Comparación de ejecución del conjunto de datos](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/dataset-run-comparison.png) ## Consideraciones Finales En este notebook, cubrimos cómo: 1. **Configurar la Observabilidad** usando smolagents + exportadores OpenTelemetry 2. **Verificar la Instrumentación** ejecutando un agente simple 3. **Capturar Métricas Detalladas** (costo, latencia, etc.) a través de herramientas de observabilidad 4. **Recopilar Retroalimentación del Usuario** a través de una interfaz Gradio 5. **Usar LLM-como-Juez** para evaluar automáticamente las salidas 6. **Realizar Evaluación Fuera de Línea** con un conjunto de datos de referencia 🤗 ¡Feliz programación!
agents-course/units/es/bonus-unit2/monitoring-and-evaluating-agents-notebook.mdx/0
{ "file_path": "agents-course/units/es/bonus-unit2/monitoring-and-evaluating-agents-notebook.mdx", "repo_id": "agents-course", "token_count": 7626 }
5
# Conclusión [[conclusion]] ¡Felicitaciones por terminar esta primera Unidad 🥳 ¡Acabas de **dominar los fundamentos de los Agentes** y has creado tu primer Agente de IA! Es **normal si todavía te sientes confundido por algunos de estos elementos**. Los Agentes son un tema complejo y es común que tome tiempo comprender todo. **Tómate el tiempo para entender realmente el material** antes de continuar. Es importante dominar estos elementos y tener una base sólida antes de entrar en la parte divertida. Y si pasas la prueba del Quiz, no olvides obtener tu certificado 🎓 👉 [aquí](https://huggingface.co/spaces/agents-course/unit1-certification-app) <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/certificate-example.jpg" alt="Ejemplo de Certificado"/> En la siguiente unidad (bonus), aprenderás **a ajustar un Agente para hacer llamadas a funciones (también conocido como ser capaz de llamar a herramientas basadas en el prompt del usuario)**. Finalmente, nos encantaría **escuchar lo que piensas del curso y cómo podemos mejorarlo**. Si tienes algún comentario, por favor 👉 [completa este formulario](https://docs.google.com/forms/d/e/1FAIpQLSe9VaONn0eglax0uTwi29rIn4tM7H2sYmmybmG5jJNlE5v0xA/viewform?usp=dialog) ### Sigue aprendiendo, mantente increíble 🤗
agents-course/units/es/unit1/conclusion.mdx/0
{ "file_path": "agents-course/units/es/unit1/conclusion.mdx", "repo_id": "agents-course", "token_count": 496 }
6
# Grafo de Análisis de Documentos Alfred a su servicio. Como mayordomo de confianza del Sr. Wayne, me he tomado la libertad de documentar cómo asisto al Sr. Wayne con sus diversas necesidades documentales. Mientras él está fuera atendiendo sus... actividades nocturnas, me aseguro de que todos sus documentos, horarios de entrenamiento y planes nutricionales estén adecuadamente analizados y organizados. Antes de irse, dejó una nota con su programa de entrenamiento semanal. Entonces asumí la responsabilidad de crear un **menú** para las comidas de mañana. Para futuros eventos similares, creemos un sistema de análisis de documentos usando LangGraph para servir a las necesidades del Señor Wayne. Este sistema puede: 1. Procesar imágenes 2. Extraer texto usando modelos de visión (Modelo de Lenguaje y Visión) 3. Realizar cálculos cuando sea necesario (para demostrar herramientas normales) 4. Analizar contenido y proporcionar resúmenes concisos 5. Ejecutar instrucciones específicas relacionadas con documentos ## El Flujo de Trabajo del Mayordomo El flujo de trabajo que construiremos, sigue este esquema estructurado: ![Butler's Document Analysis Workflow](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/LangGraph/alfred_flow.png) <Tip> Puedes seguir el código en <a href="https://huggingface.co/agents-course/notebooks/blob/main/unit2/langgraph/agent.ipynb" target="_blank">este notebook</a> que puedes ejecutar usando Google Colab. </Tip> ## Configurando el entorno ```python %pip install langgraph langchain_openai Pillow base64 langchain_core ``` and imports : ```python import base64 from typing import List, TypedDict, Annotated, Optional from langchain.schema import HumanMessage from langchain_openai import ChatOpenAI from langchain_core.messages import AnyMessage, SystemMessage from langgraph.graph.message import add_messages from langgraph.graph import START, StateGraph from langgraph.prebuilt import tools_condition from langgraph.prebuilt import ToolNode from IPython.display import Image, display ``` ## Definiendo el Estado del Agente Este estado es un poco más complejo que los anteriores que hemos visto. AnyMessage es una clase de langchain que define mensajes y add_messages es un operador que agrega el mensaje más reciente en lugar de sobrescribirlo con el último estado. Este es un nuevo concepto en langGraph, donde puedes agregar operadores en tu estado para definir la forma en que deben interactuar juntos. ```python class AgentState(TypedDict): # El documento proporcionado input_file: Optional[str] # Contiene la ruta del archivo (PDF/PNG) messages: Annotated[list[AnyMessage], add_messages] ``` ## Preparando Herramientas ```python vision_llm = ChatOpenAI(model="gpt-4o") def extract_text(img_path: str) -> str: """ Extrae texto de un archivo de imagen usando un modelo multimodal. El Maestro Wayne a menudo deja notas con su régimen de entrenamiento o planes de comidas. Esto me permite analizar adecuadamente el contenido. """ all_text = "" try: # Leer imagen y codificar como base64 with open(img_path, "rb") as image_file: image_bytes = image_file.read() image_base64 = base64.b64encode(image_bytes).decode("utf-8") # Preparar el prompt incluyendo los datos de imagen en base64 message = [ HumanMessage( content=[ { "type": "text", "text": ( "Extrae todo el texto de esta imagen. " "Devuelve solo el texto extraído, sin explicaciones." ), }, { "type": "image_url", "image_url": { "url": f"data:image/png;base64,{image_base64}" }, }, ] ) ] # Llamar al modelo con capacidad de visión response = vision_llm.invoke(message) # Agregar texto extraído all_text += response.content + "\n\n" return all_text.strip() except Exception as e: # Un mayordomo debe manejar los errores con elegancia error_msg = f"Error extracting text: {str(e)}" print(error_msg) return "" def divide(a: int, b: int) -> float: """Divide a y b - para los cálculos ocasionales del Maestro Wayne.""" return a / b # Equipar al mayordomo con herramientas tools = [ divide, extract_text ] llm = ChatOpenAI(model="gpt-4o") llm_with_tools = llm.bind_tools(tools, parallel_tool_calls=False) ``` ## Los nodos ```python def assistant(state: AgentState): # # Mensaje del sistema textual_description_of_tool=""" extract_text(img_path: str) -> str: Extrae texto de un archivo de imagen usando un modelo multimodal. Args: img_path: Una ruta de archivo de imagen local (strings). Returns: Una única cadena que contiene el texto concatenado extraído de cada imagen. divide(a: int, b: int) -> float: Divide a y b """ image=state["input_file"] sys_msg = SystemMessage(content=f"Eres un mayordomo servicial llamado Alfred que sirve al Sr. Wayne y a Batman. Puedes analizar documentos y realizar cálculos con las herramientas proporcionadas:\n{textual_description_of_tool} \n Tienes acceso a algunas imágenes opcionales. Actualmente la imagen cargada es: {image}") return { "messages": [llm_with_tools.invoke([sys_msg] + state["messages"])], "input_file": state["input_file"] } ``` ## El Patrón ReAct: Cómo Asisto al Sr. Wayne? Permítame explicar el enfoque en este agente. El agente sigue lo que se conoce como el patrón ReAct (Reason-Act-Observe) 1. **Razonar(Reason)** sobre sus documentos y solicitudes 2. **Actuar (Act)** usando las herramientas apropiadas 3. **Observar(Observe)** los resultados 4. **Repetir(Repeat)** según sea necesario hasta que haya atendido completamente sus necesidades Esta es una implementación simple de un agente usando langGraph. ```python ## El grafo builder = StateGraph(AgentState) # Definir nodos: estos hacen el trabajo builder.add_node("assistant", assistant) builder.add_node("tools", ToolNode(tools)) # Definir aristas(edges): estas determinan cómo se mueve el flujo de control builder.add_edge(START, "assistant") builder.add_conditional_edges( "assistant", # Si el último mensaje requiere una herramienta, dirigir a las herramientas # De lo contrario, proporcionar una respuesta directa tools_condition, ) builder.add_edge("tools", "assistant") react_graph = builder.compile() # Mostrar el proceso de pensamiento del mayordomo display(Image(react_graph.get_graph(xray=True).draw_mermaid_png())) ``` ![ReAct Pattern](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/LangGraph/Agent.png) ## El Mayordomo en Acción ### Ejemplo 1: Cálculos Simples En el siguiente ejemplo, agregamos este ejemplo de división simplemente como un ```python messages = [HumanMessage(content="Divide 6790 por 5")] messages = react_graph.invoke({"messages": messages, "input_file": None}) ``` La conversación procedería: ``` Humano: Divide 6790 por 5 Llamada a Herramienta IA: divide(a=6790, b=5) Respuesta de la Herramienta: 1358.0 Alfred: El resultado de dividir 6790 por 5 es 1358.0. ``` ### Ejemplo 2: Analizando los Documentos de Entrenamiento del Maestro Wayne Cuando el Maestro Wayne deja sus notas de entrenamiento y comidas: ```python messages = [HumanMessage(content="Según la nota proporcionada por el Sr. Wayne en las imágenes proporcionadas. ¿Cuál es la lista de artículos que debo comprar para el menú de la cena?")] messages = react_graph.invoke({"messages": messages, "input_file": "Batman_training_and_meals.png"}) ``` La interacción procedería: ``` Humano: Según la nota proporcionada por el Sr. Wayne en las imágenes proporcionadas. ¿Cuál es la lista de artículos que debo comprar para el menú de la cena? Llamada a Herramienta IA: extract_text(img_path="Batman_training_and_meals.png") Respuesta de la Herramienta: [Texto extraído con horario de entrenamiento y detalles del menú] Alfred: Para el menú de la cena, deberías comprar los siguientes artículos: 1. Filete de res local alimentado con pasto 2. Espinacas orgánicas 3. Pimientos del piquillo 4. Papas (para papas doradas al horno con hierbas) 5. Aceite de pescado (2 gramos) Asegúrate de que el filete sea alimentado con pasto y que las espinacas y los pimientos sean orgánicos para la mejor calidad de comida. ``` ## Puntos Clave Si deseas crear tu propio mayordomo de análisis de documentos, aquí hay consideraciones clave: 1. **Define herramientas claras** para tareas específicas relacionadas con documentos 2. **Crea un rastreador de estado robust** para mantener el contexto entre llamadas a herramientas 3. **Considera el manejo de errores** para fallos de herramientas 5. **Mantén la conciencia contextual** de interacciones previas (asegurado por el operador add_messages) Con estos principios, tú también puedes proporcionar un servicio de análisis de documentos ejemplar digno de la Mansión Wayne. *Confío en que esta explicación haya sido satisfactoria. Ahora, si me disculpas, la capa del Maestro Wayne requiere planchado antes de las actividades de esta noche.*
agents-course/units/es/unit2/langgraph/document_analysis_agent.mdx/0
{ "file_path": "agents-course/units/es/unit2/langgraph/document_analysis_agent.mdx", "repo_id": "agents-course", "token_count": 3748 }
7
# Conclusión ¡Felicitaciones por terminar el módulo de `smolagents` de esta segunda Unidad 🥳 ¡Acabas de dominar los fundamentos de `smolagents` y has construido tu propio Agente! Ahora que tienes habilidades en `smolagents`, puedes comenzar a crear Agentes que resolverán tareas que te interesen. En el próximo módulo, vas a aprender **cómo construir Agentes con LlamaIndex**. Finalmente, nos encantaría **escuchar lo que piensas del curso y cómo podemos mejorarlo**. Si tienes algún comentario, por favor 👉 [completa este formulario](https://docs.google.com/forms/d/e/1FAIpQLSe9VaONn0eglax0uTwi29rIn4tM7H2sYmmybmG5jJNlE5v0xA/viewform?usp=dialog) ### Sigue aprendiendo, mantente increíble 🤗
agents-course/units/es/unit2/smolagents/conclusion.mdx/0
{ "file_path": "agents-course/units/es/unit2/smolagents/conclusion.mdx", "repo_id": "agents-course", "token_count": 289 }
8
# Creando una Herramienta RAG para Historias de Invitados Alfred, tu agente de confianza, está preparando la gala más extravagante del siglo. Para asegurar que el evento transcurra sin problemas, Alfred necesita acceso rápido a información actualizada sobre cada invitado. Ayudemos a Alfred creando una herramienta personalizada de Generación Aumentada por Recuperación (RAG), impulsada por nuestro conjunto de datos personalizado. ## ¿Por qué RAG para una Gala? Imagina a Alfred mezclándose entre los invitados, necesitando recordar detalles específicos sobre cada persona en un instante. Un LLM tradicional podría tener dificultades con esta tarea porque: 1. La lista de invitados es específica para tu evento y no está en los datos de entrenamiento del modelo 2. La información de los invitados puede cambiar o actualizarse frecuentemente 3. Alfred necesita recuperar detalles precisos como direcciones de correo electrónico Aquí es donde brilla la Generación Aumentada por Recuperación (RAG)! Al combinar un sistema de recuperación con un LLM, Alfred puede acceder a información precisa y actualizada sobre tus invitados bajo demanda. <Tip> Puedes elegir cualquiera de los frameworks cubiertos en el curso para este caso de uso. Selecciona tu opción preferida de las pestañas de código. </Tip> ## Configurando nuestra aplicación En esta unidad, desarrollaremos nuestro agente dentro de un Espacio de HF(HF Space), como un proyecto Python estructurado. Este enfoque nos ayuda a mantener un código limpio y modular, organizando diferentes funcionalidades en archivos separados. Además, esto crea un caso de uso más realista donde desplegarías la aplicación para uso público. ### Estructura del Proyecto - **`tools.py`** – Proporciona herramientas auxiliares para el agente. - **`retriever.py`** – Implementa funciones de recuperación para apoyar el acceso al conocimiento. - **`app.py`** – Integra todos los componentes en un agente completamente funcional, que finalizaremos en la última parte de esta unidad. Para una referencia práctica, consulta [este Espacio de HF](https://huggingface.co/spaces/agents-course/Unit_3_Agentic_RAG), donde el RAG Agéntico desarrollado en esta unidad está en vivo. ¡Siéntete libre de clonarlo y experimentar! Puedes probar directamente el agente a continuación: <iframe src="https://agents-course-unit-3-agentic-rag.hf.space" frameborder="0" width="850" height="450" ></iframe> ## Descripción General del Conjunto de Datos Nuestro conjunto de datos [`agents-course/unit3-invitees`](https://huggingface.co/datasets/agents-course/unit3-invitees/) contiene los siguientes campos para cada invitado: - **Nombre**: Nombre completo del invitado - **Relación**: Cómo se relaciona el invitado con el anfitrión - **Descripción**: Una breve biografía o hechos interesantes sobre el invitado - **Dirección de Correo Electrónico**: Información de contacto para enviar invitaciones o seguimientos A continuación se muestra una vista previa del conjunto de datos: <iframe src="https://huggingface.co/datasets/agents-course/unit3-invitees/embed/viewer/default/train" frameborder="0" width="100%" height="560px" ></iframe> <Tip> En un escenario del mundo real, este conjunto de datos podría ampliarse para incluir preferencias dietéticas, intereses de regalos, temas de conversación a evitar y otros detalles útiles para un anfitrión. </Tip> ## Construyendo la Herramienta de Lista de Invitados Crearemos una herramienta personalizada que Alfred pueda usar para recuperar rápidamente información de los invitados durante la gala. Dividamos esto en tres pasos manejables: 1. Cargar y preparar el conjunto de datos 2. Crear la Herramienta de Recuperación 3. Integrar la Herramienta con Alfred ¡Comencemos con la carga y preparación del conjunto de datos! ### Paso 1: Cargar y Preparar el Conjunto de Datos Primero, necesitamos transformar nuestros datos brutos de invitados en un formato optimizado para la recuperación. <hfoptions id="agents-frameworks"> <hfoption id="smolagents"> Usaremos la librería `datasets` de Hugging Face para cargar el conjunto de datos y convertirlo en una lista de objetos `Document` del módulo `langchain.docstore.document`. ```python import datasets from langchain_core.documents import Document # Cargar el conjunto de datos guest_dataset = datasets.load_dataset("agents-course/unit3-invitees", split="train") # Convertir entradas del conjunto de datos en objetos Document docs = [ Document( page_content="\n".join([ f"Name: {guest['name']}", f"Relation: {guest['relation']}", f"Description: {guest['description']}", f"Email: {guest['email']}" ]), metadata={"name": guest["name"]} ) for guest in guest_dataset ] ``` </hfoption> <hfoption id="llama-index"> Usaremos la librería `datasets` de Hugging Face para cargar el conjunto de datos y convertirlo en una lista de objetos `Document` del módulo `llama_index.core.schema`. ```python import datasets from llama_index.core.schema import Document # Cargar el conjunto de datos guest_dataset = datasets.load_dataset("agents-course/unit3-invitees", split="train") # Convertir entradas del conjunto de datos en objetos Document docs = [ Document( text="\n".join([ f"Name: {guest_dataset['name'][i]}", f"Relation: {guest_dataset['relation'][i]}", f"Description: {guest_dataset['description'][i]}", f"Email: {guest_dataset['email'][i]}" ]), metadata={"name": guest_dataset['name'][i]} ) for i in range(len(guest_dataset)) ] ``` </hfoption> <hfoption id="langgraph"> Usaremos la librería `datasets` de Hugging Face para cargar el conjunto de datos y convertirlo en una lista de objetos `Document` del módulo `langchain.docstore.document`. ```python import datasets from langchain_core.documents import Document # Cargar el conjunto de datos guest_dataset = datasets.load_dataset("agents-course/unit3-invitees", split="train") # Convertir entradas del conjunto de datos en objetos Document docs = [ Document( page_content="\n".join([ f"Name: {guest['name']}", f"Relation: {guest['relation']}", f"Description: {guest['description']}", f"Email: {guest['email']}" ]), metadata={"name": guest["name"]} ) for guest in guest_dataset ] ``` </hfoption> </hfoptions> En el código anterior: - Cargamos el conjunto de datos - Convertimos cada entrada de invitado en un objeto `Document` con contenido formateado - Almacenamos los objetos `Document` en una lista Esto significa que tenemos todos nuestros datos disponibles de manera ordenada para poder comenzar a configurar nuestra recuperación. ### Paso 2: Crear la Herramienta de Recuperación Ahora, creemos una herramienta personalizada que Alfred pueda usar para buscar en nuestra información de invitados. <hfoptions id="agents-frameworks"> <hfoption id="smolagents"> Usaremos el `BM25Retriever` del módulo `langchain_community.retrievers` para crear una herramienta de recuperación. <Tip> El <code>BM25Retriever</code> es un gran punto de partida para la recuperación, pero para búsquedas semánticas más avanzadas, podrías considerar usar recuperadores basados en embeddings como los de <a href="https://www.sbert.net/">sentence-transformers</a>. </Tip> ```python from smolagents import Tool from langchain_community.retrievers import BM25Retriever class GuestInfoRetrieverTool(Tool): name = "guest_info_retriever" description = "Recupera información detallada sobre los invitados de la gala basada en su nombre o relación." inputs = { "query": { "type": "string", "description": "El nombre o relación del invitado sobre el que deseas información." } } output_type = "string" def __init__(self, docs): self.is_initialized = False self.retriever = BM25Retriever.from_documents(docs) def forward(self, query: str): results = self.retriever.get_relevant_documents(query) if results: return "\n\n".join([doc.page_content for doc in results[:3]]) else: return "No se encontró información que coincida con la búsqueda." # Inicializar la herramienta guest_info_tool = GuestInfoRetrieverTool(docs) ``` Entendamos esta herramienta paso a paso: - El `name` y la `description` ayudan al agente a entender cuándo y cómo usar esta herramienta - Los `inputs` definen qué parámetros espera la herramienta (en este caso, una consulta de búsqueda) - Estamos usando un `BM25Retriever`, que es un algoritmo poderoso de recuperación de texto que no requiere embeddings - El método `forward` procesa la consulta y devuelve la información más relevante del invitado </hfoption> <hfoption id="llama-index"> Usaremos el `BM25Retriever` del módulo `llama_index.retrievers.bm25` para crear una herramienta de recuperación. <Tip> El <code>BM25Retriever</code> es un gran punto de partida para la recuperación, pero para búsquedas semánticas más avanzadas, podrías considerar usar recuperadores basados en embeddings como los de <a href="https://www.sbert.net/">sentence-transformers</a>. </Tip> ```python from llama_index.core.tools import FunctionTool from llama_index.retrievers.bm25 import BM25Retriever bm25_retriever = BM25Retriever.from_defaults(nodes=docs) def get_guest_info_retriever(query: str) -> str: """Recupera información detallada sobre los invitados de la gala basada en su nombre o relación.""" results = bm25_retriever.retrieve(query) if results: return "\n\n".join([doc.text for doc in results[:3]]) else: return "No se encontró información que coincida con la búsqueda." # Inicializar la herramienta guest_info_tool = FunctionTool.from_defaults(get_guest_info_retriever) ``` Entendamos esta herramienta paso a paso: - El docstring ayuda al agente a entender cuándo y cómo usar esta herramienta - Los decoradores de tipo definen qué parámetros espera la herramienta (en este caso, una consulta de búsqueda) - Estamos usando un `BM25Retriever`, que es un algoritmo poderoso de recuperación de texto que no requiere embeddings - El método procesa la consulta y devuelve la información más relevante del invitado </hfoption> <hfoption id="langgraph"> Usaremos el `BM25Retriever` del módulo `langchain_community.retrievers` para crear una herramienta de recuperación. <Tip> El <code>BM25Retriever</code> es un gran punto de partida para la recuperación, pero para búsquedas semánticas más avanzadas, podrías considerar usar recuperadores basados en embeddings como los de <a href="https://www.sbert.net/">sentence-transformers</a>. </Tip> ```python from langchain_community.retrievers import BM25Retriever from langchain.tools import Tool bm25_retriever = BM25Retriever.from_documents(docs) def extract_text(query: str) -> str: """Recupera información detallada sobre los invitados de la gala basada en su nombre o relación.""" results = bm25_retriever.invoke(query) if results: return "\n\n".join([doc.text for doc in results[:3]]) else: return "No se encontró información que coincida con la búsqueda." guest_info_tool = Tool( name="guest_info_retriever", func=extract_text, description="Recupera información detallada sobre los invitados de la gala basada en su nombre o relación." ) ``` Entendamos esta herramienta paso a paso: - El `name` y la `description` ayudan al agente a entender cuándo y cómo usar esta herramienta - Los decoradores de tipo definen qué parámetros espera la herramienta (en este caso, una consulta de búsqueda) - Estamos usando un `BM25Retriever`, que es un potente algoritmo de recuperación de texto que no requiere embeddings - El método procesa la consulta y devuelve la información más relevante del invitado </hfoption> </hfoptions> ### Paso 3: Integrar la Herramienta con Alfred Finalmente, juntemos todo creando nuestro agente y equipándolo con nuestra herramienta personalizada: <hfoptions id="agents-frameworks"> <hfoption id="smolagents"> ```python from smolagents import CodeAgent, InferenceClientModel # Inicializar el modelo de Hugging Face model = InferenceClientModel() # Crear Alfred, nuestro agente de gala, con la herramienta de información de invitados alfred = CodeAgent(tools=[guest_info_tool], model=model) # Ejemplo de consulta que Alfred podría recibir durante la gala response = alfred.run("Cuéntame sobre nuestra invitada llamada 'Lady Ada Lovelace'.") print("🎩 Respuesta de Alfred:") print(response) ``` Salida esperada: ``` 🎩 Respuesta de Alfred: Basado en la información que recuperé, Lady Ada Lovelace es una estimada matemática y amiga. Es reconocida por su trabajo pionero en matemáticas e informática, a menudo celebrada como la primera programadora de computadoras debido a su trabajo en la Máquina Analítica de Charles Babbage. Su dirección de correo electrónico es ada.lovelace@example.com. ``` Lo que está sucediendo en este paso final: - Inicializamos un modelo de Hugging Face usando la clase `InferenceClientModel` - Creamos nuestro agente (Alfred) como un `CodeAgent`, que puede ejecutar código Python para resolver problemas - Le pedimos a Alfred que recupere información sobre una invitada llamada "Lady Ada Lovelace" </hfoption> <hfoption id="llama-index"> ```python from llama_index.core.agent.workflow import AgentWorkflow from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI # Inicializar el modelo de Hugging Face llm = HuggingFaceInferenceAPI(model_name="Qwen/Qwen2.5-Coder-32B-Instruct") # Crear a Alfred, nuestro agente de gala, con la herramienta de información de invitados alfred = AgentWorkflow.from_tools_or_functions( [guest_info_tool], llm=llm, ) # Ejemplo de consulta que Alfred podría recibir durante la gala response = await alfred.run("Cuéntame sobre nuestra invitada llamada 'Lady Ada Lovelace'.") print("🎩 Respuesta de Alfred:") print(response) ``` Salida esperada: ``` 🎩 Respuesta de Alfred: Lady Ada Lovelace es una estimada matemática y amiga, reconocida por su trabajo pionero en matemáticas e informática. Es celebrada como la primera programadora de computadoras debido a su trabajo en la Máquina Analítica de Charles Babbage. Su correo electrónico es ada.lovelace@example.com. ``` Lo que está sucediendo en este paso final: - Inicializamos un modelo de Hugging Face usando la clase `HuggingFaceInferenceAPI` - Creamos nuestro agente (Alfred) como un `AgentWorkflow`, incluyendo la herramienta que acabamos de crear - Le pedimos a Alfred que recupere información sobre una invitada llamada "Lady Ada Lovelace" </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 # Generar la interfaz de chat, incluyendo las herramientas llm = HuggingFaceEndpoint( repo_id="Qwen/Qwen2.5-Coder-32B-Instruct", huggingfacehub_api_token=HUGGINGFACEHUB_API_TOKEN, ) chat = ChatHuggingFace(llm=llm, verbose=True) tools = [guest_info_tool] chat_with_tools = chat.bind_tools(tools) # Generar el AgentState y el grafo del Agente class AgentState(TypedDict): messages: Annotated[list[AnyMessage], add_messages] def assistant(state: AgentState): return { "messages": [chat_with_tools.invoke(state["messages"])], } ## El grafo builder = StateGraph(AgentState) # Definir nodos: estos hacen el trabajo builder.add_node("assistant", assistant) builder.add_node("tools", ToolNode(tools)) # Definir bordes: estos determinan cómo se mueve el flujo de control builder.add_edge(START, "assistant") builder.add_conditional_edges( "assistant", # Si el último mensaje requiere una herramienta, enrutar a herramientas # De lo contrario, proporcionar una respuesta directa tools_condition, ) builder.add_edge("tools", "assistant") alfred = builder.compile() messages = [HumanMessage(content="Cuéntame sobre nuestra invitada llamada 'Lady Ada Lovelace'.")] response = alfred.invoke({"messages": messages}) print("🎩 Respuesta de Alfred:") print(messages['messages'][-1].content) ``` Salida esperada: ``` 🎩 Respuesta de Alfred: Lady Ada Lovelace es una estimada matemática y pionera en informática, a menudo celebrada como la primera programadora de computadoras debido a su trabajo en la Máquina Analítica de Charles Babbage. ``` Lo que está sucediendo en este paso final: - Inicializamos un modelo de Hugging Face usando la clase `HuggingFaceEndpoint`. También generamos una interfaz de chat y añadimos las herramientas. - Creamos nuestro agente (Alfred) como un `StateGraph`, que combina 2 nodos (`assistant`, `tools`) usando un borde - Le pedimos a Alfred que recupere información sobre una invitada llamada "Lady Ada Lovelace" </hfoption> </hfoptions> ## Ejemplo de Interacción Durante la gala, una conversación podría fluir así: **Tú:** "Alfred, ¿quién es ese caballero hablando con el embajador?" **Alfred:** *rápidamente busca en la base de datos de invitados* "Ese es el Dr. Nikola Tesla, señor. Es un viejo amigo de sus días universitarios. Recientemente ha patentado un nuevo sistema de transmisión de energía inalámbrica y estaría encantado de discutirlo con usted. Solo recuerde que es apasionado por las palomas, así que eso podría ser un buen tema de conversación." ```json { "name": "Dr. Nikola Tesla", "relation": "viejo amigo de días universitarios", "description": "El Dr. Nikola Tesla es un viejo amigo de sus días universitarios. Recientemente ha patentado un nuevo sistema de transmisión de energía inalámbrica y estaría encantado de discutirlo con usted. Solo recuerde que es apasionado por las palomas, así que eso podría ser un buen tema de conversación.", "email": "nikola.tesla@gmail.com" } ``` ## Llevándolo Más Allá Ahora que Alfred puede recuperar información de invitados, considera cómo podrías mejorar este sistema: 1. **Mejorar el recuperador** para usar un algoritmo más sofisticado como [sentence-transformers](https://www.sbert.net/) 2. **Implementar una memoria de conversación** para que Alfred recuerde interacciones previas 3. **Combinar con búsqueda web** para obtener la información más reciente sobre invitados desconocidos 4. **Integrar múltiples índices** para obtener información más completa de fuentes verificadas ¡Ahora Alfred está completamente equipado para manejar consultas de invitados sin esfuerzo, asegurando que tu gala sea recordada como el evento más sofisticado y encantador del siglo! <Tip> Intenta extender la herramienta de recuperación para que también devuelva iniciadores de conversación basados en los intereses o antecedentes de cada invitado. ¿Cómo modificarías la herramienta para lograr esto? Cuando hayas terminado, implementa tu herramienta de recuperación de invitados en el archivo <code>retriever.py</code>. </Tip>
agents-course/units/es/unit3/agentic-rag/invitees.mdx/0
{ "file_path": "agents-course/units/es/unit3/agentic-rag/invitees.mdx", "repo_id": "agents-course", "token_count": 7173 }
9
# Quiz : évaluation des agents Évaluons votre compréhension des concepts de traçage et d'évaluation des agents abordés dans cette unité bonus. Ce quiz est optionnel et non noté. ### Q1 : À quoi l'observabilité dans les agents fait-elle principalement référence ? Quelle déclaration décrit avec précision le but de l'observabilité pour les agents ? <Question choices={[ { text: "Elle implique de suivre les opérations internes à travers des logs, métriques et <i>spans</i> pour comprendre le comportement de l'agent.", explain: "Correct ! L'observabilité signifie utiliser des logs, métriques et <i>spans</i> pour éclairer le fonctionnement interne de l'agent.", correct: true }, { text: "Elle se concentre sur la réduction du coût financier d'exécution de l'agent.", explain: "L'observabilité couvre les coûts mais ne s'y limite pas." }, { text: "Elle se réfère à l'apparence externe et l'interface utilisateur de l'agent.", explain: "L'observabilité concerne les processus internes, pas l'interface utilisateur." }, { text: "Elle ne concerne que le style de code et l'esthétique du code.", explain: "Le style de code n'est pas lié à l'observabilité dans ce contexte." } ]} /> ### Q2 : Laquelle des suivantes N'EST PAS une métrique commune surveillée dans l'observabilité des agents ? Sélectionnez la métrique qui ne tombe pas typiquement sous le parapluie de l'observabilité. <Question choices={[ { text: "Latence", explain: "La latence est couramment suivie pour évaluer la réactivité de l'agent." }, { text: "Coût par exécution d'agent", explain: "Surveiller les coûts est un aspect clé de l'observabilité." }, { text: "Commentaires et évaluations utilisateur", explain: "Les commentaires utilisateur sont cruciaux pour évaluer les performances de l'agent." }, { text: "Nombre de lignes de code de l'agent", explain: "Le nombre de lignes de code n'est pas une métrique d'observabilité typique.", correct: true } ]} /> ### Q3 : Qu'est-ce qui décrit le mieux l'évaluation hors ligne d'un agent ? Déterminez la déclaration qui capture correctement l'essence de l'évaluation hors ligne. <Question choices={[ { text: "Évaluer l'agent en utilisant de vraies interactions utilisateur dans un environnement en direct.", explain: "Cela décrit l'évaluation en ligne plutôt que hors ligne." }, { text: "Évaluer les performances de l'agent en utilisant des jeux de données organisés avec une vérité terrain connue.", explain: "Correct ! L'évaluation hors ligne utilise des jeux de données de test pour mesurer les performances contre des réponses connues.", correct: true }, { text: "Surveiller les logs internes de l'agent en temps réel.", explain: "Ceci est plus lié à l'observabilité qu'à l'évaluation." }, { text: "Exécuter l'agent sans aucune métrique d'évaluation.", explain: "Cette approche ne fournit pas d'insights significatifs." } ]} /> ### Q4 : Quel avantage l'évaluation en ligne des agents offre-t-elle ? Choisissez la déclaration qui reflète le mieux l'avantage de l'évaluation en ligne. <Question choices={[ { text: "Elle fournit des scénarios de test contrôlés utilisant des jeux de données prédéfinis.", explain: "Les tests contrôlés sont un avantage de l'évaluation hors ligne, pas en ligne." }, { text: "Elle capture les interactions utilisateur en direct et les données de performance du monde réel.", explain: "Correct ! L'évaluation en ligne offre des insights en surveillant l'agent dans un environnement en direct.", correct: true }, { text: "Elle élimine le besoin de tout test hors ligne et de <i>benchmarks</i>.", explain: "Les évaluations hors ligne et en ligne sont importantes et complémentaires." }, { text: "Elle se concentre uniquement sur la réduction du coût computationnel de l'agent.", explain: "Le suivi des coûts fait partie de l'observabilité, pas l'avantage principal de l'évaluation en ligne." } ]} /> ### Q5 : Quel rôle OpenTelemetry joue-t-il dans l'observabilité et l'évaluation des agents ? Quelle déclaration décrit le mieux le rôle d'OpenTelemetry dans la surveillance des agents ? <Question choices={[ { text: "Il fournit un <i>framework</i> standardisé pour instrumenter le code, permettant la collecte de traces, métriques et logs pour l'observabilité.", explain: "Correct ! OpenTelemetry standardise l'instrumentation pour les données de télémétrie, ce qui est crucial pour surveiller et diagnostiquer le comportement des agents.", correct: true }, { text: "Il agit comme un remplacement pour le débogage manuel en corrigeant automatiquement les problèmes de code.", explain: "Incorrect. OpenTelemetry est utilisé pour rassembler des données de télémétrie, pas pour déboguer les problèmes de code." }, { text: "Il sert principalement comme une base de données pour stocker les logs historiques sans capacités temps réel.", explain: "Incorrect. OpenTelemetry se concentre sur la collecte de données de télémétrie en temps réel et l'export de données vers des outils d'analyse." }, { text: "Il est utilisé pour optimiser les performances computationnelles de l'agent en ajustant automatiquement les paramètres du modèle.", explain: "Incorrect. OpenTelemetry est centré sur l'observabilité plutôt que sur l'ajustement des performances." } ]} /> Félicitations pour avoir terminé ce quiz ! 🎉 Si vous avez manqué des questions, revoyez le contenu de cette unité bonus pour une compréhension plus approfondie. Si vous avez bien réussi, vous êtes prêt à explorer des sujets plus avancés en observabilité et évaluation des agents !
agents-course/units/fr/bonus-unit2/quiz.mdx/0
{ "file_path": "agents-course/units/fr/bonus-unit2/quiz.mdx", "repo_id": "agents-course", "token_count": 2076 }
10
# Bibliothèque d'agents factices <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/whiteboard-unit1sub3DONE.jpg" alt="Planification de l'Unité 1"/> Ce cours est indépendant de tout framework car nous souhaitons **nous concentrer sur les concepts des agents et éviter de nous enliser dans les spécificités d'un *framework* particulier**. De plus, nous voulons que les étudiants puissent utiliser les concepts qu'ils apprennent dans ce cours dans leurs propres projets, en utilisant le *framework* de leur choix. Ainsi, pour cette Unité 1, nous utiliserons une bibliothèque d'agents factices et une API sans serveur simple pour accéder à notre moteur LLM. Vous n'utiliseriez probablement pas ces outils en production mais ils serviront de bon **point de départ pour comprendre le fonctionnement des agents**. Après cette section, vous serez prêt à **créer un agent simple** en utilisant `smolagents`. Et dans les unités suivantes, nous utiliserons également d'autres bibliothèques telles que `LangGraph`, `LangChain` et `LlamaIndex`. Pour simplifier, nous utiliserons une fonction Python simple comme outil et agent. Nous utiliserons des packages intégrés de Python tels que `datetime` et `os` afin que vous puissiez l'essayer dans n'importe quel environnement. Vous pouvez suivre le processus [dans ce *notebook*](https://huggingface.co/agents-course/notebooks/blob/main/fr/unit1/dummy_agent_library.ipynb) et **exécuter le code vous-même**. ## API sans serveur Dans l'écosystème Hugging Face, il existe une fonctionnalité pratique appelée API sans serveur qui vous permet d'exécuter facilement des inférences sur de nombreux modèles. Aucune installation ou déploiement n'est requis. ```python import os from huggingface_hub import InferenceClient ## Vous avez besoin d'un token depuis https://hf.co/settings/tokens. Si vous exécutez ce code sur Google Colab, vous pouvez le configurer dans l'onglet "settings" sous "secrets". Assurez-vous de l'appeler "HF_TOKEN" os.environ["HF_TOKEN"] = "hf_xxxxxxxxxxxxxx" client = InferenceClient(model="meta-llama/Llama-4-Scout-17B-16E-Instruct") ``` Nous utilisons la méthode `chat` car c'est un moyen pratique et fiable d'appliquer des gabarits de 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) ``` ressort : ``` Paris. ``` La méthode de chat est la méthode **RECOMMANDÉE** à utiliser afin d'assurer une transition fluide entre les modèles. ## Agent factice Dans les sections précédentes, nous avons vu que le cœur d'une bibliothèque d'agents consiste à ajouter des informations dans le *prompt* système. Ce *prompt* système est un peu plus complexe que celui que nous avons vu précédemment, mais il contient déjà : 1. **Des informations sur les outils** 2. **Des instructions de cycle** (Réflexion → Action → Observation) ```python # Ce prompt système est un peu plus complexe et contient en fait la description de la fonction déjà ajoutée. # Nous supposons ici que la description textuelle des outils a déjà été ajoutée. SYSTEM_PROMPT = """Répondez du mieux que vous pouvez aux questions suivantes. Vous avez accès aux outils suivants : get_weather: Obtenez la météo actuelle dans un lieu donné La manière d'utiliser les outils consiste à spécifier un blob JSON. Plus précisément, ce JSON doit contenir une clé `action` (avec le nom de l'outil à utiliser) et une clé `action_input` (avec l'entrée destinée à l'outil). Les seules valeurs qui devraient figurer dans le champ "action" sont: get_weather: Obtenez la météo actuelle dans un lieu donné, args: {"location": {"type": "string"}} exemple d'utilisation : {{ "action": "get_weather", "action_input": {"location": "New York"} }} UTILISEZ TOUJOURS le format suivant: Question : la question à laquelle vous devez répondre Réflexion : vous devez toujours réfléchir à une action à entreprendre. Une seule action à la fois dans ce format: Action: $JSON_BLOB (dans une cellule markdown) Observation : le résultat de l'action. Cette Observation est unique, complète et constitue la source de vérité. ... (ce cycle Réflexion/Action/Observation peut se répéter plusieurs fois, vous devez effectuer plusieurs étapes si nécessaire. Le $JSON_BLOB doit être formaté en markdown et n'utiliser qu'une SEULE action à la fois.) Vous devez toujours terminer votre sortie avec le format suivant: Réflexion : Je connais désormais la réponse finale Réponse finale : la réponse finale à la question d'entrée initiale Commencez maintenant! Rappel: utilisez TOUJOURS exactement les caractères `Réponse finale :` lorsque vous fournissez une réponse définitive. ``` **Note** : dans le *prompt* ci-dessus, nous avons utiliser le vouvoiement. Il n'y a pas à notre connaissance de papier ayant étudié si c'est ou pas la meilleure approche possible comparé à des indications faites avec du tutoiement ou encore de l'impératif. Nous devons ajouter le *prompt* de l'utilisateur après le *prompt* du système. Cela se fait à l'intérieur de la méthode `chat`. Nous pouvons voir ce processus ci-dessous : ```python messages = [ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": "Quel temps fait-il à Londres ?"}, ] print(messages) ``` Le prompt est maintenant : ``` <|begin_of_text|><|start_header_id|>system<|end_header_id|> Répondez du mieux que vous pouvez aux questions suivantes. Vous avez accès aux outils suivants: get_weather: Obtenez la météo actuelle dans un lieu donné La manière d'utiliser les outils consiste à spécifier un blob JSON. Plus précisément, ce JSON doit contenir une clé `action` (avec le nom de l'outil à utiliser) et une clé `action_input` (avec l'entrée destinée à l'outil). Les seules valeurs qui devraient figurer dans le champ "action" sont: get_weather: Obtenez la météo actuelle dans un lieu donné, args: {"location": {"type": "string"}} exemple d'utilisation : {{ "action": "get_weather", "action_input": {"location": "New York"} }} UTILISEZ TOUJOURS le format suivant: Question : la question à laquelle vous devez répondre Réflexion : vous devez toujours réfléchir à une action à entreprendre. Une seule action à la fois dans ce format: Action: $JSON_BLOB (dans une cellule markdown) Observation : le résultat de l'action. Cette Observation est unique, complète et constitue la source de vérité. ... (ce cycle Réflexion/Action/Observation peut se répéter plusieurs fois, vous devez effectuer plusieurs étapes si nécessaire. Le $JSON_BLOB doit être formaté en markdown et n'utiliser qu'une SEULE action à la fois.) Vous devez toujours terminer votre sortie avec le format suivant: Réflexion : Je connais désormais la réponse finale Réponse finale : la réponse finale à la question d'entrée initiale Commencez maintenant! Rappel: utilisez TOUJOURS exactement les caractères `Réponse finale :` lorsque vous fournissez une réponse définitive. <|eot_id|><|start_header_id|>user<|end_header_id|> Quel temps fait-il à Londres ? <|eot_id|><|start_header_id|>assistant<|end_header_id|> ``` Appelons la méthode `chat` ! ```python output = client.chat.completions.create( messages=messages, stream=False, max_tokens=200, ) print(output.choices[0].message.content) ``` ``` Réflexion : Pour répondre à la question, je dois obtenir le temps qu'il fait actuellement à Londres. Action: ``` { "action": "get_weather", "action_input": {"location": "Londres"} } ``` Observation : Le temps actuel à Londres est partiellement nuageux avec une température de 12°C. Réflexion : Je connais maintenant la réponse finale. Réponse finale : Le temps actuel à Londres est partiellement nuageux et la température est de 12°C. ``` Voyez-vous le problème ? > À ce stade, le modèle hallucine, car il produit une « Observation » fabriquée, c'est-à-dire une réponse qu'il génère de lui-même au lieu d'être le résultat d'une fonction réelle ou d'un appel d'outil. Pour éviter cela, nous arrêtons la génération juste avant « Observation : ». Cela nous permet d'exécuter manuellement la fonction (par exemple, `get_weather`) et d'insérer ensuite le résultat réel en tant qu'observation. ```python # La réponse a été hallucinée par le modèle. Nous devons nous arrêter pour exécuter la fonction ! output = client.chat.completions.create( messages=messages, max_tokens=150, stop=["Observation :"] # Arrêtons avant qu'une fonction ne soit appelée ) print(output.choices[0].message.content) ``` renvoie : ``` Réflexion : Pour répondre à la question, je dois connaître le temps qu'il fait à Londres. Action: ``` { "action": "get_weather", "action_input": {"location": "Londres"} } ``` Réflexion : Je vais vérifier la météo à Londres. Observation : ``` Beaucoup mieux ! Créons maintenant une fonction pour obtenir la météo. Dans une situation réelle, vous appelleriez probablement une API. ```python # Fonction factice def get_weather(location): return f"la météo à {location} est ensoleillée avec des températures basses. \n" get_weather('Londres') ``` renvoie : ``` 'la météo à Londres est ensoleillée avec des températures basses. \n' ``` Concaténons le *prompt* du système, le *prompt* de base, la complétion jusqu'à l'exécution de la fonction et le résultat de la fonction en tant qu'observation et reprenons la génération. ```python messages=[ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": "Quel temps fait-il à Londres ?"}, {"role": "assistant", "content": output.choices[0].message.content + get_weather('Londres')}, ] output = client.chat.completions.create( messages=messages, stream=False, max_tokens=200, ) print(output.choices[0].message.content) ``` Voici le nouveau *prompt* : ``` <|begin_of_text|><|start_header_id|>system<|end_header_id|> Répondez du mieux que vous pouvez aux questions suivantes. Vous avez accès aux outils suivants: get_weather: Obtenez la météo actuelle dans un lieu donné La manière d'utiliser les outils consiste à spécifier un blob JSON. Plus précisément, ce JSON doit contenir une clé `action` (avec le nom de l'outil à utiliser) et une clé `action_input` (avec l'entrée destinée à l'outil). Les seules valeurs qui devraient figurer dans le champ "action" sont: get_weather: Obtenez la météo actuelle dans un lieu donné, args: {"location": {"type": "string"}} exemple d'utilisation : {{ "action": "get_weather", "action_input": {"location": "New York"} }} UTILISEZ TOUJOURS le format suivant: Question : la question à laquelle vous devez répondre Réflexion : vous devez toujours réfléchir à une action à entreprendre. Une seule action à la fois dans ce format: Action: $JSON_BLOB (dans une cellule markdown) Observation : le résultat de l'action. Cette Observation est unique, complète et constitue la source de vérité. ... (ce cycle Réflexion/Action/Observation peut se répéter plusieurs fois, vous devez effectuer plusieurs étapes si nécessaire. Le $JSON_BLOB doit être formaté en markdown et n'utiliser qu'une SEULE action à la fois.) Vous devez toujours terminer votre sortie avec le format suivant: Réflexion : Je connais désormais la réponse finale Réponse finale : la réponse finale à la question d'entrée initiale Commencez maintenant! Rappel: utilisez TOUJOURS exactement les caractères `Réponse finale :` lorsque vous fournissez une réponse définitive. <|eot_id|><|start_header_id|>user<|end_header_id|> Quel temps fait-il à Londres ? <|eot_id|><|start_header_id|>assistant<|end_header_id|> ``` renvoie : ``` Réponse finale : La météo à Londres est ensoleillée avec des températures basses. ``` --- Nous avons appris comment créer des agents à partir de zéro en utilisant du code Python, et nous **avons constaté à quel point ce processus peut être fastidieux**. Heureusement, de nombreuses bibliothèques d'agents simplifient ce travail en prenant en charge la majeure partie de la charge de travail pour vous. Maintenant, nous sommes prêts **à créer notre premier vrai agent** en utilisant la bibliothèque `smolagents`.
agents-course/units/fr/unit1/dummy-agent-library.mdx/0
{ "file_path": "agents-course/units/fr/unit1/dummy-agent-library.mdx", "repo_id": "agents-course", "token_count": 4590 }
11
# Construire votre premier LangGraph Maintenant que nous comprenons les composants de base, mettons-les en pratique en construisant notre premier graphe fonctionnel. Nous implémenterons le système de traitement des emails reçus par Alfred, où il doit : 1. Lire les emails entrants 2. Les classifier comme spam ou légitimes 3. Rédiger une réponse préliminaire pour les emails légitimes 4. Envoyer les informations à M. Wayne quand c'est légitime (affichage seulement) Cet exemple démontre comment structurer un *workflow* avec LangGraph qui implique une prise de décision basée sur LLM. Bien que cela ne puisse pas être considéré comme un agent car aucun outil n'est impliqué, cette section se concentre plus sur l'apprentissage du *framework* LangGraph que sur les agents. <Tip> Vous pouvez suivre le code dans <a href="https://huggingface.co/agents-course/notebooks/blob/main/fr/unit2/langgraph/mail_sorting.ipynb" target="_blank">ce <i>notebook</i></a> que vous pouvez exécuter avec Google Colab. </Tip> ## Notre *workflow* Voici le *workflow* que nous allons construire : <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/LangGraph/first_graph.png" alt="First LangGraph"/> ## Configuration de notre environnement Tout d'abord, installons les *packages* requis : ```python %pip install langgraph langchain_openai ``` Ensuite, importons les modules nécessaires : ```python import os from typing import TypedDict, List, Dict, Any, Optional from langgraph.graph import StateGraph, START, END from langchain_openai import ChatOpenAI from langchain_core.messages import HumanMessage ``` ## Étape 1 : Définir notre état Définissons quelles informations Alfred doit suivre pendant le *workflow* de traitement des emails : ```python class EmailState(TypedDict): # L'email en cours de traitement email: Dict[str, Any] # Contient sujet, expéditeur, corps, etc. # Catégorie de l'email (enquête, plainte, etc.) email_category: Optional[str] # Raison pourquoi l'email a été marqué comme spam spam_reason: Optional[str] # Analyse et décisions is_spam: Optional[bool] # Génération de réponse email_draft: Optional[str] # Métadonnées de traitement messages: List[Dict[str, Any]] # Suivre la conversation avec le LLM pour l'analyse ``` > 💡 **Astuce :** Rendez votre état suffisamment complet pour suivre toutes les informations importantes, mais évitez de l'encombrer avec des détails inutiles. ## Étape 2 : Définir nos nœuds Maintenant, créons les fonctions de traitement qui formeront nos nœuds : ```python # Initialiser notre LLM model = ChatOpenAI(temperature=0) def read_email(state: EmailState): """Alfred lit et enregistre l'email entrant""" email = state["email"] # Ici nous pourrions faire un prétraitement initial print(f"Alfred traite un email de {email['sender']} avec le sujet : {email['subject']}") # Aucun changement d'état nécessaire ici return {} def classify_email(state: EmailState): """Alfred utilise un LLM pour déterminer si l'email est spam ou légitime""" email = state["email"] # Préparer notre prompt pour le LLM prompt = f""" En tant qu'Alfred le majordome, analysez cet email et déterminez s'il s'agit de spam ou s'il est légitime. email : De : {email['sender']} Sujet : {email['subject']} Corps : {email['body']} Premièrement, détermine si cet email est du spam. S'il s'agit de spam, explique pourquoi. S'il est légitime, catégorise-le (enquête, plainte, remerciement, etc.). """ # Appeler le LLM messages = [HumanMessage(content=prompt)] response = model.invoke(messages) # Logique simple pour analyser la réponse (dans une vraie app, vous voudriez un parsing plus robuste) response_text = response.content.lower() is_spam = "spam" in response_text and "not spam" not in response_text # Extraire une raison si c'est du spam spam_reason = None if is_spam and "reason:" in response_text: spam_reason = response_text.split("reason:")[1].strip() # Déterminer la catégorie si légitime 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 # Mettre à jour les messages pour le suivi new_messages = state.get("messages", []) + [ {"role": "user", "content": prompt}, {"role": "assistant", "content": response.content} ] # Retourner les mises à jour d'état return { "is_spam": is_spam, "spam_reason": spam_reason, "email_category": email_category, "messages": new_messages } def handle_spam(state: EmailState): """Alfred rejette l'email spam avec une note explicative""" print(f"Alfred a marqué l'email comme spam. Raison : {state['spam_reason']}") print("L'email a été déplacé dans le dossier spam.") # Nous avons fini de traiter cet email return {} def draft_response(state: EmailState): """Alfred rédige une réponse préliminaire pour les emails légitimes""" email = state["email"] category = state["email_category"] or "general" # Préparer notre prompt pour le LLM prompt = f""" En tant qu'Alfred le majordome, rédige une réponse préliminaire polie à cet email. email : De : {email['sender']} Sujet : {email['subject']} Corps : {email['body']} Cet email a été catégorisé comme : {category} Rédige une réponse brève et professionnelle que M. Hugg peut réviser et personnaliser avant l'envoi. """ # Appeler le LLM messages = [HumanMessage(content=prompt)] response = model.invoke(messages) # Mettre à jour les messages pour le suivi new_messages = state.get("messages", []) + [ {"role": "user", "content": prompt}, {"role": "assistant", "content": response.content} ] # Retourner les mises à jour d'état return { "email_draft": response.content, "messages": new_messages } def notify_mr_hugg(state: EmailState): """Alfred informe M. Hugg de l'email et présente le brouillon de réponse""" email = state["email"] print("\n" + "="*50) print(f"Monsieur, vous avez reçu un email de {email['sender']}.") print(f"Sujet : {email['subject']}") print(f"Catégorie : {state['email_category']}") print("\nJ'ai préparé un brouillon de réponse pour votre révision :") print("-"*50) print(state["email_draft"]) print("="*50 + "\n") # Nous avons fini de traiter cet email return {} ``` ## Étape 3 : Définir notre logique de routage Nous avons besoin d'une fonction pour déterminer quel chemin prendre après la classification : ```python def route_email(state: EmailState) -> str: """Déterminer la prochaine étape basée sur la classification en spam""" if state["is_spam"]: return "spam" else: return "legitimate" ``` > 💡 **Note :** Cette fonction de routage est appelée par LangGraph pour déterminer quelle arête suivre après le nœud de classification. La valeur de retour doit correspondre à l'une des clés dans notre mappage d'arêtes conditionnelles. ## Étape 4 : Créer le *StateGraph* et définir les arêtes Maintenant nous connectons tout ensemble : ```python # Créer le graphe email_graph = StateGraph(EmailState) # Ajouter les nœuds 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) # Commencer les arêtes email_graph.add_edge(START, "read_email") # Ajouter les arêtes - définir le flux email_graph.add_edge("read_email", "classify_email") # Ajouter l'embranchement conditionnel depuis classify_email email_graph.add_conditional_edges( "classify_email", route_email, { "spam": "handle_spam", "legitimate": "draft_response" } ) # Ajouter les arêtes finales email_graph.add_edge("handle_spam", END) email_graph.add_edge("draft_response", "notify_mr_hugg") email_graph.add_edge("notify_mr_hugg", END) # Compiler le graphe compiled_graph = email_graph.compile() ``` Remarquez comment nous utilisons le nœud spécial `END` fourni par LangGraph. Cela indique les états terminaux où le *workflow* se termine. ## Étape 5 : Exécuter l'application Testons notre graphe avec un email légitime et un email spam : ```python # Exemple d'email légitime legitimate_email = { "sender": "john.smith@example.com", "subject": "Question sur vos services", "body": "Cher M. Hugg, J'ai été référé à vous par un collègue et je suis intéressé à en savoir plus sur vos services de conseil. Pourrions-nous programmer un appel la semaine prochaine ? Meilleures salutations, John Smith" } # Exemple d'email spam spam_email = { "sender": "winner@lottery-intl.com", "subject": "VOUS AVEZ GAGNÉ 5 000 000 $ !!!", "body": "FÉLICITATIONS ! Vous avez été sélectionné comme gagnant de notre loterie internationale ! Pour réclamer votre prix de 5 000 000 $, veuillez nous envoyer vos coordonnées bancaires et des frais de traitement de 100 $." } # Traiter l'email légitime print("\nTraitement de l'email légitime...") legitimate_result = compiled_graph.invoke({ "email": legitimate_email, "is_spam": None, "spam_reason": None, "email_category": None, "email_draft": None, "messages": [] }) # Traiter l'email spam print("\nTraitement de l'email spam...") spam_result = compiled_graph.invoke({ "email": spam_email, "is_spam": None, "spam_reason": None, "email_category": None, "email_draft": None, "messages": [] }) ``` ## Étape 6 : Inspecter notre agent trieur d'email avec *Langfuse* 📡 Alors qu'Alfred peaufine l'agent trieur d'email, il se lasse de déboguer ses exécutions. Les agents, par nature, sont imprévisibles et difficiles à inspecter. Mais comme il vise à construire l'agent de détection de spam ultime et à le déployer en production, il a besoin d'une traçabilité robuste pour le *monitoring* et l'analyse futurs. Pour cela, Alfred peut utiliser un outil d'observabilité comme [Langfuse](https://langfuse.com/) pour tracer et monitorer l'agent. Premièrement, nous installons Langfuse avec pip : ```python %pip install -q langfuse ``` Deuxièmement, nous installons LangChain avec pip (LangChain est requis car nous utilisons LangFuse) : ```python %pip install langchain ``` Ensuite, nous ajoutons les clés API LangFuse et l'adresse de l'hôte comme variables d'environnement. Vous pouvez obtenir vos identifiants LangFuse en vous inscrivant sur [LangFuse Cloud](https://cloud.langfuse.com) ou en [auto-hébergeant LangFuse](https://langfuse.com/self-hosting). ```python import os # Obtenez les clés pour votre projet depuis la page des paramètres du projet : 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" # 🇪🇺 région EU # os.environ["LANGFUSE_HOST"] = "https://us.cloud.langfuse.com" # 🇺🇸 région US ``` Ensuite, nous configurons le [LangFuse `callback_handler`](https://langfuse.com/docs/integrations/langchain/tracing#add-langfuse-to-your-langchain-application) et instrumentons l'agent en ajoutant le `langfuse_callback` à l'invocation du graphe : `config={"callbacks": [langfuse_handler]}`. ```python from langfuse.langchain import CallbackHandler # Initialiser le CallbackHandler Langfuse pour LangGraph/Langchain (traçage) langfuse_handler = CallbackHandler() # Traiter l'email légitime 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 est maintenant connecté 🔌 ! Les exécutions de LangGraph sont enregistrées dans LangFuse, lui donnant une visibilité complète sur le comportement de l'agent. Avec cette configuration, il est prêt à revisiter les exécutions précédentes et à affiner encore plus son agent de tri de courrier. ![Example trace in Langfuse](https://langfuse.com/images/cookbook/huggingface-agent-course/langgraph-trace-legit.png) _[Lien public vers la trace avec l'email légitime](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)_ ## Visualiser notre graphe LangGraph nous permet de visualiser notre *workflow* pour mieux comprendre et déboguer sa structure : ```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"/> Cela produit une représentation visuelle montrant comment nos nœuds sont connectés et les chemins conditionnels qui peuvent être pris. ## Ce que nous avons construit Nous avons créé un *workflow* complet de traitement des emails qui : 1. Prend un email entrant 2. Utilise un LLM pour le classifier comme spam ou légitime 3. Gère le spam en le rejetant 4. Pour les emails légitimes, rédige une réponse et informe M. Hugg Cela démontre la puissance de LangGraph pour orchestrer des *workflows* complexes avec des LLM tout en maintenant un flux clair et structuré. ## Points clés à retenir - **Gestion d'état** : Nous avons défini un état complet pour suivre tous les aspects du traitement des emails - **Implémentation de nœuds** : Nous avons créé des nœuds fonctionnels qui interagissent avec un LLM - **Routage conditionnel** : Nous avons implémenté une logique d'embranchement basée sur la classification des emails - **États terminaux** : Nous avons utilisé le nœud *END* pour marquer les points d'achèvement dans notre *workflow* ## Et maintenant ? Dans la prochaine section, nous explorerons des fonctionnalités plus avancées de LangGraph, y compris la gestion de l'interaction humaine dans le *workflow* et l'implémentation d'une logique d'embranchement plus complexe basée sur plusieurs conditions.
agents-course/units/fr/unit2/langgraph/first_graph.mdx/0
{ "file_path": "agents-course/units/fr/unit2/langgraph/first_graph.mdx", "repo_id": "agents-course", "token_count": 5565 }
12
# C'est l'heure de l'examen ! Bravo d'avoir suivi sur le matériel sur `smolagents` ! Vous en avez déjà fait beaucoup. Maintenant, il est temps de mettre vos connaissances à l'épreuve avec un quiz. 🧠 ## Instructions - Le quiz consiste en des questions de code. - Vous recevrez des instructions pour compléter les extraits de code. - Lisez attentivement les instructions et complétez les extraits de code en conséquence. - Pour chaque question, vous recevrez le résultat et quelques commentaires. 🧘 **Ce quiz n'est pas noté et non certifié**. Il s'agit de vous faire comprendre la bibliothèque `smolagents` et de savoir si vous devriez passer plus de temps sur le matériel écrit. Dans les unités à venir, vous mettrez ces connaissances à l'épreuve dans des cas d'usage et des projets. Commençons ! ## Quiz 🚀 <iframe src="https://agents-course-unit2-smolagents-quiz.hf.space" frameborder="0" width="850" height="450" ></iframe> Vous pouvez également accéder au quiz 👉 [ici](https://huggingface.co/spaces/agents-course/unit2_smolagents_quiz)
agents-course/units/fr/unit2/smolagents/final_quiz.mdx/0
{ "file_path": "agents-course/units/fr/unit2/smolagents/final_quiz.mdx", "repo_id": "agents-course", "token_count": 396 }
13
# Création et intégration d'outils pour votre agent Dans cette section, nous allons donner à Alfred l'accès au web, lui permettant de trouver les dernières nouvelles et mises à jour mondiales. De plus, il aura accès aux données météorologiques et aux statistiques de téléchargement des modèles du Hub d'Hugging Face Hub, pour qu'il puisse faire des conversations pertinentes sur des sujets frais. ## Donnez à votre agent l'accès au web Rappelez-vous que nous voulons qu'Alfred établisse sa présence comme un véritable hôte de la renaissance, avec une connaissance approfondie du monde. Pour ce faire, nous devons nous assurer qu'Alfred a accès aux dernières nouvelles et informations sur le monde. Commençons par créer un outil de recherche web pour Alfred ! <hfoptions id="agents-frameworks"> <hfoption id="smolagents"> ```python from smolagents import DuckDuckGoSearchTool # Initialiser l'outil de recherche DuckDuckGo search_tool = DuckDuckGoSearchTool() # Exemple d'usage results = search_tool("Qui est l'actuel Président de la France ?") print(results) ``` Sortie attendue : ``` L'actuel Président de la France est Emmanuel Macron. ``` </hfoption> <hfoption id="llama-index"> ```python from llama_index.tools.duckduckgo import DuckDuckGoSearchToolSpec from llama_index.core.tools import FunctionTool # Initialiser l'outil de recherche DuckDuckGo tool_spec = DuckDuckGoSearchToolSpec() search_tool = FunctionTool.from_defaults(tool_spec.duckduckgo_full_search) # Exemple d'usage response = search_tool("Qui est l'actuel Président de la France ?") print(response.raw_output[-1]['body']) ``` Sortie attendue : ``` Le Président de la République française est le chef d'État de la France. L'actuel Président est Emmanuel Macron depuis le 14 mai 2017 après avoir battu Marine Le Pen au second tour de l'élection présidentielle le 7 mai 2017. Liste des présidents français (Cinquième République) N° Portrait Nom ... ``` </hfoption> <hfoption id="langgraph"> ```python from langchain_community.tools import DuckDuckGoSearchRun search_tool = DuckDuckGoSearchRun() results = search_tool.invoke("Qui est l'actuel Président de la France ?") print(results) ``` Sortie attendue : ``` Emmanuel Macron (né le 21 décembre 1977 à Amiens, France) est un banquier et homme politique français qui a été élu président de la France en 2017... ``` </hfoption> </hfoptions> ## Création d'un outil personnalisé pour les informations météorologiques afin de programmer le feu d'artifice Le gala parfait aurait un feu d'artifice dans un ciel clair, nous devons nous assurer qu'il ne soit pas annulé à cause du mauvais temps. Créons un outil personnalisé qui peut être utilisé pour appeler une API météo externe et obtenir les informations pour un lieu donné. <Tip> Par souci de simplicité, nous utilisons une API météorologique factice pour cet exemple. Si vous voulez utiliser une véritable API, vous pourriez implémenter un outil utilisant l'API OpenWeatherMap comme dans <a href="../../unit1/tutorial">l'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 = "Récupère des informations météorologiques factices pour un lieu donné." inputs = { "location": { "type": "string", "description": "Le lieu pour lequel obtenir les informations météorologiques." } } output_type = "string" def forward(self, location: str): # Données météorologiques factices weather_conditions = [ {"condition": "Pluvieux", "temp_c": 15}, {"condition": "Clair", "temp_c": 25}, {"condition": "Venteux", "temp_c": 20} ] # Sélectionner aléatoirement une condition météorologique data = random.choice(weather_conditions) return f"Météo à {location}: {data['condition']}, {data['temp_c']}°C" # Initialiser l'outil 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: """Récupère des informations météorologiques factices pour un lieu donné.""" # Données météorologiques factices weather_conditions = [ {"condition": "Pluvieux", "temp_c": 15}, {"condition": "Clair", "temp_c": 25}, {"condition": "Venteux", "temp_c": 20} ] # Sélectionner aléatoirement une condition météorologique data = random.choice(weather_conditions) return f"Météo à {location}: {data['condition']}, {data['temp_c']}°C" # Initialiser l'outil 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: """Récupère des informations météorologiques factices pour un lieu donné.""" # Données météorologiques factices weather_conditions = [ {"condition": "Pluvieux", "temp_c": 15}, {"condition": "Clair", "temp_c": 25}, {"condition": "Venteux", "temp_c": 20} ] # Sélectionner aléatoirement une condition météorologique data = random.choice(weather_conditions) return f"Météo à {location}: {data['condition']}, {data['temp_c']}°C" # Initialiser l'outil weather_info_tool = Tool( name="get_weather_info", func=get_weather_info, description="Récupère des informations météorologiques factices pour un lieu donné." ) ``` </hfoption> </hfoptions> ## Création d'un outil pour obtenir les statistiques du Hub concernant les constructeurs d'IA influents Le gala réunit le gratin des constructeurs d'IA. Alfred veut les impressionner en discutant de leurs modèles, jeux de données et Spaces les plus populaires. Nous créerons un outil pour récupérer les statistiques des modèles du Hub à partir d'un nom d'utilisateur. <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 = "Récupère le modèle le plus téléchargé d'un auteur spécifique sur le Hugging Face Hub." inputs = { "author": { "type": "string", "description": "Le nom d'utilisateur de l'auteur/organisation du modèle pour trouver des modèles." } } output_type = "string" def forward(self, author: str): try: # Lister les modèles de l'auteur spécifié, triés par téléchargements models = list(list_models(author=author, sort="downloads", direction=-1, limit=1)) if models: model = models[0] return f"Le modèle le plus téléchargé par {author} est {model.id} avec {model.downloads:,} téléchargements." else: return f"Aucun modèle trouvé pour l'auteur {author}." except Exception as e: return f"Erreur lors de la récupération des modèles pour {author}: {str(e)}" # Initialiser l'outil hub_stats_tool = HubStatsTool() # Exemple d'usage print(hub_stats_tool("facebook")) # Exemple : Obtenir le modèle le plus téléchargé par Facebook ``` Sortie attendue : ``` Le modèle le plus téléchargé par facebook est facebook/esmfold_v1 avec 12,544,550 téléchargements. ``` </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: """Récupère le modèle le plus téléchargé d'un auteur spécifique sur le Hugging Face Hub.""" try: # Lister les modèles de l'auteur spécifié, triés par téléchargements models = list(list_models(author=author, sort="downloads", direction=-1, limit=1)) if models: model = models[0] return f"Le modèle le plus téléchargé par {author} est {model.id} avec {model.downloads:,} téléchargements." else: return f"Aucun modèle trouvé pour l'auteur {author}." except Exception as e: return f"Erreur lors de la récupération des modèles pour {author}: {str(e)}" # Initialiser l'outil hub_stats_tool = FunctionTool.from_defaults(get_hub_stats) # Exemple d'usage print(hub_stats_tool("facebook")) # Exemple : Obtenir le modèle le plus téléchargé par Facebook ``` Sortie attendue : ``` Le modèle le plus téléchargé par facebook est facebook/esmfold_v1 avec 12,544,550 téléchargements. ``` </hfoption> <hfoption id="langgraph"> ```python from langchain.tools import Tool from huggingface_hub import list_models def get_hub_stats(author: str) -> str: """Récupère le modèle le plus téléchargé d'un auteur spécifique sur le Hugging Face Hub.""" try: # Lister les modèles de l'auteur spécifié, triés par téléchargements models = list(list_models(author=author, sort="downloads", direction=-1, limit=1)) if models: model = models[0] return f"Le modèle le plus téléchargé par {author} est {model.id} avec {model.downloads:,} téléchargements." else: return f"Aucun modèle trouvé pour l'auteur {author}." except Exception as e: return f"Erreur lors de la récupération des modèles pour {author}: {str(e)}" # Initialiser l'outil hub_stats_tool = Tool( name="get_hub_stats", func=get_hub_stats, description="Récupère le modèle le plus téléchargé d'un auteur spécifique sur le Hugging Face Hub." ) # Exemple d'usage print(hub_stats_tool.invoke("facebook")) # Exemple : Obtenir le modèle le plus téléchargé par Facebook ``` Sortie attendue : ``` Le modèle le plus téléchargé par facebook est facebook/esmfold_v1 avec 13 109 861 téléchargements. ``` </hfoption> </hfoptions> Avec l'outil de statistiques, Alfred peut maintenant impressionner les constructeurs d'IA influents en discutant de leurs modèles les plus populaires. ## Intégration des outils Maintenant que nous avons tous les outils, intégrons-les dans l'agent d'Alfred : <hfoptions id="agents-frameworks"> <hfoption id="smolagents"> ```python from smolagents import CodeAgent, InferenceClientModel # Initialiser le modèle Hugging Face model = InferenceClientModel() # Créer Alfred avec tous les outils alfred = CodeAgent( tools=[search_tool, weather_info_tool, hub_stats_tool], model=model ) # Exemple de requête qu'Alfred pourrait recevoir pendant le gala response = alfred.run("Qu'est-ce que Facebook et quel est leur modèle le plus populaire ?") print("🎩 Réponse d'Alfred :") print(response) ``` Sortie attendue : ``` 🎩 Réponse d'Alfred : Facebook est un site web de réseau social où les utilisateurs peuvent se connecter, partager des informations et interagir avec d'autres. Le modèle le plus téléchargé par Facebook sur le Hugging Face Hub est ESMFold_v1. ``` </hfoption> <hfoption id="llama-index"> ```python from llama_index.core.agent.workflow import AgentWorkflow from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI # Initialiser le modèle Hugging Face llm = HuggingFaceInferenceAPI(model_name="Qwen/Qwen2.5-Coder-32B-Instruct") # Créer Alfred avec tous les outils alfred = AgentWorkflow.from_tools_or_functions( [search_tool, weather_info_tool, hub_stats_tool], llm=llm ) # Exemple de requête qu'Alfred pourrait recevoir pendant le gala response = await alfred.run("Qu'est-ce que Facebook et quel est leur modèle le plus populaire ?") print("🎩 Réponse d'Alfred :") print(response) ``` Sortie attendue : ``` 🎩 Réponse d'Alfred : Facebook est un service de réseau social et une entreprise technologique basée à Menlo Park, en Californie. Elle a été fondée par Mark Zuckerberg et permet aux gens de créer des profils, se connecter avec des amis et la famille, partager des photos et vidéos, et rejoindre des groupes basés sur des intérêts partagés. Le modèle le plus populaire par Facebook sur le Hugging Face Hub est facebook/esmfold_v1 avec 13 109 861 téléchargements. ``` </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 # Générer l'interface de chat, incluant les outils 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) # Générer l'AgentState et le graphe d'agent class AgentState(TypedDict): messages: Annotated[list[AnyMessage], add_messages] def assistant(state: AgentState): return { "messages": [chat_with_tools.invoke(state["messages"])], } ## Le graphe builder = StateGraph(AgentState) # Définir les nœuds : ils font le travail builder.add_node("assistant", assistant) builder.add_node("tools", ToolNode(tools)) # Définir les arêtes : elles déterminent comment le flux de contrôle se déplace builder.add_edge(START, "assistant") builder.add_conditional_edges( "assistant", # Si le dernier message nécessite un outil, router vers les outils # Sinon, fournir une réponse directe tools_condition, ) builder.add_edge("tools", "assistant") alfred = builder.compile() messages = [HumanMessage(content="Qui est Facebook et quel est leur modèle le plus populaire ?")] response = alfred.invoke({"messages": messages}) print("🎩 Réponse d'Alfred :") print(response['messages'][-1].content) ``` Sortie attendue : ``` 🎩 Réponse d'Alfred : Facebook est une entreprise de médias sociaux connue pour son site de réseau social, Facebook, ainsi que d'autres services comme Instagram et WhatsApp. Le modèle le plus téléchargé par Facebook sur le Hugging Face Hub est facebook/esmfold_v1 avec 13 202 321 téléchargements. ``` </hfoption> </hfoptions> ## Conclusion En intégrant ces outils, Alfred est maintenant équipé pour gérer une variété de tâches, des recherches web aux mises à jour météorologiques et aux statistiques de modèles. Cela garantit qu'il reste l'hôte le plus informé et engageant du gala. <Tip> Essayez d'implémenter un outil qui peut être utilisé pour obtenir les dernières nouvelles sur un sujet spécifique. Quand vous avez terminé, implémentez vos outils personnalisés dans le fichier <code>tools.py</code>. </Tip>
agents-course/units/fr/unit3/agentic-rag/tools.mdx/0
{ "file_path": "agents-course/units/fr/unit3/agentic-rag/tools.mdx", "repo_id": "agents-course", "token_count": 5593 }
14
# Unit 1 퀴즈 [[unit-1-quiz]] <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/whiteboard-unit1sub4DONE.jpg" alt="Unit 1 planning"/> 첫 번째 단원을 완료하신 것을 축하합니다! 지금까지 배운 핵심 개념들에 대한 이해도를 테스트해 보겠습니다. 퀴즈를 통과하면 다음 섹션으로 진행하여 수료증을 받을 수 있습니다. 행운을 빕니다! ## 퀴즈 [[quiz]] 여기 인터랙티브 퀴즈가 있습니다. 이 퀴즈는 Hugging Face Hub의 스페이스에서 호스팅됩니다. 이 단원에서 다룬 핵심 개념에 대한 이해도를 테스트하는 객관식 문제들이 제공됩니다. 퀴즈를 완료하면 점수와 정답 해설을 확인할 수 있습니다. 중요한 점: **통과 후 제출 버튼을 클릭하는 것을 잊지 마세요. 그렇지 않으면 시험 점수가 저장되지 않습니다!** <iframe src="https://agents-course-unit-1-quiz.hf.space" frameborder="0" width="850" height="450" ></iframe> 퀴즈에 👉 [여기](https://huggingface.co/spaces/agents-course/unit_1_quiz)에서도 접속할 수 있습니다. ## 수료증 [[certificate]] 퀴즈를 성공적으로 통과했으니, **이제 수료증을 받을 수 있습니다 🎓** 퀴즈를 완료하면 이 단원의 수료증에 접근할 수 있게 됩니다. 이 수료증을 다운로드하고 공유하여 과정에서의 진행 상황을 보여줄 수 있습니다. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/whiteboard-unit1sub5DONE.jpg" alt="Unit 1 planning"/> 수료증을 받으면 LinkedIn 🧑‍💼에 추가하거나 X, Bluesky 등에서 공유할 수 있습니다. **@huggingface를 태그하시면 저희가 매우 자랑스러워하며 축하해 드리고 싶습니다!** 🤗
agents-course/units/ko/unit1/final-quiz.mdx/0
{ "file_path": "agents-course/units/ko/unit1/final-quiz.mdx", "repo_id": "agents-course", "token_count": 1333 }
15
# Live 1: Как работает курс и первые ответы на вопросы В этой первой прямой трансляции курса по Агентам мы рассказали о том, как **работает** курс (объем, разделы, задачи и многое другое), и ответили на ваши вопросы. <iframe width="560" height="315" src="https://www.youtube.com/embed/iLVyYDbdSmM?si=TCX5Ai3uZuKLXq45" title="Видеоплеер YouTube" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe> Чтобы узнать, когда запланирован следующая прямая трансляция, проверьте наш сервер **Discord**. Мы также отправим вам электронное письмо. Если вы не сможете принять участие, не волнуйтесь, мы **записываем все прямые трансляции**.
agents-course/units/ru-RU/communication/live1.mdx/0
{ "file_path": "agents-course/units/ru-RU/communication/live1.mdx", "repo_id": "agents-course", "token_count": 576 }
16
# Быстрая самопроверка (не оценивается) [[quiz2]] Что?! Еще один тест? Мы знаем, мы знаем, ... 😅 Но эта короткий, не оцениваемый тест поможет вам **закрепить ключевые понятия, которые вы только что выучили**. Этот тест охватывает Большие Языковые Модели (Large Language Model), системы сообщений и инструменты; важные компоненты для понимания и создания агентов ИИ. ### Вопрос 1: Что из перечисленного ниже лучше всего описывает AI инструмент? <Question choices={[ { text: "Процесс, который генерирует только текстовые ответы.", explain: "", }, { text: "Исполняемый процесс или внешнее API, позволяющие агентам выполнять определенные задачи и взаимодействовать с внешней средой", explain: "Инструменты - это исполняемые функции, которые агенты могут использовать для выполнения определенных задач и взаимодействия с внешней средой.", correct: true }, { text: "Функция, хранящая диалоги агентов.", explain: "", } ]} /> --- ### Вопрос 2: Как AI агенты используют инструменты в качестве формы "действия" в окружающей среде? <Question choices={[ { text: "Пассивно ожидая инструкций пользователя.", explain: "", }, { text: "Используя только предварительно запрограммированные ответы.", explain: "", }, { text: "Запрашивая LLM сгенерировать код вызова инструментов, когда это необходимо, и запуская инструменты от имени модели", explain: "Агенты могут вызывать инструменты и использовать рассуждения для планирования и перепланирования на основе полученной информации.", correct: true } ]} /> --- ### Вопрос 3: Что такое Большая Языковая Модель (LLM)? <Question choices={[ { text: "Простой чат-бот, предназначенный для ответов на заранее определенные вопросы.", explain: "", }, { text: "Модель глубокого обучения, обученная на больших объемах текста для понимания и генерации человекоподобного языка.", explain: "", correct: true }, { text: "AI, основанный на правилах, который следует строго определенным командам.", explain: "", } ]} /> --- ### Вопрос 4: Что из перечисленного ниже лучше всего описывает роль специальных токенов в LLM? <Question choices={[ { text: "Это дополнительные слова, которые хранятся в словаре модели для повышения качества генерации текста.", explain: "", }, { text: "Они выполняют такие специфические функции, как обозначение конца последовательности (EOS) или разделение различных ролей сообщений в моделях чата.", explain: "", correct: true }, { text: "Это случайно вставленные токены, используемые для улучшения вариативности ответов.", explain: "", } ]} /> --- ### Вопрос 5: Как внутри AI модели чата обрабатывают сообщения пользователей? <Question choices={[ { text: "Они напрямую интерпретируют сообщения как структурированные команды без каких-либо преобразований.", explain: "", }, { text: "Они преобразуют сообщения пользователя в форматированную подсказку, конкатенируя сообщения системы, пользователя и ассистента.", explain: "", correct: true }, { text: "Они генерируют ответы случайным образом, основываясь на предыдущих диалогах.", explain: "", } ]} /> --- Получилось? Отлично! Теперь давайте **погрузимся в полный поток Агентов и начнем создавать вашего первого ИИ-Агента!**.
agents-course/units/ru-RU/unit1/quiz2.mdx/0
{ "file_path": "agents-course/units/ru-RU/unit1/quiz2.mdx", "repo_id": "agents-course", "token_count": 2951 }
17
# Hành động: Giúp Agent Tương tác với Môi trường <Tip> Trong phần này, chúng ta sẽ khám phá các bước cụ thể mà một AI agent thực hiện để tương tác với môi trường. Ta sẽ tìm hiểu cách biểu diễn hành động (sử dụng JSON hoặc code), tầm quan trọng của phương pháp dừng và phân tích (stop and parse approach), cùng các loại agent khác nhau. </Tip> Hành động là những bước cụ thể **một AI agent thực hiện để tương tác với môi trường**. Dù là duyệt web để tìm thông tin hay điều khiển thiết bị vật lý, mỗi hành động đều là một thao tác có chủ đích được agent thực thi. Ví dụ: một agent hỗ trợ dịch vụ khách hàng có thể truy xuất dữ liệu khách hàng, đề xuất bài viết hỗ trợ hoặc chuyển vấn đề cho nhân viên con người. ## Các loại Hành động của Agent Có nhiều loại Agent thực hiện hành động theo cách khác nhau: | Loại Agent | Mô tả | |------------------------|--------------------------------------------------------------------------------------------------| | JSON Agent | Hành động được xác định bằng định dạng JSON. | | Code Agent | Agent viết một khối code để hệ thống bên ngoài thực thi. | | Function-calling Agent | Là nhánh con của JSON Agent đã được tinh chỉnh để tạo thông điệp mới cho mỗi hành động. | Bản thân các hành động có thể phục vụ nhiều mục đích: | Loại Hành động | Mô tả | |--------------------------|------------------------------------------------------------------------------------------| | Thu thập thông tin | Thực hiện tìm kiếm web, truy vấn cơ sở dữ liệu, truy xuất tài liệu. | | Sử dụng Tools (công cụ) | Gọi API, chạy tính toán, thực thi code. | | Tương tác môi trường | Thao tác giao diện số hoặc điều khiển thiết bị vật lý. | | Giao tiếp | Tương tác với người dùng qua chat hoặc hợp tác với Agent khác. | Một phần quan trọng của agent là **khả năng DỪNG tạo token mới khi hoàn thành hành động**, đúng với mọi định dạng Agent: JSON, code hay function-calling. Điều này ngăn đầu ra ngoài ý muốn và đảm bảo phản hồi của agent rõ ràng, chính xác. LLM (Tìm kiếm và tạo ra câu trả lời) chỉ xử lý văn bản, dùng nó để mô tả hành động muốn thực hiện và tham số cần cung cấp cho công cụ. ## Phương pháp Dừng và Phân tích Một phương pháp chính để triển khai hành động là **phương pháp dừng và phân tích**. Phương pháp này đảm bảo đầu ra của Agent có cấu trúc và dự đoán được: 1. **Tạo đầu ra định dạng cấu trúc**: Agent xuất hành động dự định bằng định dạng xác định trước (JSON hoặc code). 2. **Dừng tạo token tiếp theo**: Khi hoàn thành hành động, **Agent dừng tạo token mới** để tránh đầu ra thừa/lỗi. 3. **Phân tích đầu ra**: Bộ phân tích bên ngoài đọc hành động đã định dạng, xác định Tool cần gọi và trích xuất tham số cần thiết. Ví dụ: một Agent cần kiểm tra thời tiết có thể đưa ra quyết định: ```json Tư duy: Tôi cần kiểm tra thời tiết hiện tại ở New York. Hành động: { "action": "get_weather", "action_input": {"location": "New York"} } ``` Framework sau đó dễ dàng phân tích tên hàm cần gọi và đối số cần áp dụng. Định dạng rõ ràng, máy đọc được này giảm thiểu lỗi và giúp công cụ bên ngoài xử lý chính xác lệnh của Agent. Lưu ý: Function-calling Agent hoạt động tương tự bằng cách cấu trúc mỗi hành động để gọi hàm được chỉ định với đúng đối số. Chúng ta sẽ tìm hiểu sâu hơn về các loại Agent này trong chương sau. ## Code Agent Một cách tiếp cận khác là sử dụng *Code Agent*. Ý tưởng: **thay vì xuất object JSON đơn giản**, Code Agent tạo **khối code thực thi được - thường bằng ngôn ngữ cấp cao như Python**. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/code-vs-json-actions.png" alt="Code Agents" /> Cách này có nhiều ưu điểm: - **Linh hoạt:** Code có thể biểu diễn logic phức tạp như vòng lặp, điều kiện, hàm lồng nhau, linh hoạt hơn JSON. - **Module và tái sử dụng:** Code tạo ra có thể chứa hàm/module dùng lại cho nhiều hành động/tác vụ. - **Dễ debug:** Với cú pháp lập trình xác định, lỗi code thường dễ phát hiện và sửa hơn. - **Tích hợp trực tiếp:** Code Agent tích hợp trực tiếp với thư viện/API bên ngoài, cho phép thao tác phức tạp như xử lý data hay ra quyết định thời gian thực. Ví dụ: Code Agent được giao nhiệm vụ lấy thông tin thời tiết có thể tạo đoạn Python sau: ```python # Ví dụ Code Agent: Lấy thông tin thời tiết def get_weather(city): import requests api_url = f"https://api.weather.com/v1/location/{city}?apiKey=YOUR_API_KEY" response = requests.get(api_url) if response.status_code == 200: data = response.json() return data.get("weather", "Không có thông tin thời tiết") else: return "Lỗi: Không thể lấy dữ liệu thời tiết." # Thực thi hàm và chuẩn bị câu trả lời cuối result = get_weather("New York") final_answer = f"Thời tiết hiện tại ở New York là: {result}" print(final_answer) ``` Trong ví dụ này, Code Agent: - Lấy data thời tiết **qua gọi API**, - Xử lý phản hồi, - Dùng hàm print() để xuất câu trả lời cuối. Phương pháp này **cũng tuân theo phương pháp dừng và phân tích** bằng cách xác định rõ khối code và báo hiệu khi hoàn thành (ở đây là in final_answer). --- Chúng ta đã học được rằng Hành động kết nối lập luận nội bộ của Agent với tương tác thực tế thông qua thực thi các tác vụ có cấu trúc rõ ràng - dù qua JSON, code hay lệnh gọi hàm. Việc thực thi có chủ đích này đảm bảo mỗi hành động chính xác và sẵn sàng cho xử lý bên ngoài qua phương pháp dừng và phân tích. Ở phần tiếp theo, ta sẽ khám phá Quan sát để xem Agent thu thập và tích hợp phản hồi từ môi trường thế nào. Sau đó, **chúng ta sẽ sẵn sàng xây dựng Agent đầu tiên của mình!**
agents-course/units/vi/unit1/actions.mdx/0
{ "file_path": "agents-course/units/vi/unit1/actions.mdx", "repo_id": "agents-course", "token_count": 4549 }
18
# 智能体框架介绍 <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/thumbnail.jpg" alt="Thumbnail"/> 欢迎来到第二单元,在这里**我们将探索不同的智能体框架(agentic frameworks)**,这些框架可用于构建强大的智能体应用。 我们将学习: - 在单元 2.1:[smolagents](https://huggingface.co/docs/smolagents/en/index) - 在单元 2.2:[LlamaIndex](https://www.llamaindex.ai/) - 在单元 2.3:[LangGraph](https://www.langchain.com/langgraph) 让我们开始吧!🕵 ## 何时使用智能体框架 **构建围绕大语言模型(LLMs)的应用时,并不总是需要智能体框架**。它们在工作流中提供了灵活性,可以高效地解决特定任务,但并非总是必需的。 有时,**预定义的工作流足以满足用户请求**,并且没有真正需要智能体框架。如果构建智能体的方法很简单,比如一系列提示,使用纯代码可能就足够了。优势在于开发者将**完全控制和理解他们的系统,没有抽象层**。 然而,当工作流变得更加复杂时,例如让大语言模型调用函数或使用多个智能体,这些抽象开始变得有用。 考虑到这些想法,我们已经可以确定对一些功能的需求: * 一个驱动系统的*大语言模型引擎*。 * 智能体可以访问的*工具列表*。 * 用于从大语言模型输出中提取工具调用的*解析器*。 * 与解析器同步的*系统提示*。 * 一个*记忆系统*。 * *错误日志和重试机制*以控制大语言模型的错误。 我们将探讨这些主题在各种框架中如何解决,包括 `smolagents`、`LlamaIndex` 和 `LangGraph`。 ## 智能体框架单元 | 框架 | 描述 | 单元作者 | |------------|----------------|----------------| | [smolagents](./smolagents/introduction) | 由 Hugging Face 开发的智能体框架。 | Sergio Paniego - [HF](https://huggingface.co/sergiopaniego) - [X](https://x.com/sergiopaniego) - [Linkedin](https://www.linkedin.com/in/sergio-paniego-blanco) | | [Llama-Index](./llama-index/introduction) | 将上下文增强智能体带至生产端的端到端工具 | David Berenstein - [HF](https://huggingface.co/davidberenstein1957) - [X](https://x.com/davidberenstei) - [Linkedin](https://www.linkedin.com/in/davidberenstein) | | [LangGraph](./langgraph/introduction) | 允许对智能体进行有序协调的智能体 | Joffrey THOMAS - [HF](https://huggingface.co/Jofthomas) - [X](https://x.com/Jthmas404) - [Linkedin](https://www.linkedin.com/in/joffrey-thomas) |
agents-course/units/zh-CN/unit2/introduction.mdx/0
{ "file_path": "agents-course/units/zh-CN/unit2/introduction.mdx", "repo_id": "agents-course", "token_count": 1568 }
19
# 在 LlamaIndex 中使用工具 **定义清晰明确的工具集对性能至关重要。** 正如我们在[第一单元](../../unit1/tools)中讨论的,清晰的工具接口更便于 LLM 使用。 就像人类工程师使用的软件API接口一样,如果工具的工作原理容易理解,LLM就能更好地利用它。 LlamaIndex 中主要包含**四种工具类型**: ![工具](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/llama-index/tools.png) 1. `FunctionTool`:将任意 Python 函数转换为智能体可以使用的工具。它能自动识别函数的工作原理。 2. `QueryEngineTool`:让智能体能够使用查询引擎的工具。由于智能体本身基于查询引擎构建,因此它们也可以将其他智能体作为工具使用。 3. `Toolspecs`:由社区创建的预设工具集,通常包含针对特定服务(如 Gmail)的工具。 4. `Utility Tools`:帮助处理来自其他工具的大量数据的特殊工具。 下面我们将详细讲解每种工具的使用方法。 ## 创建FunctionTool <Tip> 您可以通过<a href="https://huggingface.co/agents-course/notebooks/blob/main/unit2/llama-index/tools.ipynb" target="_blank">这个 Notebook</a>中的代码进行实践(支持 Google Colab 运行)。 </Tip> FunctionTool 提供了一种简单的方式,可以将任意 Python 函数封装成智能体可用的工具。 你可以传递同步或异步函数给这个工具,并可选地指定`name`和`description`参数。 工具名称和描述尤为重要,它们能帮助智能体理解何时以及如何有效地使用该工具。 以下示例演示了如何创建并调用 FunctionTool。 ```python from llama_index.core.tools import FunctionTool def get_weather(location: str) -> str: """Useful for getting the weather for a given location.""" print(f"Getting weather for {location}") return f"The weather in {location} is sunny" tool = FunctionTool.from_defaults( get_weather, name="my_weather_tool", description="Useful for getting the weather for a given location.", ) tool.call("New York") ``` <Tip>使用带有函数调用的智能体或 LLM 时,所选工具(以及为该工具编写的参数)在很大程度上取决于工具名称以及工具用途和参数的描述。在<a href="https://docs.llamaindex.ai/en/stable/examples/workflow/function_calling_agent/">函数调用指南</a>。</Tip> ## 创建 QueryEngineTool 我们在上一单元中定义的 `QueryEngine` 可以使用 `QueryEngineTool` 类轻松转换为工具。 让我们看看如何在下面的示例中从 `QueryEngine` 创建 `QueryEngineTool`。 ```python from llama_index.core import VectorStoreIndex from llama_index.core.tools import QueryEngineTool from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI from llama_index.embeddings.huggingface_api import HuggingFaceInferenceAPIEmbedding from llama_index.vector_stores.chroma import ChromaVectorStore embed_model = HuggingFaceInferenceAPIEmbedding("BAAI/bge-small-en-v1.5") db = chromadb.PersistentClient(path="./alfred_chroma_db") chroma_collection = db.get_or_create_collection("alfred") vector_store = ChromaVectorStore(chroma_collection=chroma_collection) index = VectorStoreIndex.from_vector_store(vector_store, embed_model=embed_model) llm = HuggingFaceInferenceAPI(model_name="Qwen/Qwen2.5-Coder-32B-Instruct") query_engine = index.as_query_engine(llm=llm) tool = QueryEngineTool.from_defaults(query_engine, name="some useful name", description="some useful description") ``` ## 创建 Toolspecs 将 `ToolSpecs` 视为可以和谐协作的工具集合 - 就像一个组织良好的专业工具包。 就像机械师的工具包包含用于车辆维修的互补工具一样,`ToolSpec` 会将相关工具组合起来用于特定目的。 例如,会计智能体的 `ToolSpec` 可以优雅地集成电子表格功能、电子邮件功能和计算工具,以精确高效地处理财务任务。 <details> <summary>安装 Google Toolspec</summary> 正如 [LlamaHub 部分](llama-hub) 中介绍的那样,我们可以使用以下命令安装 Google toolspec: ```python pip install llama-index-tools-google ``` </details> 现在我们可以加载工具规范并将其转换为工具列表。 ```python from llama_index.tools.google import GmailToolSpec tool_spec = GmailToolSpec() tool_spec_list = tool_spec.to_tool_list() ``` 为了更详细地了解这些工具,我们可以查看每个工具的`元数据`。 ```python [(tool.metadata.name, tool.metadata.description) for tool in tool_spec_list] ``` ## 实用工具 很多时候,直接查询 API **可能会返回过量数据**,其中部分可能无关紧要、超出 LLM 的上下文窗口容量,或导致不必要的 token 消耗。 让我们详细了解以下两个主要实用工具: 1. `OnDemandToolLoader`:该工具可将任何现有的 LlamaIndex 数据加载器(BaseReader 类)转化为智能体可使用的工具。该工具可通过调用数据加载器`load_data`所需的所有参数以及自然语言查询字符串来触发。在执行过程中,我们首先从数据加载器加载数据,建立索引(例如使用向量存储),然后进行"按需"查询。这三个步骤都在单个工具调用中完成。 2. `LoadAndSearchToolSpec`:该工具规范接受任何现有工具作为输入。作为工具规范,它实现了`to_tool_list`方法,调用该方法时会返回两个工具:加载工具和搜索工具。加载工具的执行会调用底层工具并对输出建立索引(默认使用向量索引)。搜索工具的执行会接受查询字符串作为输入并调用底层索引。 <Tip>您可以在<a href="https://llamahub.ai/">LlamaHub</a>找到各种工具规范和实用工具</Tip> 现在我们已经理解了 LlamaIndex 中智能体和工具的基础知识,接下来让我们看看如何**使用 LlamaIndex 创建可配置且易管理的工作流程!**
agents-course/units/zh-CN/unit2/llama-index/tools.mdx/0
{ "file_path": "agents-course/units/zh-CN/unit2/llama-index/tools.mdx", "repo_id": "agents-course", "token_count": 3312 }
20
# 智能体增强检索生成(Agentic RAG) 在本单元中,我们将探讨如何利用智能体增强检索生成(Agentic RAG)帮助 Alfred 筹备精彩的晚会。 <Tip>提示:我们已在先前单元讨论过检索增强生成(RAG)和智能体增强 RAG,如果您已熟悉这些概念可跳过本节。</Tip> 大语言模型(LLMs)通过海量数据训练获得通用知识。 但其世界知识模型可能包含过时或不相关信息。 **RAG 通过从您的数据中检索相关信息并传递给大语言模型,有效解决了这个问题。** ![RAG 示意图](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/llama-index/rag.png) 思考 Alfred 的工作流程: 1. 我们要求 Alfred 协助策划晚会 2. Alfred 需要获取最新新闻和天气信息 3. Alfred 需要整理和检索宾客信息 正如 Alfred 需要搜索家庭信息才能提供有效帮助,任何智能体都需要理解和检索相关数据的能力。 **智能体增强 RAG 是帮助智能体解答数据问题的强大工具**,我们可以为 Alfred 提供多种工具来辅助问题解答。 与传统文档自动问答不同,Alfred 可以自主决定使用任何工具或流程来回答问题。 ![智能体增强 RAG 架构](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/llama-index/agentic-rag.png) 现在让我们开始**构建智能体增强 RAG 工作流**! 首先创建用于检索最新受邀者详情的 RAG 工具,接着开发网络搜索、天气更新和 Hugging Face Hub 模型下载统计等工具,最终整合所有组件实现我们的智能体增强 RAG 智能体!
agents-course/units/zh-CN/unit3/agentic-rag/agentic-rag.mdx/0
{ "file_path": "agents-course/units/zh-CN/unit3/agentic-rag/agentic-rag.mdx", "repo_id": "agents-course", "token_count": 1137 }
21
repos: - repo: https://github.com/Narsil/pre-commit-rust rev: 2eed6366172ef2a5186e8785ec0e67243d7d73d0 hooks: - id: fmt name: "Rust (fmt)" - id: clippy name: "Rust (clippy)" args: [ "--tests", "--examples", "--", "-Dwarnings", ]
candle/.pre-commit-config.yaml/0
{ "file_path": "candle/.pre-commit-config.yaml", "repo_id": "candle", "token_count": 210 }
22
# Creating a desktop Tauri app
candle/candle-book/src/apps/desktop.md/0
{ "file_path": "candle/candle-book/src/apps/desktop.md", "repo_id": "candle", "token_count": 8 }
23
# Porting a custom kernel
candle/candle-book/src/inference/cuda/porting.md/0
{ "file_path": "candle/candle-book/src/inference/cuda/porting.md", "repo_id": "candle", "token_count": 7 }
24
use crate::benchmarks::{BenchDevice, BenchDeviceHandler}; use candle_core::{DType, Device, Tensor}; use criterion::{black_box, criterion_group, Criterion, Throughput}; use std::time::Instant; fn run(a: &Tensor) { a.affine(12.34, 56.78).unwrap(); } fn run_affine_benchmark(c: &mut Criterion, device: &Device, dtype: DType, name: &str) { let b = 1; let m = 1024; let k = 1024; let tensor = Tensor::zeros((b, m, k), dtype, device).unwrap(); let flops = b * m * k * dtype.size_in_bytes(); let mut group = c.benchmark_group(device.bench_name(name)); group.throughput(Throughput::Bytes(flops as u64)); group.bench_function("iter", move |b| { b.iter_custom(|iters| { let start = Instant::now(); for _i in 0..iters { run(black_box(&tensor)); } device.sync().unwrap(); start.elapsed() }) }); group.finish(); } fn criterion_benchmark(c: &mut Criterion) { let handler = BenchDeviceHandler::new().unwrap(); for device in handler.devices { run_affine_benchmark(c, &device, DType::F32, "affine_f32"); run_affine_benchmark(c, &device, DType::F16, "affine_f16"); run_affine_benchmark(c, &device, DType::BF16, "affine_bf16"); run_affine_benchmark(c, &device, DType::F8E4M3, "affine_fp8"); } } criterion_group!(benches, criterion_benchmark);
candle/candle-core/benches/benchmarks/affine.rs/0
{ "file_path": "candle/candle-core/benches/benchmarks/affine.rs", "repo_id": "candle", "token_count": 628 }
25
//! Methods for backpropagation of gradients. use crate::op::{BinaryOp, Op, ReduceOp, UnaryOp}; use crate::{Error, Result, Tensor, TensorId}; use std::collections::HashMap; // arg has been reduced to node via reduce_dims, expand it back to arg. // This has to handle keepdims. fn broadcast_back(arg: &Tensor, node: &Tensor, reduced_dims: &[usize]) -> Result<Tensor> { if arg.rank() == node.rank() { // keepdim = true node.broadcast_as(arg.shape()) } else { // keepdim = false // first expand the reduced dims. node.reshape(reduced_dims)?.broadcast_as(arg.shape()) } } thread_local! { static CANDLE_GRAD_DO_NOT_DETACH: bool = { match std::env::var("CANDLE_GRAD_DO_NOT_DETACH") { Ok(s) => { !s.is_empty() && s != "0" }, Err(_) => false, } } } impl Tensor { /// Return all the nodes that lead to this value in a topologically sorted vec, the first /// elements having dependencies on the latter ones, e.g. the first element if any is the /// argument. /// This assumes that the op graph is a DAG. pub fn sorted_nodes(&self) -> Vec<&Tensor> { // The vec of sorted nodes is passed as an owned value rather than a mutable reference // to get around some lifetime limitations. fn walk<'a>( node: &'a Tensor, nodes: Vec<&'a Tensor>, already_seen: &mut HashMap<TensorId, bool>, ) -> (bool, Vec<&'a Tensor>) { if let Some(&tg) = already_seen.get(&node.id()) { return (tg, nodes); } let mut track_grad = false; let mut nodes = if node.is_variable() { // Do not call recursively on the "leaf" nodes. track_grad = true; nodes } else if node.dtype().is_int() { nodes } else if let Some(op) = node.op() { match op { Op::IndexAdd(t1, t2, t3, _) | Op::Scatter(t1, t2, t3, _) | Op::ScatterAdd(t1, t2, t3, _) | Op::CustomOp3(t1, t2, t3, _) | Op::WhereCond(t1, t2, t3) => { let (tg, nodes) = walk(t1, nodes, already_seen); track_grad |= tg; let (tg, nodes) = walk(t2, nodes, already_seen); track_grad |= tg; let (tg, nodes) = walk(t3, nodes, already_seen); track_grad |= tg; nodes } Op::Conv1D { arg: lhs, kernel: rhs, .. } | Op::ConvTranspose1D { arg: lhs, kernel: rhs, .. } | Op::Conv2D { arg: lhs, kernel: rhs, .. } | Op::ConvTranspose2D { arg: lhs, kernel: rhs, .. } | Op::CustomOp2(lhs, rhs, _) | Op::Binary(lhs, rhs, _) | Op::Gather(lhs, rhs, _) | Op::IndexSelect(lhs, rhs, _) | Op::Matmul(lhs, rhs) | Op::SliceScatter0(lhs, rhs, _) => { let (tg, nodes) = walk(lhs, nodes, already_seen); track_grad |= tg; let (tg, nodes) = walk(rhs, nodes, already_seen); track_grad |= tg; nodes } Op::Cat(args, _) => args.iter().fold(nodes, |nodes, arg| { let (tg, nodes) = walk(arg, nodes, already_seen); track_grad |= tg; nodes }), Op::Affine { arg, mul, .. } => { if *mul == 0. { nodes } else { let (tg, nodes) = walk(arg, nodes, already_seen); track_grad |= tg; nodes } } Op::Unary(_node, UnaryOp::Ceil) | Op::Unary(_node, UnaryOp::Floor) | Op::Unary(_node, UnaryOp::Round) | Op::Unary(_node, UnaryOp::Sign) => nodes, Op::Reshape(node) | Op::UpsampleNearest1D { arg: node, .. } | Op::UpsampleNearest2D { arg: node, .. } | Op::AvgPool2D { arg: node, .. } | Op::MaxPool2D { arg: node, .. } | Op::Copy(node) | Op::Broadcast(node) | Op::Cmp(node, _) | Op::Reduce(node, ReduceOp::Min | ReduceOp::Sum | ReduceOp::Max, _) | Op::ToDevice(node) | Op::Transpose(node, _, _) | Op::Permute(node, _) | Op::Narrow(node, _, _, _) | Op::Unary(node, _) | Op::Elu(node, _) | Op::Powf(node, _) | Op::CustomOp1(node, _) => { let (tg, nodes) = walk(node, nodes, already_seen); track_grad |= tg; nodes } Op::ToDType(node) => { if node.dtype().is_float() { let (tg, nodes) = walk(node, nodes, already_seen); track_grad |= tg; nodes } else { nodes } } Op::Reduce(_, ReduceOp::ArgMin | ReduceOp::ArgMax, _) => nodes, } } else { nodes }; already_seen.insert(node.id(), track_grad); if track_grad { nodes.push(node); } (track_grad, nodes) } let (_tg, mut nodes) = walk(self, vec![], &mut HashMap::new()); nodes.reverse(); nodes } pub fn backward(&self) -> Result<GradStore> { let sorted_nodes = self.sorted_nodes(); let mut grads = GradStore::new(); grads.insert(self, self.ones_like()?.contiguous()?); for node in sorted_nodes.iter() { if node.is_variable() { continue; } let grad = grads .remove(node) .expect("candle internal error - grad not populated"); // https://github.com/huggingface/candle/issues/1241 // Ideally, we would make these operations in place where possible to ensure that we // do not have to allocate too often. Here we just call `.detach` to avoid computing // the backprop graph of the backprop itself. This would be an issue for second order // derivatives but these are out of scope at the moment. let do_not_detach = CANDLE_GRAD_DO_NOT_DETACH.with(|b| *b); let grad = if do_not_detach { grad } else { grad.detach() }; if let Some(op) = node.op() { match op { Op::Binary(lhs, rhs, BinaryOp::Add) => { let lhs_sum_grad = grads.or_insert(lhs)?; *lhs_sum_grad = lhs_sum_grad.add(&grad)?; let rhs_sum_grad = grads.or_insert(rhs)?; *rhs_sum_grad = rhs_sum_grad.add(&grad)?; } Op::Binary(lhs, rhs, BinaryOp::Sub) => { let lhs_sum_grad = grads.or_insert(lhs)?; *lhs_sum_grad = lhs_sum_grad.add(&grad)?; let rhs_sum_grad = grads.or_insert(rhs)?; *rhs_sum_grad = rhs_sum_grad.sub(&grad)?; } Op::Binary(lhs, rhs, BinaryOp::Mul) => { let lhs_grad = grad.mul(rhs)?; let lhs_sum_grad = grads.or_insert(lhs)?; *lhs_sum_grad = lhs_sum_grad.add(&lhs_grad)?; let rhs_grad = grad.mul(lhs)?; let rhs_sum_grad = grads.or_insert(rhs)?; *rhs_sum_grad = rhs_sum_grad.add(&rhs_grad)?; } Op::Binary(lhs, rhs, BinaryOp::Div) => { let lhs_grad = grad.div(rhs)?; let lhs_sum_grad = grads.or_insert(lhs)?; *lhs_sum_grad = lhs_sum_grad.add(&lhs_grad)?; let rhs_grad = grad.mul(lhs)?.div(&rhs.sqr()?)?; let rhs_sum_grad = grads.or_insert(rhs)?; *rhs_sum_grad = rhs_sum_grad.sub(&rhs_grad)?; } Op::Binary(lhs, rhs, BinaryOp::Minimum) | Op::Binary(lhs, rhs, BinaryOp::Maximum) => { let mask_lhs = node.eq(lhs)?.to_dtype(grad.dtype())?; let mask_rhs = node.eq(rhs)?.to_dtype(grad.dtype())?; // If both masks are 1 one the same point, we want to scale the // gradient by 0.5 rather than 1. let lhs_grad = mask_lhs.mul(&grad)?.div(&(&mask_rhs + 1.)?)?; let lhs_sum_grad = grads.or_insert(lhs)?; *lhs_sum_grad = lhs_sum_grad.add(&lhs_grad)?; let rhs_grad = mask_rhs.mul(&grad)?.div(&(&mask_lhs + 1.)?)?; let rhs_sum_grad = grads.or_insert(rhs)?; *rhs_sum_grad = rhs_sum_grad.add(&rhs_grad)?; } Op::WhereCond(pred, t, f) => { let zeros = grad.zeros_like()?; let t_sum_grad = grads.or_insert(t)?; let t_grad = pred.where_cond(&grad, &zeros)?; *t_sum_grad = t_sum_grad.add(&t_grad)?; let f_sum_grad = grads.or_insert(f)?; let f_grad = pred.where_cond(&zeros, &grad)?; *f_sum_grad = f_sum_grad.add(&f_grad)?; } Op::Conv1D { arg, kernel, padding, stride, dilation, } => { // The output height for conv_transpose1d is: // (l_in - 1) * stride - 2 * padding + dilation * (k_size - 1) + out_padding + 1 let grad_l_in = grad.dim(2)?; let k_size = kernel.dim(2)?; let out_size = (grad_l_in - 1) * stride + dilation * (k_size - 1) + 1 - 2 * padding; let out_padding = arg.dim(2)? - out_size; let grad_arg = grad.conv_transpose1d( kernel, *padding, out_padding, *stride, *dilation, /* groups */ 1, )?; let sum_grad = grads.or_insert(arg)?; *sum_grad = sum_grad.add(&grad_arg)?; let grad_kernel = arg .transpose(0, 1)? .conv1d(&grad.transpose(0, 1)?, *padding, *dilation, *stride, 1)? .transpose(0, 1)?; let sum_grad = grads.or_insert(kernel)?; let (_, _, k0) = kernel.dims3()?; let (_, _, g_k0) = grad_kernel.dims3()?; let grad_kernel = if g_k0 != k0 { grad_kernel.narrow(2, 0, k0)? } else { grad_kernel }; *sum_grad = sum_grad.add(&grad_kernel)?; } Op::Conv2D { arg, kernel, padding, stride, dilation, } => { // The output height for conv_transpose2d is: // (i_h - 1) * stride - 2 * padding + dilation * (k_h - 1) + out_padding + 1 let grad_h = grad.dim(2)?; let k_h = kernel.dim(2)?; let out_size = (grad_h - 1) * stride + dilation * (k_h - 1) + 1 - 2 * padding; let out_padding = arg.dim(2)? - out_size; let grad_arg = grad.conv_transpose2d( kernel, *padding, out_padding, *stride, *dilation, )?; let sum_grad = grads.or_insert(arg)?; *sum_grad = sum_grad.add(&grad_arg)?; let grad_kernel = arg .transpose(0, 1)? .conv2d(&grad.transpose(0, 1)?, *padding, *dilation, *stride, 1)? .transpose(0, 1)?; let sum_grad = grads.or_insert(kernel)?; let (_, _, k0, k1) = kernel.dims4()?; let (_, _, g_k0, g_k1) = grad_kernel.dims4()?; let grad_kernel = if g_k0 != k0 || g_k1 != k1 { grad_kernel.narrow(2, 0, k0)?.narrow(3, 0, k1)? } else { grad_kernel }; *sum_grad = sum_grad.add(&grad_kernel)?; } Op::ConvTranspose1D { .. } => Err(Error::BackwardNotSupported { op: "conv-transpose1d", })?, Op::ConvTranspose2D { arg, kernel, padding, stride, dilation, output_padding: _output_padding, } => { let grad_arg = grad.conv2d(kernel, *padding, *stride, *dilation, 1)?; let sum_grad = grads.or_insert(arg)?; *sum_grad = sum_grad.add(&grad_arg)?; let grad_kernel = grad .transpose(0, 1)? .conv2d(&arg.transpose(0, 1)?, *padding, *dilation, *stride, 1)? .transpose(0, 1)?; let sum_grad = grads.or_insert(kernel)?; let (_, _, k0, k1) = kernel.dims4()?; let (_, _, g_k0, g_k1) = grad_kernel.dims4()?; let grad_kernel = if g_k0 != k0 || g_k1 != k1 { grad_kernel.narrow(2, 0, k0)?.narrow(3, 0, k1)? } else { grad_kernel }; *sum_grad = sum_grad.add(&grad_kernel)?; } Op::AvgPool2D { arg, kernel_size, stride, } => { if kernel_size != stride { crate::bail!("backward not supported for avgpool2d if ksize {kernel_size:?} != stride {stride:?}") } let (_n, _c, h, w) = arg.dims4()?; let grad_arg = grad.upsample_nearest2d(h, w)?; let grad_arg = (grad_arg * (1f64 / (kernel_size.0 * kernel_size.1) as f64))?; let sum_grad = grads.or_insert(arg)?; *sum_grad = sum_grad.add(&grad_arg)?; } Op::MaxPool2D { arg, kernel_size, stride, } => { if kernel_size != stride { crate::bail!("backward not supported for maxpool2d if ksize {kernel_size:?} != stride {stride:?}") } let (_n, _c, h, w) = arg.dims4()?; // For computing the max-pool gradient, we compute a mask where a 1 means // that the element is the maximum, then we apply this mask to the // upsampled gradient (taking into account that multiple max may exist so // we scale the gradient for this case). let node_upsampled = node.upsample_nearest2d(h, w)?; let mask = arg.eq(&node_upsampled)?.to_dtype(arg.dtype())?; let avg = mask.avg_pool2d_with_stride(*kernel_size, *stride)?; let grad_arg = ((grad * avg)?.upsample_nearest2d(h, w)? * mask)?; let sum_grad = grads.or_insert(arg)?; *sum_grad = sum_grad.add(&grad_arg)?; } Op::UpsampleNearest1D { arg, target_size } => { let (_n, c, size) = arg.dims3()?; if target_size % size != 0 { crate::bail!("backward not supported for non integer upscaling factors") } let scale = target_size / size; let kernel = Tensor::ones((c, 1, scale), arg.dtype(), arg.device())?; let conv_sum = grad.conv1d(&kernel, 0, scale, 1, c)?; let sum_grad = grads.or_insert(arg)?; *sum_grad = conv_sum; } Op::UpsampleNearest2D { arg, target_h, target_w, } => { let (_n, c, h, w) = arg.dims4()?; if target_h % h != 0 || target_w % w != 0 { crate::bail!("backward not supported for non integer upscaling factors") } let scale_h = target_h / h; let scale_w = target_w / w; if scale_h != scale_w { crate::bail!("backward not supported for non uniform upscaling factors") }; let kernel = Tensor::ones((c, 1, scale_h, scale_w), arg.dtype(), arg.device())?; let conv_sum = grad.conv2d(&kernel, 0, scale_h, 1, c)?; let sum_grad = grads.or_insert(arg)?; *sum_grad = conv_sum; } Op::SliceScatter0(lhs, rhs, start_rhs) => { let rhs_sum_grad = grads.or_insert(rhs)?; let rhs_grad = grad.narrow(0, *start_rhs, rhs.dim(0)?)?; *rhs_sum_grad = rhs_sum_grad.add(&rhs_grad)?; let lhs_sum_grad = grads.or_insert(lhs)?; let lhs_grad = grad.slice_scatter0(&rhs.zeros_like()?, *start_rhs)?; *lhs_sum_grad = lhs_sum_grad.add(&lhs_grad)? } Op::Gather(arg, indexes, dim) => { let sum_grad = grads.or_insert(arg)?; *sum_grad = sum_grad.scatter_add(indexes, &grad, *dim)?; } Op::Scatter(init, indexes, src, dim) => { let init_sum_grad = grads.or_insert(init)?; *init_sum_grad = init_sum_grad.add(&grad)?; let src_grad = grad.gather(indexes, *dim)?; let src_sum_grad = grads.or_insert(src)?; *src_sum_grad = src_sum_grad.add(&src_grad)?; } Op::ScatterAdd(init, indexes, src, dim) => { let init_sum_grad = grads.or_insert(init)?; let mask = init.ones_like()?; let mask = mask.scatter(indexes, &mask.zeros_like()?, *dim)?; *init_sum_grad = init_sum_grad.add(&grad.mul(&mask)?)?; let src_grad = grad.gather(indexes, *dim)?; let src_sum_grad = grads.or_insert(src)?; *src_sum_grad = src_sum_grad.add(&src_grad)?; } Op::IndexAdd(init, indexes, src, dim) => { let init_sum_grad = grads.or_insert(init)?; *init_sum_grad = init_sum_grad.add(&grad)?; let src_grad = grad.index_select(indexes, *dim)?; let src_sum_grad = grads.or_insert(src)?; *src_sum_grad = src_sum_grad.add(&src_grad)?; } Op::IndexSelect(arg, indexes, dim) => { let sum_grad = grads.or_insert(arg)?; *sum_grad = sum_grad.index_add(indexes, &grad, *dim)?; } Op::Matmul(lhs, rhs) => { // Skipping checks, the op went ok, we can skip // the matmul size checks for now. let lhs_grad = grad.matmul(&rhs.t()?)?; let lhs_sum_grad = grads.or_insert(lhs)?; *lhs_sum_grad = lhs_sum_grad.add(&lhs_grad)?; let rhs_grad = lhs.t()?.matmul(&grad)?; let rhs_sum_grad = grads.or_insert(rhs)?; *rhs_sum_grad = rhs_sum_grad.add(&rhs_grad)?; } Op::Cat(args, dim) => { let mut start_idx = 0; for arg in args { let len = arg.dims()[*dim]; let arg_grad = grad.narrow(*dim, start_idx, len)?; let sum_grad = grads.or_insert(arg)?; *sum_grad = sum_grad.add(&arg_grad)?; start_idx += len; } } Op::Broadcast(arg) => { let arg_dims = arg.dims(); let node_dims = node.dims(); // The number of dims that have been inserted on the left. let left_dims = node_dims.len() - arg_dims.len(); let mut sum_dims: Vec<usize> = (0..left_dims).collect(); for (dim, (node_dim, arg_dim)) in node_dims[left_dims..] .iter() .zip(arg_dims.iter()) .enumerate() { if node_dim != arg_dim { sum_dims.push(dim + left_dims) } } let mut arg_grad = grad.sum_keepdim(sum_dims.as_slice())?; for _i in 0..left_dims { arg_grad = arg_grad.squeeze(0)? } let sum_grad = grads.or_insert(arg)?; *sum_grad = sum_grad.add(&arg_grad.broadcast_as(sum_grad.dims())?)?; } Op::Reduce(arg, ReduceOp::Sum, reduced_dims) => { let grad = broadcast_back(arg, &grad, reduced_dims)?; let sum_grad = grads.or_insert(arg)?; *sum_grad = sum_grad.add(&grad)?; } Op::Reduce(arg, ReduceOp::Max, reduced_dims) => { let node = broadcast_back(arg, node, reduced_dims)?; let grad = broadcast_back(arg, &grad, reduced_dims)?; let grad = node.eq(arg)?.to_dtype(grad.dtype())?.mul(&grad)?; let sum_grad = grads.or_insert(arg)?; *sum_grad = sum_grad.add(&grad.broadcast_as(sum_grad.dims())?)?; } Op::Reduce(arg, ReduceOp::Min, reduced_dims) => { let node = broadcast_back(arg, node, reduced_dims)?; let grad = broadcast_back(arg, &grad, reduced_dims)?; let grad = node.eq(arg)?.to_dtype(grad.dtype())?.mul(&grad)?; let sum_grad = grads.or_insert(arg)?; *sum_grad = sum_grad.add(&grad.broadcast_as(sum_grad.dims())?)?; } Op::ToDType(arg) => { let sum_grad = grads.or_insert(arg)?; *sum_grad = sum_grad.add(&grad.to_dtype(arg.dtype())?)? } Op::Copy(arg) => { let sum_grad = grads.or_insert(arg)?; *sum_grad = sum_grad.add(&grad)? } Op::Affine { arg, mul, .. } => { let arg_grad = grad.affine(*mul, 0.)?; let sum_grad = grads.or_insert(arg)?; *sum_grad = sum_grad.add(&arg_grad)? } Op::Unary(arg, UnaryOp::Log) => { let sum_grad = grads.or_insert(arg)?; *sum_grad = sum_grad.add(&(grad / arg)?)? } Op::Unary(arg, UnaryOp::Sin) => { let sum_grad = grads.or_insert(arg)?; *sum_grad = sum_grad.add(&(&grad * arg.cos())?)? } Op::Unary(arg, UnaryOp::Cos) => { let sum_grad = grads.or_insert(arg)?; *sum_grad = sum_grad.sub(&(&grad * arg.sin())?)? } Op::Unary(arg, UnaryOp::Tanh) => { let sum_grad = grads.or_insert(arg)?; let minus_dtanh = (node.sqr()? - 1.)?; *sum_grad = sum_grad.sub(&(&grad * &minus_dtanh)?)? } Op::Unary(arg, UnaryOp::Abs) => { let sum_grad = grads.or_insert(arg)?; let ones = arg.ones_like()?; let abs_grad = arg.ge(&arg.zeros_like()?)?.where_cond(&ones, &ones.neg()?); *sum_grad = sum_grad.add(&(&grad * abs_grad)?)? } Op::Unary(arg, UnaryOp::Exp) => { let sum_grad = grads.or_insert(arg)?; *sum_grad = sum_grad.add(&(&grad * *node)?)? } Op::Unary(arg, UnaryOp::Neg) => { let sum_grad = grads.or_insert(arg)?; *sum_grad = sum_grad.sub(&grad)? } Op::Unary(arg, UnaryOp::Recip) => { let sum_grad = grads.or_insert(arg)?; let grad = (grad / arg.sqr()?)?; *sum_grad = sum_grad.sub(&grad)? } &Op::Narrow(ref arg, dim, start_idx, len) => { let arg_dims = arg.dims(); let left_pad = if start_idx == 0 { None } else { let mut dims = arg_dims.to_vec(); dims[dim] = start_idx; Some(Tensor::zeros(dims, grad.dtype(), grad.device())?) }; let right_pad = arg_dims[dim] - start_idx - len; let right_pad = if right_pad == 0 { None } else { let mut dims = arg_dims.to_vec(); dims[dim] = right_pad; Some(Tensor::zeros(dims, grad.dtype(), grad.device())?) }; let arg_grad = match (left_pad, right_pad) { (None, None) => grad, (Some(l), None) => Tensor::cat(&[&l, &grad], dim)?, (None, Some(r)) => Tensor::cat(&[&grad, &r], dim)?, (Some(l), Some(r)) => Tensor::cat(&[&l, &grad, &r], dim)?, }; let sum_grad = grads.or_insert(arg)?; *sum_grad = sum_grad.add(&arg_grad)? } Op::Unary(_, UnaryOp::Floor) | Op::Unary(_, UnaryOp::Round) | Op::Reduce(_, ReduceOp::ArgMin, _) | Op::Reduce(_, ReduceOp::ArgMax, _) | Op::Unary(_, UnaryOp::Sign) | Op::Cmp(_, _) => {} Op::Reshape(arg) => { let arg_grad = grad.reshape(arg.dims())?; let sum_grad = grads.or_insert(arg)?; *sum_grad = sum_grad.add(&arg_grad)? } Op::Unary(_, UnaryOp::Ceil) => Err(Error::BackwardNotSupported { op: "ceil" })?, Op::Unary(arg, UnaryOp::Gelu) => { let sum_grad = grads.or_insert(arg)?; let cube = arg.powf(3.)?; let tanh = (0.0356774 * &cube + (0.797885 * arg)?)?.tanh()?; let gelu_grad = (((0.5 * &tanh)? + (0.0535161 * cube + (0.398942 * arg)?)? * (1. - tanh.powf(2.)?))? + 0.5)?; *sum_grad = sum_grad.add(&(&grad * gelu_grad)?)? } Op::Unary(arg, UnaryOp::Erf) => { let sum_grad = grads.or_insert(arg)?; // d/dx erf(x) = 2/sqrt(pi) * e^(-x^2) let erf_grad = (2. / std::f64::consts::PI.sqrt()) * (arg.sqr()?.neg()?).exp()?; *sum_grad = sum_grad.add(&(&grad * erf_grad)?)? } Op::Unary(arg, UnaryOp::GeluErf) => { let sum_grad = grads.or_insert(arg)?; // d/dx gelu_erf(x) = 0.5 + 0.398942 e^(-x^2/2) x + 0.5 erf(x/sqrt(2)) let neg_half_square = (arg.sqr()?.neg()? / 2.)?; let scaled_exp_arg = (0.398942 * neg_half_square.exp()? * arg)?; let arg_scaled_sqrt = (arg / 2f64.sqrt())?; let erf_scaled_sqrt = (0.5 * arg_scaled_sqrt.erf()?)?; let gelu_erf_grad = (0.5 + scaled_exp_arg + erf_scaled_sqrt)?; *sum_grad = sum_grad.add(&(&grad * gelu_erf_grad)?)?; } Op::Unary(arg, UnaryOp::Relu) => { let sum_grad = grads.or_insert(arg)?; let relu_grad = arg.ge(&arg.zeros_like()?)?.to_dtype(arg.dtype())?; *sum_grad = sum_grad.add(&(&grad * relu_grad)?)? } Op::Unary(arg, UnaryOp::Silu) => { let sum_grad = grads.or_insert(arg)?; // d/dx silu = sigmoid(x) * (1 + x * (1 - sigmoid(x))) = sigmoid(x) * (1 - node) + node let sigmoid_arg = (arg.neg()?.exp()? + 1.)?.recip()?; let silu_grad = &sigmoid_arg * (1. - *node) + *node; *sum_grad = sum_grad.add(&(&grad * silu_grad)?)? } Op::Elu(arg, alpha) => { // d/dx elu(x) = 1 for x > 0, alpha * e^x for x <= 0 let sum_grad = grads.or_insert(arg)?; let zeros = arg.zeros_like()?; let positive_mask = arg.gt(&zeros)?.to_dtype(arg.dtype())?; let negative_mask = arg.le(&zeros)?.to_dtype(arg.dtype())?; // node == alpha * (e^x - 1) for x <= 0, reuse it let negative_exp_mask = (negative_mask * (*node + *alpha))?; let combined_mask = (positive_mask + negative_exp_mask)?; *sum_grad = sum_grad.add(&(grad * combined_mask)?)? } Op::Powf(arg, e) => { let arg_grad = (&(grad * arg.powf(e - 1.)?)? * *e)?; let sum_grad = grads.or_insert(arg)?; *sum_grad = sum_grad.add(&arg_grad)? } Op::CustomOp1(arg, c) => { if let Some(arg_grad) = c.bwd(arg, node, &grad)? { let sum_grad = grads.or_insert(arg)?; *sum_grad = sum_grad.add(&arg_grad)? } } Op::CustomOp2(arg1, arg2, c) => { let (arg_grad1, arg_grad2) = c.bwd(arg1, arg2, node, &grad)?; if let Some(arg_grad1) = arg_grad1 { let sum_grad = grads.or_insert(arg1)?; *sum_grad = sum_grad.add(&arg_grad1)? } if let Some(arg_grad2) = arg_grad2 { let sum_grad = grads.or_insert(arg2)?; *sum_grad = sum_grad.add(&arg_grad2)? } } Op::CustomOp3(arg1, arg2, arg3, c) => { let (arg_grad1, arg_grad2, arg_grad3) = c.bwd(arg1, arg2, arg3, node, &grad)?; if let Some(arg_grad1) = arg_grad1 { let sum_grad = grads.or_insert(arg1)?; *sum_grad = sum_grad.add(&arg_grad1)? } if let Some(arg_grad2) = arg_grad2 { let sum_grad = grads.or_insert(arg2)?; *sum_grad = sum_grad.add(&arg_grad2)? } if let Some(arg_grad3) = arg_grad3 { let sum_grad = grads.or_insert(arg3)?; *sum_grad = sum_grad.add(&arg_grad3)? } } Op::Unary(arg, UnaryOp::Sqr) => { let arg_grad = arg.mul(&grad)?.affine(2., 0.)?; let sum_grad = grads.or_insert(arg)?; *sum_grad = sum_grad.add(&arg_grad)? } Op::Unary(arg, UnaryOp::Sqrt) => { let arg_grad = grad.div(node)?.affine(0.5, 0.)?; let sum_grad = grads.or_insert(arg)?; *sum_grad = sum_grad.add(&arg_grad)? } Op::ToDevice(arg) => { let sum_grad = grads.or_insert(arg)?; let arg_grad = grad.to_device(sum_grad.device())?; *sum_grad = sum_grad.add(&arg_grad)? } Op::Transpose(arg, dim1, dim2) => { let arg_grad = grad.transpose(*dim1, *dim2)?; let sum_grad = grads.or_insert(arg)?; *sum_grad = sum_grad.add(&arg_grad)? } Op::Permute(arg, dims) => { let mut inv_dims = vec![0; dims.len()]; for (i, &dim_idx) in dims.iter().enumerate() { inv_dims[dim_idx] = i } let arg_grad = grad.permute(inv_dims)?; let sum_grad = grads.or_insert(arg)?; *sum_grad = sum_grad.add(&arg_grad)? } }; } } Ok(grads) } } /// A store for gradients, associating a tensor id to the corresponding gradient tensor, used for back propagation. #[derive(Debug)] pub struct GradStore(HashMap<TensorId, Tensor>); impl GradStore { /// Create a new gradient store fn new() -> Self { GradStore(HashMap::new()) } /// Get the gradient tensor corresponding to the given tensor id pub fn get_id(&self, id: TensorId) -> Option<&Tensor> { self.0.get(&id) } /// Get the gradient tensor associated with the given tensor pub fn get(&self, tensor: &Tensor) -> Option<&Tensor> { self.0.get(&tensor.id()) } /// Remove the gradient tensor associated with the given tensor, returning it if it exists pub fn remove(&mut self, tensor: &Tensor) -> Option<Tensor> { self.0.remove(&tensor.id()) } /// Insert a gradient tensor associated with the given tensor, returning the previous gradient tensor if it existed pub fn insert(&mut self, tensor: &Tensor, grad: Tensor) -> Option<Tensor> { self.0.insert(tensor.id(), grad) } /// Get the gradient tensor associated with the given tensor, or, if it does not exist, /// insert a tensor of zeroes, with the same shape and type as the given tensors and return it fn or_insert(&mut self, tensor: &Tensor) -> Result<&mut Tensor> { use std::collections::hash_map::Entry; let grad = match self.0.entry(tensor.id()) { Entry::Occupied(entry) => entry.into_mut(), Entry::Vacant(entry) => { let grad = tensor.zeros_like()?; entry.insert(grad) } }; Ok(grad) } /// Get the tensor ids of the stored gradient tensors pub fn get_ids(&self) -> impl Iterator<Item = &TensorId> { self.0.keys() } }
candle/candle-core/src/backprop.rs/0
{ "file_path": "candle/candle-core/src/backprop.rs", "repo_id": "candle", "token_count": 24753 }
26
use crate::op::{BackpropOp, Op}; use crate::tensor::from_storage; use crate::{CpuStorage, CudaStorage, Layout, MetalStorage, Result, Shape, Tensor}; use std::sync::Arc; /// Unary ops that can be defined in user-land. pub trait CustomOp1 { // Box<dyn> does not support const yet, so use a function to get the name. fn name(&self) -> &'static str; /// The forward pass, as run on a cpu device. Note that the storage can use arbitrary strides, /// offsets etc so the associated layout should be used to access it. fn cpu_fwd(&self, storage: &CpuStorage, layout: &Layout) -> Result<(CpuStorage, Shape)>; /// The forward pass, as run on a gpu device. Note that the storage can use arbitrary strides, /// offsets etc so the associated layout should be used to access it. fn cuda_fwd(&self, _storage: &CudaStorage, _layout: &Layout) -> Result<(CudaStorage, Shape)> { Err(crate::Error::Cuda( format!("no cuda implementation for {}", self.name()).into(), )) } /// The forward pass, as run on a metal gpu device. Note that the storage can use arbitrary strides, /// offsets etc so the associated layout should be used to access it. fn metal_fwd( &self, _storage: &MetalStorage, _layout: &Layout, ) -> Result<(MetalStorage, Shape)> { Err(crate::Error::Metal( format!("no metal implementation for {}", self.name()).into(), )) } /// This function takes as argument the argument `arg` used in the forward pass, the result /// produced by the forward operation `res` and the gradient of the result `grad_res`. /// The function should return the gradient of the argument. fn bwd(&self, _arg: &Tensor, _res: &Tensor, _grad_res: &Tensor) -> Result<Option<Tensor>> { Err(crate::Error::BackwardNotSupported { op: self.name() }) } } pub trait CustomOp2 { fn name(&self) -> &'static str; /// The forward pass, as run on a cpu device. Note that the storage can use arbitrary strides, /// offsets etc so the associated layout should be used to access it. fn cpu_fwd( &self, s1: &CpuStorage, l1: &Layout, s2: &CpuStorage, l2: &Layout, ) -> Result<(CpuStorage, Shape)>; /// The forward pass, as run on a gpu device. Note that the storage can use arbitrary strides, /// offsets etc so the associated layout should be used to access it. fn cuda_fwd( &self, _: &CudaStorage, _: &Layout, _: &CudaStorage, _: &Layout, ) -> Result<(CudaStorage, Shape)> { Err(crate::Error::Cuda( format!("no cuda implementation for {}", self.name()).into(), )) } /// The forward pass, as run on a metal gpu device. Note that the storage can use arbitrary strides, /// offsets etc so the associated layout should be used to access it. fn metal_fwd( &self, _: &MetalStorage, _: &Layout, _: &MetalStorage, _: &Layout, ) -> Result<(MetalStorage, Shape)> { Err(crate::Error::Metal( format!("no metal implementation for {}", self.name()).into(), )) } fn bwd( &self, _arg1: &Tensor, _arg2: &Tensor, _res: &Tensor, _grad_res: &Tensor, ) -> Result<(Option<Tensor>, Option<Tensor>)> { Err(crate::Error::BackwardNotSupported { op: self.name() }) } } pub trait CustomOp3 { fn name(&self) -> &'static str; /// The forward pass, as run on a cpu device. Note that the storage can use arbitrary strides, /// offsets etc so the associated layout should be used to access it. fn cpu_fwd( &self, s1: &CpuStorage, l1: &Layout, s2: &CpuStorage, l2: &Layout, s3: &CpuStorage, l3: &Layout, ) -> Result<(CpuStorage, Shape)>; /// The forward pass, as run on a gpu device. Note that the storage can use arbitrary strides, /// offsets etc so the associated layout should be used to access it. fn cuda_fwd( &self, _: &CudaStorage, _: &Layout, _: &CudaStorage, _: &Layout, _: &CudaStorage, _: &Layout, ) -> Result<(CudaStorage, Shape)> { Err(crate::Error::Cuda( format!("no cuda implementation for {}", self.name()).into(), )) } /// The forward pass, as run on a metal gpu device. Note that the storage can use arbitrary strides, /// offsets etc so the associated layout should be used to access it. fn metal_fwd( &self, _: &MetalStorage, _: &Layout, _: &MetalStorage, _: &Layout, _: &MetalStorage, _: &Layout, ) -> Result<(MetalStorage, Shape)> { Err(crate::Error::Metal( format!("no metal implementation for {}", self.name()).into(), )) } fn bwd( &self, _arg1: &Tensor, _arg2: &Tensor, _arg3: &Tensor, _res: &Tensor, _grad_res: &Tensor, ) -> Result<(Option<Tensor>, Option<Tensor>, Option<Tensor>)> { Err(crate::Error::BackwardNotSupported { op: self.name() }) } } impl Tensor { /// Applies a unary custom op without backward support pub fn apply_op1_no_bwd<C: CustomOp1>(&self, c: &C) -> Result<Self> { let (storage, shape) = self.storage().apply_op1(self.layout(), c)?; Ok(from_storage(storage, shape, BackpropOp::none(), false)) } /// Applies a binary custom op without backward support pub fn apply_op2_no_bwd<C: CustomOp2>(&self, rhs: &Self, c: &C) -> Result<Self> { let (storage, shape) = self.storage() .apply_op2(self.layout(), &rhs.storage(), rhs.layout(), c)?; Ok(from_storage(storage, shape, BackpropOp::none(), false)) } /// Applies a ternary custom op without backward support pub fn apply_op3_no_bwd<C: CustomOp3>(&self, t2: &Self, t3: &Self, c: &C) -> Result<Self> { let (storage, shape) = self.storage().apply_op3( self.layout(), &t2.storage(), t2.layout(), &t3.storage(), t3.layout(), c, )?; Ok(from_storage(storage, shape, BackpropOp::none(), false)) } /// Applies a unary custom op. pub fn apply_op1_arc(&self, c: Arc<Box<dyn CustomOp1 + Send + Sync>>) -> Result<Self> { let (storage, shape) = self .storage() .apply_op1(self.layout(), c.as_ref().as_ref())?; let op = BackpropOp::new1(self, |s| Op::CustomOp1(s, c.clone())); Ok(from_storage(storage, shape, op, false)) } pub fn apply_op1<C: 'static + CustomOp1 + Send + Sync>(&self, c: C) -> Result<Self> { self.apply_op1_arc(Arc::new(Box::new(c))) } /// Applies a binary custom op. pub fn apply_op2_arc( &self, rhs: &Self, c: Arc<Box<dyn CustomOp2 + Send + Sync>>, ) -> Result<Self> { let (storage, shape) = self.storage().apply_op2( self.layout(), &rhs.storage(), rhs.layout(), c.as_ref().as_ref(), )?; let op = BackpropOp::new2(self, rhs, |t1, t2| Op::CustomOp2(t1, t2, c.clone())); Ok(from_storage(storage, shape, op, false)) } pub fn apply_op2<C: 'static + CustomOp2 + Send + Sync>(&self, r: &Self, c: C) -> Result<Self> { self.apply_op2_arc(r, Arc::new(Box::new(c))) } /// Applies a ternary custom op. pub fn apply_op3_arc( &self, t2: &Self, t3: &Self, c: Arc<Box<dyn CustomOp3 + Send + Sync>>, ) -> Result<Self> { let (storage, shape) = self.storage().apply_op3( self.layout(), &t2.storage(), t2.layout(), &t3.storage(), t3.layout(), c.as_ref().as_ref(), )?; let op = BackpropOp::new3(self, t2, t3, |t1, t2, t3| { Op::CustomOp3(t1, t2, t3, c.clone()) }); Ok(from_storage(storage, shape, op, false)) } pub fn apply_op3<C: 'static + CustomOp3 + Send + Sync>( &self, t2: &Self, t3: &Self, c: C, ) -> Result<Self> { self.apply_op3_arc(t2, t3, Arc::new(Box::new(c))) } } // In place ops. /// Unary ops that can be defined in user-land. /// These ops work in place and as such back-prop is unsupported. pub trait InplaceOp1 { // Box<dyn> does not support const yet, so use a function to get the name. fn name(&self) -> &'static str; /// The forward pass, as run on a cpu device. Note that the storage can use arbitrary strides, /// offsets etc so the associated layout should be used to access it. fn cpu_fwd(&self, storage: &mut CpuStorage, layout: &Layout) -> Result<()>; /// The forward pass, as run on a gpu device. Note that the storage can use arbitrary strides, /// offsets etc so the associated layout should be used to access it. fn cuda_fwd(&self, _storage: &mut CudaStorage, _layout: &Layout) -> Result<()> { Err(crate::Error::Cuda( format!("no cuda implementation for {}", self.name()).into(), )) } /// The forward pass, as run on a metal gpu device. Note that the storage can use arbitrary strides, /// offsets etc so the associated layout should be used to access it. fn metal_fwd(&self, _storage: &mut MetalStorage, _layout: &Layout) -> Result<()> { Err(crate::Error::Metal( format!("no metal implementation for {}", self.name()).into(), )) } } pub trait InplaceOp2 { fn name(&self) -> &'static str; /// The forward pass, as run on a cpu device. Note that the storage can use arbitrary strides, /// offsets etc so the associated layout should be used to access it. fn cpu_fwd(&self, s1: &mut CpuStorage, l1: &Layout, s2: &CpuStorage, l2: &Layout) -> Result<()>; /// The forward pass, as run on a gpu device. Note that the storage can use arbitrary strides, /// offsets etc so the associated layout should be used to access it. fn cuda_fwd(&self, _: &mut CudaStorage, _: &Layout, _: &CudaStorage, _: &Layout) -> Result<()> { Err(crate::Error::Cuda( format!("no cuda implementation for {}", self.name()).into(), )) } /// The forward pass, as run on a metal gpu device. Note that the storage can use arbitrary strides, /// offsets etc so the associated layout should be used to access it. fn metal_fwd( &self, _: &mut MetalStorage, _: &Layout, _: &MetalStorage, _: &Layout, ) -> Result<()> { Err(crate::Error::Metal( format!("no metal implementation for {}", self.name()).into(), )) } } pub trait InplaceOp3 { fn name(&self) -> &'static str; /// The forward pass, as run on a cpu device. Note that the storage can use arbitrary strides, /// offsets etc so the associated layout should be used to access it. fn cpu_fwd( &self, s1: &mut CpuStorage, l1: &Layout, s2: &CpuStorage, l2: &Layout, s3: &CpuStorage, l3: &Layout, ) -> Result<()>; /// The forward pass, as run on a gpu device. Note that the storage can use arbitrary strides, /// offsets etc so the associated layout should be used to access it. fn cuda_fwd( &self, _: &mut CudaStorage, _: &Layout, _: &CudaStorage, _: &Layout, _: &CudaStorage, _: &Layout, ) -> Result<()> { Err(crate::Error::Cuda( format!("no cuda implementation for {}", self.name()).into(), )) } /// The forward pass, as run on a metal gpu device. Note that the storage can use arbitrary strides, /// offsets etc so the associated layout should be used to access it. fn metal_fwd( &self, _: &mut MetalStorage, _: &Layout, _: &MetalStorage, _: &Layout, _: &MetalStorage, _: &Layout, ) -> Result<()> { Err(crate::Error::Metal( format!("no metal implementation for {}", self.name()).into(), )) } } impl Tensor { /// Applies a unary custom op in place. pub fn inplace_op1<C: InplaceOp1>(&self, c: &C) -> Result<()> { self.storage_mut().inplace_op1(self.layout(), c) } /// Applies a unary custom op in place (for the first tensor). pub fn inplace_op2<C: InplaceOp2>(&self, rhs: &Self, c: &C) -> Result<()> { self.storage_mut() .inplace_op2(self.layout(), &rhs.storage(), rhs.layout(), c) } /// Applies a ternary custom op in place (for the first tensor). pub fn inplace_op3<C: InplaceOp3>(&self, t2: &Self, t3: &Self, c: &C) -> Result<()> { self.storage_mut().inplace_op3( self.layout(), &t2.storage(), t2.layout(), &t3.storage(), t3.layout(), c, ) } } pub struct UgIOp1 { name: &'static str, #[cfg(feature = "cuda")] func: cudarc::driver::CudaFunction, #[cfg(feature = "metal")] func: metal::ComputePipelineState, } impl UgIOp1 { #[allow(unused)] #[cfg(not(target_arch = "wasm32"))] pub fn new( name: &'static str, kernel: ug::lang::ssa::Kernel, device: &crate::Device, ) -> Result<Self> { #[cfg(feature = "cuda")] { let device = device.as_cuda_device()?; let func = device.compile(name, kernel)?; Ok(Self { name, func: func.into_cuda_function(), }) } #[cfg(feature = "metal")] { let device = device.as_metal_device()?; let func = device.compile(name, kernel)?; Ok(Self { name, func }) } #[cfg(not(any(feature = "cuda", feature = "metal")))] { Ok(Self { name }) } } } impl InplaceOp1 for UgIOp1 { fn name(&self) -> &'static str { self.name } fn cpu_fwd(&self, _: &mut CpuStorage, _: &Layout) -> Result<()> { crate::bail!("ug ops are only supported on metal/cuda at the moment") } #[cfg(feature = "metal")] fn metal_fwd(&self, sto: &mut MetalStorage, layout: &Layout) -> Result<()> { use crate::backend::BackendStorage; use candle_metal_kernels::utils::EncoderProvider; let elem_count = layout.shape().elem_count(); if sto.dtype() != crate::DType::F32 { // TODO: support more dtypes. crate::bail!("input is not a f32 tensor") } let device = sto.device(); println!("here"); let command_buffer = device.command_buffer()?; let command_buffer = &command_buffer; let encoder = command_buffer.encoder(); let encoder = encoder.as_ref(); encoder.set_compute_pipeline_state(&self.func); let (g, b) = if elem_count % 32 == 0 { (elem_count / 32, 32) } else { (elem_count, 1) }; let grid_dims = metal::MTLSize { width: g as u64, height: 1, depth: 1, }; let group_dims = candle_metal_kernels::utils::get_block_dims(b as u64, 1, 1); candle_metal_kernels::utils::set_param(encoder, 0, (sto.buffer(), 0usize)); encoder.use_resource(sto.buffer(), metal::MTLResourceUsage::Write); encoder.dispatch_threads(grid_dims, group_dims); Ok(()) } #[cfg(feature = "cuda")] fn cuda_fwd(&self, sto: &mut CudaStorage, layout: &Layout) -> Result<()> { use crate::cuda_backend::WrapErr; use cudarc::driver::PushKernelArg; let elem_count = layout.shape().elem_count(); let stream = sto.device.cuda_stream(); // TODO: support more dtypes. let sto = sto.as_cuda_slice::<f32>()?; let sto = match layout.contiguous_offsets() { None => crate::bail!("input has to be contiguous"), Some((o1, o2)) => sto.slice(o1..o2), }; let (g, b) = if elem_count % 32 == 0 { (elem_count / 32, 32) } else { (elem_count, 1) }; let cfg = cudarc::driver::LaunchConfig { grid_dim: (g as u32, 1, 1), block_dim: (b as u32, 1, 1), shared_mem_bytes: 0, }; let mut builder = stream.launch_builder(&self.func); builder.arg(&sto); unsafe { builder.launch(cfg) }.w()?; Ok(()) } }
candle/candle-core/src/custom_op.rs/0
{ "file_path": "candle/candle-core/src/custom_op.rs", "repo_id": "candle", "token_count": 7461 }
27
use super::k_quants::{ BlockQ2K, BlockQ3K, BlockQ4K, BlockQ4_0, BlockQ5K, BlockQ6K, BlockQ8K, BlockQ8_0, QK8_0, QK_K, }; use crate::Result; use byteorder::{ByteOrder, LittleEndian}; use half::f16; #[cfg(target_arch = "x86")] use core::arch::x86::*; #[cfg(target_arch = "x86_64")] use core::arch::x86_64::*; #[inline(always)] pub(crate) unsafe fn sum_i16_pairs_float(x: __m256i) -> __m256 { let ones = _mm256_set1_epi16(1); let summed_pairs = _mm256_madd_epi16(ones, x); _mm256_cvtepi32_ps(summed_pairs) } #[inline(always)] pub(crate) unsafe fn mul_sum_us8_pairs_float(ax: __m256i, sy: __m256i) -> __m256 { let dot = _mm256_maddubs_epi16(ax, sy); sum_i16_pairs_float(dot) } #[inline(always)] pub(crate) unsafe fn hsum_float_8(x: __m256) -> f32 { let res = _mm256_extractf128_ps(x, 1); let res = _mm_add_ps(res, _mm256_castps256_ps128(x)); let res = _mm_add_ps(res, _mm_movehl_ps(res, res)); let res = _mm_add_ss(res, _mm_movehdup_ps(res)); _mm_cvtss_f32(res) } #[inline(always)] pub(crate) unsafe fn bytes_from_nibbles_32(rsi: *const u8) -> __m256i { let tmp = _mm_loadu_si128(rsi as *const __m128i); let bytes = _mm256_insertf128_si256::<1>(_mm256_castsi128_si256(tmp), _mm_srli_epi16(tmp, 4)); let low_mask = _mm256_set1_epi8(0xF); _mm256_and_si256(low_mask, bytes) } #[inline(always)] pub(crate) unsafe fn mul_sum_i8_pairs_float(x: __m256i, y: __m256i) -> __m256 { let ax = _mm256_sign_epi8(x, x); let sy = _mm256_sign_epi8(y, x); mul_sum_us8_pairs_float(ax, sy) } #[inline(always)] pub(crate) fn vec_dot_q4_0_q8_0(n: usize, xs: &[BlockQ4_0], ys: &[BlockQ8_0]) -> Result<f32> { let qk = QK8_0; if n % QK8_0 != 0 { crate::bail!("vec_dot_q4_0_q8_0: {n} is not divisible by {qk}") } unsafe { let mut acc = _mm256_setzero_ps(); for (x, y) in xs.iter().zip(ys.iter()) { let d = _mm256_set1_ps(f16::to_f32(x.d) * f16::to_f32(y.d)); let bx = bytes_from_nibbles_32(x.qs.as_ptr()); let off = _mm256_set1_epi8(8); let bx = _mm256_sub_epi8(bx, off); let by = _mm256_loadu_si256(y.qs.as_ptr() as *const __m256i); let q = mul_sum_i8_pairs_float(bx, by); acc = _mm256_fmadd_ps(d, q, acc); } Ok(hsum_float_8(acc)) } } #[inline(always)] pub(crate) fn vec_dot_q8_0_q8_0(n: usize, xs: &[BlockQ8_0], ys: &[BlockQ8_0]) -> Result<f32> { let qk = QK8_0; if n % QK8_0 != 0 { crate::bail!("vec_dot_q8_0_q8_0: {n} is not divisible by {qk}") } unsafe { let mut acc = _mm256_setzero_ps(); for (x, y) in xs.iter().zip(ys.iter()) { let d = _mm256_set1_ps(f16::to_f32(x.d) * f16::to_f32(y.d)); let bx = _mm256_loadu_si256(x.qs.as_ptr() as *const __m256i); let by = _mm256_loadu_si256(y.qs.as_ptr() as *const __m256i); let q = mul_sum_i8_pairs_float(bx, by); acc = _mm256_fmadd_ps(d, q, acc); } Ok(hsum_float_8(acc)) } } #[inline(always)] unsafe fn get_scale_shuffle(i: usize) -> __m128i { const K_SHUFFLE: [u8; 128] = [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, ]; _mm_loadu_si128((K_SHUFFLE.as_ptr() as *const __m128i).add(i)) } #[inline(always)] unsafe fn get_scale_shuffle_k4(i: usize) -> __m256i { const K_SHUFFLE: [u8; 256] = [ 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 10, 11, 10, 11, 10, 11, 10, 11, 10, 11, 10, 11, 10, 11, 10, 11, 10, 11, 10, 11, 10, 11, 10, 11, 10, 11, 10, 11, 10, 11, 10, 11, 12, 13, 12, 13, 12, 13, 12, 13, 12, 13, 12, 13, 12, 13, 12, 13, 12, 13, 12, 13, 12, 13, 12, 13, 12, 13, 12, 13, 12, 13, 12, 13, 14, 15, 14, 15, 14, 15, 14, 15, 14, 15, 14, 15, 14, 15, 14, 15, 14, 15, 14, 15, 14, 15, 14, 15, 14, 15, 14, 15, 14, 15, 14, 15, ]; _mm256_loadu_si256((K_SHUFFLE.as_ptr() as *const __m256i).add(i)) } #[inline(always)] unsafe fn get_scale_shuffle_q3k(i: usize) -> __m256i { const K_SHUFFLE: [u8; 128] = [ 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 10, 11, 10, 11, 10, 11, 10, 11, 10, 11, 10, 11, 10, 11, 10, 11, 12, 13, 12, 13, 12, 13, 12, 13, 12, 13, 12, 13, 12, 13, 12, 13, 14, 15, 14, 15, 14, 15, 14, 15, 14, 15, 14, 15, 14, 15, 14, 15, ]; _mm256_loadu_si256((K_SHUFFLE.as_ptr() as *const __m256i).add(i)) } #[inline(always)] pub(crate) fn vec_dot_q6k_q8k(n: usize, xs: &[BlockQ6K], ys: &[BlockQ8K]) -> Result<f32> { let qk = QK_K; if n % qk != 0 { crate::bail!("vec_dot_q6k_8k: {n} is not divisible by {qk}") } unsafe { let m4 = _mm256_set1_epi8(0xF); let m2 = _mm256_set1_epi8(3); let m32s = _mm256_set1_epi8(32); let mut acc = _mm256_setzero_ps(); for (x, y) in xs.iter().zip(ys.iter()) { let d = y.d * x.d.to_f32(); let mut q4 = x.ql.as_ptr(); let mut qh = x.qh.as_ptr(); let mut q8 = y.qs.as_ptr(); let scales = _mm_loadu_si128(x.scales.as_ptr() as *const __m128i); let mut sumi = _mm256_setzero_si256(); for j in 0..QK_K / 128 { let is = j * 4; let scale_0 = _mm_shuffle_epi8(scales, get_scale_shuffle(is)); let scale_1 = _mm_shuffle_epi8(scales, get_scale_shuffle(is + 1)); let scale_2 = _mm_shuffle_epi8(scales, get_scale_shuffle(is + 2)); let scale_3 = _mm_shuffle_epi8(scales, get_scale_shuffle(is + 3)); let q4bits1 = _mm256_loadu_si256(q4 as *const __m256i); q4 = q4.add(32); let q4bits2 = _mm256_loadu_si256(q4 as *const __m256i); q4 = q4.add(32); let q4bits_h = _mm256_loadu_si256(qh as *const __m256i); qh = qh.add(32); let q4h_0 = _mm256_slli_epi16(_mm256_and_si256(q4bits_h, m2), 4); let q4h_1 = _mm256_slli_epi16(_mm256_and_si256(_mm256_srli_epi16(q4bits_h, 2), m2), 4); let q4h_2 = _mm256_slli_epi16(_mm256_and_si256(_mm256_srli_epi16(q4bits_h, 4), m2), 4); let q4h_3 = _mm256_slli_epi16(_mm256_and_si256(_mm256_srli_epi16(q4bits_h, 6), m2), 4); let q4_0 = _mm256_or_si256(_mm256_and_si256(q4bits1, m4), q4h_0); let q4_1 = _mm256_or_si256(_mm256_and_si256(q4bits2, m4), q4h_1); let q4_2 = _mm256_or_si256(_mm256_and_si256(_mm256_srli_epi16(q4bits1, 4), m4), q4h_2); let q4_3 = _mm256_or_si256(_mm256_and_si256(_mm256_srli_epi16(q4bits2, 4), m4), q4h_3); let q8_0 = _mm256_loadu_si256(q8 as *const __m256i); q8 = q8.add(32); let q8_1 = _mm256_loadu_si256(q8 as *const __m256i); q8 = q8.add(32); let q8_2 = _mm256_loadu_si256(q8 as *const __m256i); q8 = q8.add(32); let q8_3 = _mm256_loadu_si256(q8 as *const __m256i); q8 = q8.add(32); let q8s_0 = _mm256_maddubs_epi16(m32s, q8_0); let q8s_1 = _mm256_maddubs_epi16(m32s, q8_1); let q8s_2 = _mm256_maddubs_epi16(m32s, q8_2); let q8s_3 = _mm256_maddubs_epi16(m32s, q8_3); let p16_0 = _mm256_maddubs_epi16(q4_0, q8_0); let p16_1 = _mm256_maddubs_epi16(q4_1, q8_1); let p16_2 = _mm256_maddubs_epi16(q4_2, q8_2); let p16_3 = _mm256_maddubs_epi16(q4_3, q8_3); let p16_0 = _mm256_sub_epi16(p16_0, q8s_0); let p16_1 = _mm256_sub_epi16(p16_1, q8s_1); let p16_2 = _mm256_sub_epi16(p16_2, q8s_2); let p16_3 = _mm256_sub_epi16(p16_3, q8s_3); let p16_0 = _mm256_madd_epi16(_mm256_cvtepi8_epi16(scale_0), p16_0); let p16_1 = _mm256_madd_epi16(_mm256_cvtepi8_epi16(scale_1), p16_1); let p16_2 = _mm256_madd_epi16(_mm256_cvtepi8_epi16(scale_2), p16_2); let p16_3 = _mm256_madd_epi16(_mm256_cvtepi8_epi16(scale_3), p16_3); sumi = _mm256_add_epi32(sumi, _mm256_add_epi32(p16_0, p16_1)); sumi = _mm256_add_epi32(sumi, _mm256_add_epi32(p16_2, p16_3)); } acc = _mm256_fmadd_ps(_mm256_broadcast_ss(&d), _mm256_cvtepi32_ps(sumi), acc); } Ok(hsum_float_8(acc)) } } #[inline(always)] unsafe fn mm256_set_m128i(a: __m128i, b: __m128i) -> __m256i { _mm256_insertf128_si256(_mm256_castsi128_si256(b), a, 1) } #[inline(always)] pub(crate) fn vec_dot_q2k_q8k(n: usize, xs: &[BlockQ2K], ys: &[BlockQ8K]) -> Result<f32> { if n % QK_K != 0 { crate::bail!("vec_dot_q2k_q8k: {n} is not divisible by {QK_K}") } unsafe { let m3 = _mm256_set1_epi8(3); let m4 = _mm_set1_epi8(0xF); let mut acc = _mm256_setzero_ps(); for (x, y) in xs.iter().zip(ys.iter()) { let d = y.d * x.d.to_f32(); let dmin = -y.d * x.dmin.to_f32(); let mut q2 = x.qs.as_ptr(); let mut q8 = y.qs.as_ptr(); let mins_and_scales = _mm_loadu_si128(x.scales.as_ptr() as *const __m128i); let scales8 = _mm_and_si128(mins_and_scales, m4); let mins8 = _mm_and_si128(_mm_srli_epi16(mins_and_scales, 4), m4); let mins = _mm256_cvtepi8_epi16(mins8); let prod = _mm256_madd_epi16(mins, _mm256_loadu_si256(y.bsums.as_ptr() as *const __m256i)); acc = _mm256_fmadd_ps(_mm256_broadcast_ss(&dmin), _mm256_cvtepi32_ps(prod), acc); let all_scales = _mm256_cvtepi8_epi16(scales8); let l_scales = _mm256_extracti128_si256(all_scales, 0); let h_scales = _mm256_extracti128_si256(all_scales, 1); let scales = [ mm256_set_m128i(l_scales, l_scales), mm256_set_m128i(h_scales, h_scales), ]; let mut sumi = _mm256_setzero_si256(); for scale in scales { let q2bits = _mm256_loadu_si256(q2 as *const __m256i); q2 = q2.add(32); let q8_0 = _mm256_loadu_si256(q8 as *const __m256i); q8 = q8.add(32); let q8_1 = _mm256_loadu_si256(q8 as *const __m256i); q8 = q8.add(32); let q8_2 = _mm256_loadu_si256(q8 as *const __m256i); q8 = q8.add(32); let q8_3 = _mm256_loadu_si256(q8 as *const __m256i); q8 = q8.add(32); let q2_0 = _mm256_and_si256(q2bits, m3); let q2_1 = _mm256_and_si256(_mm256_srli_epi16(q2bits, 2), m3); let q2_2 = _mm256_and_si256(_mm256_srli_epi16(q2bits, 4), m3); let q2_3 = _mm256_and_si256(_mm256_srli_epi16(q2bits, 6), m3); let p0 = _mm256_maddubs_epi16(q2_0, q8_0); let p1 = _mm256_maddubs_epi16(q2_1, q8_1); let p2 = _mm256_maddubs_epi16(q2_2, q8_2); let p3 = _mm256_maddubs_epi16(q2_3, q8_3); let p0 = _mm256_madd_epi16(_mm256_shuffle_epi8(scale, get_scale_shuffle_q3k(0)), p0); let p1 = _mm256_madd_epi16(_mm256_shuffle_epi8(scale, get_scale_shuffle_q3k(1)), p1); let p2 = _mm256_madd_epi16(_mm256_shuffle_epi8(scale, get_scale_shuffle_q3k(2)), p2); let p3 = _mm256_madd_epi16(_mm256_shuffle_epi8(scale, get_scale_shuffle_q3k(3)), p3); let p0 = _mm256_add_epi32(p0, p1); let p2 = _mm256_add_epi32(p2, p3); sumi = _mm256_add_epi32(sumi, _mm256_add_epi32(p0, p2)); } acc = _mm256_fmadd_ps(_mm256_broadcast_ss(&d), _mm256_cvtepi32_ps(sumi), acc); } Ok(hsum_float_8(acc)) } } #[inline(always)] pub(crate) fn vec_dot_q3k_q8k(n: usize, xs: &[BlockQ3K], ys: &[BlockQ8K]) -> Result<f32> { if n % QK_K != 0 { crate::bail!("vec_dot_q3k_q8k: {n} is not divisible by {QK_K}") } const KMASK1: u32 = 0x03030303; const KMASK2: u32 = 0x0f0f0f0f; let mut aux = [0u32; 3]; unsafe { let m3 = _mm256_set1_epi8(3); let mone = _mm256_set1_epi8(1); let m32 = _mm_set1_epi8(32); let mut acc = _mm256_setzero_ps(); for (x, y) in xs.iter().zip(ys.iter()) { let d = y.d * x.d.to_f32(); let mut q3 = x.qs.as_ptr(); let mut q8 = y.qs.as_ptr(); LittleEndian::read_u32_into(&x.scales, &mut aux); let scales128 = _mm_set_epi32( (((aux[1] >> 4) & KMASK2) | (((aux[2] >> 6) & KMASK1) << 4)) as i32, (((aux[0] >> 4) & KMASK2) | (((aux[2] >> 4) & KMASK1) << 4)) as i32, ((aux[1] & KMASK2) | (((aux[2] >> 2) & KMASK1) << 4)) as i32, ((aux[0] & KMASK2) | (((aux[2]) & KMASK1) << 4)) as i32, ); let scales128 = _mm_sub_epi8(scales128, m32); let all_scales = _mm256_cvtepi8_epi16(scales128); let l_scales = _mm256_extracti128_si256(all_scales, 0); let h_scales = _mm256_extracti128_si256(all_scales, 1); let scales = [ mm256_set_m128i(l_scales, l_scales), mm256_set_m128i(h_scales, h_scales), ]; // high bit let hbits = _mm256_loadu_si256(x.hmask.as_ptr() as *const __m256i); let mut sumi = _mm256_setzero_si256(); for (j, scale) in scales.iter().enumerate() { // load low 2 bits let q3bits = _mm256_loadu_si256(q3 as *const __m256i); q3 = q3.add(32); // Prepare low and high bits // We hardcode the shifts here to avoid loading them into a separate register let q3l_0 = _mm256_and_si256(q3bits, m3); let q3h_0 = if j == 0 { _mm256_srli_epi16(_mm256_andnot_si256(hbits, _mm256_slli_epi16(mone, 0)), 0) } else { _mm256_srli_epi16(_mm256_andnot_si256(hbits, _mm256_slli_epi16(mone, 4)), 4) }; let q3h_0 = _mm256_slli_epi16(q3h_0, 2); let q3l_1 = _mm256_and_si256(_mm256_srli_epi16(q3bits, 2), m3); let q3h_1 = if j == 0 { _mm256_srli_epi16(_mm256_andnot_si256(hbits, _mm256_slli_epi16(mone, 1)), 1) } else { _mm256_srli_epi16(_mm256_andnot_si256(hbits, _mm256_slli_epi16(mone, 5)), 5) }; let q3h_1 = _mm256_slli_epi16(q3h_1, 2); let q3l_2 = _mm256_and_si256(_mm256_srli_epi16(q3bits, 4), m3); let q3h_2 = if j == 0 { _mm256_srli_epi16(_mm256_andnot_si256(hbits, _mm256_slli_epi16(mone, 2)), 2) } else { _mm256_srli_epi16(_mm256_andnot_si256(hbits, _mm256_slli_epi16(mone, 6)), 6) }; let q3h_2 = _mm256_slli_epi16(q3h_2, 2); let q3l_3 = _mm256_and_si256(_mm256_srli_epi16(q3bits, 6), m3); let q3h_3 = if j == 0 { _mm256_srli_epi16(_mm256_andnot_si256(hbits, _mm256_slli_epi16(mone, 3)), 3) } else { _mm256_srli_epi16(_mm256_andnot_si256(hbits, _mm256_slli_epi16(mone, 7)), 7) }; let q3h_3 = _mm256_slli_epi16(q3h_3, 2); // load Q8 quants let q8_0 = _mm256_loadu_si256(q8 as *const __m256i); q8 = q8.add(32); let q8_1 = _mm256_loadu_si256(q8 as *const __m256i); q8 = q8.add(32); let q8_2 = _mm256_loadu_si256(q8 as *const __m256i); q8 = q8.add(32); let q8_3 = _mm256_loadu_si256(q8 as *const __m256i); q8 = q8.add(32); // Dot product: we multiply the 2 low bits and 1 high bit part separately, so we // can use _mm256_maddubs_epi16, and then subtract. The high bit part has the 2 // already subtracted (and so, it is zero if the high bit was not set, and 2 if the // high bit was set) let q8s_0 = _mm256_maddubs_epi16(q3h_0, q8_0); let q8s_1 = _mm256_maddubs_epi16(q3h_1, q8_1); let q8s_2 = _mm256_maddubs_epi16(q3h_2, q8_2); let q8s_3 = _mm256_maddubs_epi16(q3h_3, q8_3); let p16_0 = _mm256_maddubs_epi16(q3l_0, q8_0); let p16_1 = _mm256_maddubs_epi16(q3l_1, q8_1); let p16_2 = _mm256_maddubs_epi16(q3l_2, q8_2); let p16_3 = _mm256_maddubs_epi16(q3l_3, q8_3); let p16_0 = _mm256_sub_epi16(p16_0, q8s_0); let p16_1 = _mm256_sub_epi16(p16_1, q8s_1); let p16_2 = _mm256_sub_epi16(p16_2, q8s_2); let p16_3 = _mm256_sub_epi16(p16_3, q8s_3); // multiply with scales let p16_0 = _mm256_madd_epi16(_mm256_shuffle_epi8(*scale, get_scale_shuffle_q3k(0)), p16_0); let p16_1 = _mm256_madd_epi16(_mm256_shuffle_epi8(*scale, get_scale_shuffle_q3k(1)), p16_1); let p16_2 = _mm256_madd_epi16(_mm256_shuffle_epi8(*scale, get_scale_shuffle_q3k(2)), p16_2); let p16_3 = _mm256_madd_epi16(_mm256_shuffle_epi8(*scale, get_scale_shuffle_q3k(3)), p16_3); // accumulate let p16_0 = _mm256_add_epi32(p16_0, p16_1); let p16_2 = _mm256_add_epi32(p16_2, p16_3); sumi = _mm256_add_epi32(sumi, _mm256_add_epi32(p16_0, p16_2)); } // multiply with block scale and accumulate acc = _mm256_fmadd_ps(_mm256_broadcast_ss(&d), _mm256_cvtepi32_ps(sumi), acc); } Ok(hsum_float_8(acc)) } } #[inline(always)] pub(crate) fn vec_dot_q4k_q8k(n: usize, xs: &[BlockQ4K], ys: &[BlockQ8K]) -> Result<f32> { if n % QK_K != 0 { crate::bail!("vec_dot_q4k_q8k: {n} is not divisible by {QK_K}") } let mut utmp = [0u32; 4]; const KMASK1: u32 = 0x3f3f3f3f; const KMASK2: u32 = 0x0f0f0f0f; const KMASK3: u32 = 0x03030303; unsafe { let m4 = _mm256_set1_epi8(0xF); let mut acc = _mm256_setzero_ps(); let mut acc_m = _mm_setzero_ps(); for (x, y) in xs.iter().zip(ys.iter()) { let d = y.d * x.d.to_f32(); let dmin = -y.d * x.dmin.to_f32(); LittleEndian::read_u32_into(&x.scales, &mut utmp[0..3]); utmp[3] = ((utmp[2] >> 4) & KMASK2) | (((utmp[1] >> 6) & KMASK3) << 4); let uaux = utmp[1] & KMASK1; utmp[1] = (utmp[2] & KMASK2) | (((utmp[0] >> 6) & KMASK3) << 4); utmp[2] = uaux; utmp[0] &= KMASK1; let mut q4 = x.qs.as_ptr(); let mut q8 = y.qs.as_ptr(); let mins_and_scales = _mm256_cvtepu8_epi16(_mm_set_epi32( utmp[3] as i32, utmp[2] as i32, utmp[1] as i32, utmp[0] as i32, )); let q8sums = _mm256_loadu_si256(y.bsums.as_ptr() as *const __m256i); let q8s = _mm_hadd_epi16( _mm256_extracti128_si256(q8sums, 0), _mm256_extracti128_si256(q8sums, 1), ); let prod = _mm_madd_epi16(_mm256_extracti128_si256(mins_and_scales, 1), q8s); acc_m = _mm_fmadd_ps(_mm_set1_ps(dmin), _mm_cvtepi32_ps(prod), acc_m); let sc128 = _mm256_extracti128_si256(mins_and_scales, 0); let scales = mm256_set_m128i(sc128, sc128); let mut sumi = _mm256_setzero_si256(); for j in 0..QK_K / 64 { let scale_l = _mm256_shuffle_epi8(scales, get_scale_shuffle_k4(2 * j)); let scale_h = _mm256_shuffle_epi8(scales, get_scale_shuffle_k4(2 * j + 1)); let q4bits = _mm256_loadu_si256(q4 as *const __m256i); q4 = q4.add(32); let q4l = _mm256_and_si256(q4bits, m4); let q4h = _mm256_and_si256(_mm256_srli_epi16(q4bits, 4), m4); let q8l = _mm256_loadu_si256(q8 as *const __m256i); q8 = q8.add(32); let p16l = _mm256_maddubs_epi16(q4l, q8l); let p16l = _mm256_madd_epi16(scale_l, p16l); sumi = _mm256_add_epi32(sumi, p16l); let q8h = _mm256_loadu_si256(q8 as *const __m256i); q8 = q8.add(32); let p16h = _mm256_maddubs_epi16(q4h, q8h); let p16h = _mm256_madd_epi16(scale_h, p16h); sumi = _mm256_add_epi32(sumi, p16h); } let vd = _mm256_set1_ps(d); acc = _mm256_fmadd_ps(vd, _mm256_cvtepi32_ps(sumi), acc); } let acc_m = _mm_add_ps(acc_m, _mm_movehl_ps(acc_m, acc_m)); let acc_m = _mm_add_ss(acc_m, _mm_movehdup_ps(acc_m)); Ok(hsum_float_8(acc) + _mm_cvtss_f32(acc_m)) } } #[inline(always)] pub(crate) fn vec_dot_q5k_q8k(n: usize, xs: &[BlockQ5K], ys: &[BlockQ8K]) -> Result<f32> { if n % QK_K != 0 { crate::bail!("vec_dot_q5k_q8k: {n} is not divisible by {QK_K}") } let mut utmp = [0u32; 4]; const KMASK1: u32 = 0x3f3f3f3f; const KMASK2: u32 = 0x0f0f0f0f; const KMASK3: u32 = 0x03030303; unsafe { let m4 = _mm256_set1_epi8(0xF); let mzero = _mm_setzero_si128(); let mone = _mm256_set1_epi8(1); let mut acc = _mm256_setzero_ps(); let mut summs = 0.0; for (x, y) in xs.iter().zip(ys.iter()) { let d = y.d * x.d.to_f32(); let dmin = -y.d * x.dmin.to_f32(); LittleEndian::read_u32_into(&x.scales, &mut utmp[0..3]); utmp[3] = ((utmp[2] >> 4) & KMASK2) | (((utmp[1] >> 6) & KMASK3) << 4); let uaux = utmp[1] & KMASK1; utmp[1] = (utmp[2] & KMASK2) | (((utmp[0] >> 6) & KMASK3) << 4); utmp[2] = uaux; utmp[0] &= KMASK1; let mut q5 = x.qs.as_ptr(); let mut q8 = y.qs.as_ptr(); let mins_and_scales = _mm256_cvtepu8_epi16(_mm_set_epi32( utmp[3] as i32, utmp[2] as i32, utmp[1] as i32, utmp[0] as i32, )); let q8sums = _mm256_loadu_si256(y.bsums.as_ptr() as *const __m256i); let q8s = _mm_hadd_epi16( _mm256_extracti128_si256(q8sums, 0), _mm256_extracti128_si256(q8sums, 1), ); let prod = _mm_madd_epi16(_mm256_extracti128_si256(mins_and_scales, 1), q8s); let hsum = _mm_hadd_epi32(_mm_hadd_epi32(prod, mzero), mzero); summs += dmin * _mm_extract_epi32(hsum, 0) as f32; let sc128 = _mm256_extracti128_si256(mins_and_scales, 0); let scales = mm256_set_m128i(sc128, sc128); let hbits = _mm256_loadu_si256(x.qh.as_ptr() as *const __m256i); let mut hmask = mone; let mut sumi = _mm256_setzero_si256(); for j in 0..QK_K / 64 { let scale_0 = _mm256_shuffle_epi8(scales, get_scale_shuffle_k4(2 * j)); let scale_1 = _mm256_shuffle_epi8(scales, get_scale_shuffle_k4(2 * j + 1)); let q5bits = _mm256_loadu_si256(q5 as *const __m256i); q5 = q5.add(32); //Similar to q3k we hardcode the shifts here to avoid loading them into a separate register let q5l_0 = _mm256_and_si256(q5bits, m4); let q5l_0_shift_input = _mm256_and_si256(hbits, hmask); let q5l_0_right_shift = match j { 0 => _mm256_srli_epi16(q5l_0_shift_input, 0), 1 => _mm256_srli_epi16(q5l_0_shift_input, 2), 2 => _mm256_srli_epi16(q5l_0_shift_input, 4), 3 => _mm256_srli_epi16(q5l_0_shift_input, 6), _ => unreachable!(), }; let q5h_0 = _mm256_slli_epi16(q5l_0_right_shift, 4); let q5_0 = _mm256_add_epi8(q5l_0, q5h_0); hmask = _mm256_slli_epi16(hmask, 1); let q5l_1 = _mm256_and_si256(_mm256_srli_epi16(q5bits, 4), m4); let q5l_1_shift_input = _mm256_and_si256(hbits, hmask); let q5l_1_right_shift = match j { 0 => _mm256_srli_epi16(q5l_1_shift_input, 1), 1 => _mm256_srli_epi16(q5l_1_shift_input, 3), 2 => _mm256_srli_epi16(q5l_1_shift_input, 5), 3 => _mm256_srli_epi16(q5l_1_shift_input, 7), _ => unreachable!(), }; let q5h_1 = _mm256_slli_epi16(q5l_1_right_shift, 4); let q5_1 = _mm256_add_epi8(q5l_1, q5h_1); hmask = _mm256_slli_epi16(hmask, 1); let q8_0 = _mm256_loadu_si256(q8 as *const __m256i); q8 = q8.add(32); let q8_1 = _mm256_loadu_si256(q8 as *const __m256i); q8 = q8.add(32); let p16_0 = _mm256_maddubs_epi16(q5_0, q8_0); let p16_1 = _mm256_maddubs_epi16(q5_1, q8_1); let p16_0 = _mm256_madd_epi16(scale_0, p16_0); let p16_1 = _mm256_madd_epi16(scale_1, p16_1); sumi = _mm256_add_epi32(sumi, _mm256_add_epi32(p16_0, p16_1)); } let vd = _mm256_set1_ps(d); acc = _mm256_fmadd_ps(vd, _mm256_cvtepi32_ps(sumi), acc); } Ok(hsum_float_8(acc) + summs) } } #[inline(always)] pub(crate) fn vec_dot_q8k_q8k(n: usize, xs: &[BlockQ8K], ys: &[BlockQ8K]) -> Result<f32> { let qk = QK_K; if n % qk != 0 { crate::bail!("vec_dot_q8k_8k: {n} is not divisible by {qk}") } unsafe { let mut acc = _mm256_setzero_ps(); for (xs, ys) in xs.iter().zip(ys.iter()) { let mut sumi = _mm256_setzero_si256(); let x_qs = xs.qs.as_ptr(); let y_qs = ys.qs.as_ptr(); for j in (0..QK_K).step_by(32) { let xs = _mm256_loadu_si256(x_qs.add(j) as *const __m256i); let ys = _mm256_loadu_si256(y_qs.add(j) as *const __m256i); let xs0 = _mm256_cvtepi8_epi16(_mm256_extracti128_si256(xs, 0)); let ys0 = _mm256_cvtepi8_epi16(_mm256_extracti128_si256(ys, 0)); sumi = _mm256_add_epi32(sumi, _mm256_madd_epi16(xs0, ys0)); let xs1 = _mm256_cvtepi8_epi16(_mm256_extracti128_si256(xs, 1)); let ys1 = _mm256_cvtepi8_epi16(_mm256_extracti128_si256(ys, 1)); sumi = _mm256_add_epi32(sumi, _mm256_madd_epi16(xs1, ys1)); } let d = _mm256_set1_ps(xs.d * ys.d); acc = _mm256_fmadd_ps(d, _mm256_cvtepi32_ps(sumi), acc); } Ok(hsum_float_8(acc)) } }
candle/candle-core/src/quantized/avx.rs/0
{ "file_path": "candle/candle-core/src/quantized/avx.rs", "repo_id": "candle", "token_count": 17495 }
28
use crate::backend::BackendStorage; use crate::op::{self, CmpOp, ReduceOp}; use crate::scalar::Scalar; use crate::{CpuStorage, CudaStorage, DType, Device, Error, Layout, MetalStorage, Result, Shape}; use crate::{CustomOp1, CustomOp2, CustomOp3, InplaceOp1, InplaceOp2, InplaceOp3}; // We do not want to implement Clone on Storage as cloning may fail because of // out of memory. Instead try_clone should be used. #[derive(Debug)] pub enum Storage { Cpu(CpuStorage), Cuda(CudaStorage), Metal(MetalStorage), } impl Storage { pub fn try_clone(&self, layout: &Layout) -> Result<Self> { match self { Self::Cpu(storage) => Ok(Self::Cpu(storage.clone())), Self::Cuda(storage) => { let storage = storage.try_clone(layout)?; Ok(Self::Cuda(storage)) } Self::Metal(storage) => { let storage = storage.try_clone(layout)?; Ok(Self::Metal(storage)) } } } pub fn device(&self) -> Device { match self { Self::Cpu(_) => Device::Cpu, Self::Cuda(storage) => Device::Cuda(storage.device().clone()), Self::Metal(storage) => Device::Metal(storage.device().clone()), } } pub fn dtype(&self) -> DType { match self { Self::Cpu(storage) => storage.dtype(), Self::Cuda(storage) => storage.dtype(), Self::Metal(storage) => storage.dtype(), } } pub(crate) fn same_device(&self, rhs: &Self, op: &'static str) -> Result<()> { let lhs_device = self.device(); let rhs_device = rhs.device(); let lhs = lhs_device.location(); let rhs = rhs_device.location(); let same_device = if self.device().is_metal() { // On metal, we require the device to be exactly the same rather than // having the same location. In cuda this is not necessary as all CudaDevice on the // same GPU will use the same cuda stream. lhs_device.same_device(&rhs_device) } else { lhs == rhs }; if !same_device { Err(Error::DeviceMismatchBinaryOp { lhs, rhs, op }.bt()) } else { Ok(()) } } pub(crate) fn same_dtype(&self, rhs: &Self, op: &'static str) -> Result<()> { let lhs = self.dtype(); let rhs = rhs.dtype(); if lhs != rhs { Err(Error::DTypeMismatchBinaryOp { lhs, rhs, op }.bt()) } else { Ok(()) } } pub(crate) fn const_set(&mut self, v: Scalar, l: &Layout) -> Result<()> { match self { Storage::Cpu(storage) => storage.const_set(v, l), Storage::Cuda(storage) => storage.const_set(v, l), Storage::Metal(storage) => storage.const_set(v, l), } } pub(crate) fn affine(&self, layout: &Layout, mul: f64, add: f64) -> Result<Self> { match self { Storage::Cpu(storage) => { let storage = storage.affine(layout, mul, add)?; Ok(Self::Cpu(storage)) } Self::Cuda(storage) => { let storage = storage.affine(layout, mul, add)?; Ok(Self::Cuda(storage)) } Self::Metal(storage) => { let storage = storage.affine(layout, mul, add)?; Ok(Self::Metal(storage)) } } } pub(crate) fn powf(&self, layout: &Layout, alpha: f64) -> Result<Self> { match self { Storage::Cpu(storage) => { let storage = storage.powf(layout, alpha)?; Ok(Self::Cpu(storage)) } Self::Cuda(storage) => { let storage = storage.powf(layout, alpha)?; Ok(Self::Cuda(storage)) } Self::Metal(storage) => { let storage = storage.powf(layout, alpha)?; Ok(Self::Metal(storage)) } } } pub(crate) fn elu(&self, layout: &Layout, alpha: f64) -> Result<Self> { match self { Storage::Cpu(storage) => { let storage = storage.elu(layout, alpha)?; Ok(Self::Cpu(storage)) } Self::Cuda(storage) => { let storage = storage.elu(layout, alpha)?; Ok(Self::Cuda(storage)) } Self::Metal(storage) => { let storage = storage.elu(layout, alpha)?; Ok(Self::Metal(storage)) } } } pub(crate) fn cmp( &self, op: CmpOp, rhs: &Self, lhs_layout: &Layout, rhs_layout: &Layout, ) -> Result<Self> { self.same_device(rhs, "cmp")?; self.same_dtype(rhs, "cmp")?; match (self, rhs) { (Storage::Cpu(lhs), Storage::Cpu(rhs)) => { let storage = lhs.cmp(op, rhs, lhs_layout, rhs_layout)?; Ok(Self::Cpu(storage)) } (Self::Cuda(lhs), Self::Cuda(rhs)) => { let storage = lhs.cmp(op, rhs, lhs_layout, rhs_layout)?; Ok(Self::Cuda(storage)) } (Self::Metal(lhs), Self::Metal(rhs)) => { let storage = lhs.cmp(op, rhs, lhs_layout, rhs_layout)?; Ok(Self::Metal(storage)) } (lhs, rhs) => { // Should not happen because of the same device check above but we're defensive // anyway. Err(Error::DeviceMismatchBinaryOp { lhs: lhs.device().location(), rhs: rhs.device().location(), op: "cmp", } .bt()) } } } pub(crate) fn reduce_op(&self, op: ReduceOp, layout: &Layout, s: &[usize]) -> Result<Self> { match self { Storage::Cpu(storage) => { let storage = storage.reduce_op(op, layout, s)?; Ok(Self::Cpu(storage)) } Self::Cuda(storage) => { let storage = storage.reduce_op(op, layout, s)?; Ok(Self::Cuda(storage)) } Self::Metal(storage) => { let storage = storage.reduce_op(op, layout, s)?; Ok(Self::Metal(storage)) } } } pub(crate) fn to_dtype(&self, layout: &Layout, dtype: DType) -> Result<Self> { match self { Storage::Cpu(storage) => { let storage = storage.to_dtype(layout, dtype)?; Ok(Self::Cpu(storage)) } Self::Cuda(storage) => { let storage = storage.to_dtype(layout, dtype)?; Ok(Self::Cuda(storage)) } Self::Metal(storage) => { let storage = storage.to_dtype(layout, dtype)?; Ok(Self::Metal(storage)) } } } pub(crate) fn apply_op1(&self, l: &Layout, c: &dyn CustomOp1) -> Result<(Self, Shape)> { match self { Self::Cpu(storage) => { let (storage, shape) = c.cpu_fwd(storage, l)?; Ok((Self::Cpu(storage), shape)) } Self::Cuda(storage) => { let (storage, shape) = c.cuda_fwd(storage, l)?; Ok((Self::Cuda(storage), shape)) } Self::Metal(storage) => { let (storage, shape) = c.metal_fwd(storage, l)?; Ok((Self::Metal(storage), shape)) } } } pub(crate) fn apply_op2( &self, l1: &Layout, t2: &Self, l2: &Layout, c: &dyn CustomOp2, ) -> Result<(Self, Shape)> { self.same_device(t2, c.name())?; match (self, t2) { (Self::Cpu(s1), Self::Cpu(s2)) => { let (s, shape) = c.cpu_fwd(s1, l1, s2, l2)?; Ok((Self::Cpu(s), shape)) } (Self::Cuda(s1), Self::Cuda(s2)) => { let (s, shape) = c.cuda_fwd(s1, l1, s2, l2)?; Ok((Self::Cuda(s), shape)) } (Self::Metal(s1), Self::Metal(s2)) => { let (s, shape) = c.metal_fwd(s1, l1, s2, l2)?; Ok((Self::Metal(s), shape)) } _ => unreachable!(), } } pub(crate) fn apply_op3( &self, l1: &Layout, t2: &Self, l2: &Layout, t3: &Self, l3: &Layout, c: &dyn CustomOp3, ) -> Result<(Self, Shape)> { self.same_device(t2, c.name())?; self.same_device(t3, c.name())?; match (self, t2, t3) { (Self::Cpu(s1), Self::Cpu(s2), Self::Cpu(s3)) => { let (s, shape) = c.cpu_fwd(s1, l1, s2, l2, s3, l3)?; Ok((Self::Cpu(s), shape)) } (Self::Cuda(s1), Self::Cuda(s2), Self::Cuda(s3)) => { let (s, shape) = c.cuda_fwd(s1, l1, s2, l2, s3, l3)?; Ok((Self::Cuda(s), shape)) } (Self::Metal(s1), Self::Metal(s2), Self::Metal(s3)) => { let (s, shape) = c.metal_fwd(s1, l1, s2, l2, s3, l3)?; Ok((Self::Metal(s), shape)) } _ => unreachable!(), } } pub(crate) fn inplace_op1(&mut self, l: &Layout, c: &dyn InplaceOp1) -> Result<()> { match self { Self::Cpu(storage) => c.cpu_fwd(storage, l), Self::Cuda(storage) => c.cuda_fwd(storage, l), Self::Metal(storage) => c.metal_fwd(storage, l), } } pub(crate) fn inplace_op2( &mut self, l1: &Layout, t2: &Self, l2: &Layout, c: &dyn InplaceOp2, ) -> Result<()> { self.same_device(t2, c.name())?; match (self, t2) { (Self::Cpu(s1), Self::Cpu(s2)) => c.cpu_fwd(s1, l1, s2, l2), (Self::Cuda(s1), Self::Cuda(s2)) => c.cuda_fwd(s1, l1, s2, l2), (Self::Metal(s1), Self::Metal(s2)) => c.metal_fwd(s1, l1, s2, l2), _ => unreachable!(), } } pub(crate) fn inplace_op3( &mut self, l1: &Layout, t2: &Self, l2: &Layout, t3: &Self, l3: &Layout, c: &dyn InplaceOp3, ) -> Result<()> { self.same_device(t2, c.name())?; self.same_device(t3, c.name())?; match (self, t2, t3) { (Self::Cpu(s1), Self::Cpu(s2), Self::Cpu(s3)) => c.cpu_fwd(s1, l1, s2, l2, s3, l3), (Self::Cuda(s1), Self::Cuda(s2), Self::Cuda(s3)) => c.cuda_fwd(s1, l1, s2, l2, s3, l3), (Self::Metal(s1), Self::Metal(s2), Self::Metal(s3)) => { c.metal_fwd(s1, l1, s2, l2, s3, l3) } _ => unreachable!(), } } pub(crate) fn unary_impl<B: op::UnaryOpT>(&self, layout: &Layout) -> Result<Self> { match self { Storage::Cpu(storage) => { let storage = storage.unary_impl::<B>(layout)?; Ok(Self::Cpu(storage)) } Self::Cuda(storage) => { let storage = storage.unary_impl::<B>(layout)?; Ok(Self::Cuda(storage)) } Self::Metal(storage) => { let storage = storage.unary_impl::<B>(layout)?; Ok(Self::Metal(storage)) } } } pub(crate) fn binary_impl<B: op::BinaryOpT>( &self, rhs: &Self, lhs_layout: &Layout, rhs_layout: &Layout, ) -> Result<Self> { self.same_device(rhs, B::NAME)?; self.same_dtype(rhs, B::NAME)?; match (self, rhs) { (Storage::Cpu(lhs), Storage::Cpu(rhs)) => { let storage = lhs.binary_impl::<B>(rhs, lhs_layout, rhs_layout)?; Ok(Self::Cpu(storage)) } (Self::Cuda(lhs), Self::Cuda(rhs)) => { let storage = lhs.binary_impl::<B>(rhs, lhs_layout, rhs_layout)?; Ok(Self::Cuda(storage)) } (Self::Metal(lhs), Self::Metal(rhs)) => { let storage = lhs.binary_impl::<B>(rhs, lhs_layout, rhs_layout)?; Ok(Self::Metal(storage)) } (lhs, rhs) => { // Should not happen because of the same device check above but we're defensive // anyway. Err(Error::DeviceMismatchBinaryOp { lhs: lhs.device().location(), rhs: rhs.device().location(), op: B::NAME, } .bt()) } } } pub(crate) fn conv1d( &self, l: &Layout, kernel: &Self, kernel_l: &Layout, params: &crate::conv::ParamsConv1D, ) -> Result<Self> { self.same_device(kernel, "conv1d")?; self.same_dtype(kernel, "conv1d")?; match (self, &kernel) { (Storage::Cpu(inp), Storage::Cpu(kernel)) => { let s = inp.conv1d(l, kernel, kernel_l, params)?; Ok(Self::Cpu(s)) } (Storage::Cuda(inp), Storage::Cuda(kernel)) => { let s = inp.conv1d(l, kernel, kernel_l, params)?; Ok(Self::Cuda(s)) } (Storage::Metal(inp), Storage::Metal(kernel)) => { let s = inp.conv1d(l, kernel, kernel_l, params)?; Ok(Self::Metal(s)) } (lhs, rhs) => Err(Error::DeviceMismatchBinaryOp { lhs: lhs.device().location(), rhs: rhs.device().location(), op: "conv1d", } .bt()), } } pub(crate) fn conv_transpose1d( &self, l: &Layout, kernel: &Self, kernel_l: &Layout, params: &crate::conv::ParamsConvTranspose1D, ) -> Result<Self> { self.same_device(kernel, "conv-transpose1d")?; self.same_dtype(kernel, "conv-transpose1d")?; match (self, &kernel) { (Storage::Cpu(inp), Storage::Cpu(kernel)) => { let s = inp.conv_transpose1d(l, kernel, kernel_l, params)?; Ok(Self::Cpu(s)) } (Storage::Cuda(inp), Storage::Cuda(kernel)) => { let s = inp.conv_transpose1d(l, kernel, kernel_l, params)?; Ok(Self::Cuda(s)) } (Storage::Metal(inp), Storage::Metal(kernel)) => { let s = inp.conv_transpose1d(l, kernel, kernel_l, params)?; Ok(Self::Metal(s)) } (lhs, rhs) => Err(Error::DeviceMismatchBinaryOp { lhs: lhs.device().location(), rhs: rhs.device().location(), op: "conv-transpose1d", } .bt()), } } pub(crate) fn conv2d( &self, l: &Layout, kernel: &Self, kernel_l: &Layout, params: &crate::conv::ParamsConv2D, ) -> Result<Self> { self.same_device(kernel, "conv2d")?; self.same_dtype(kernel, "conv2d")?; match (self, &kernel) { (Storage::Cpu(inp), Storage::Cpu(kernel)) => { let s = inp.conv2d(l, kernel, kernel_l, params)?; Ok(Self::Cpu(s)) } (Storage::Cuda(inp), Storage::Cuda(kernel)) => { let s = inp.conv2d(l, kernel, kernel_l, params)?; Ok(Self::Cuda(s)) } (Storage::Metal(inp), Storage::Metal(kernel)) => { let s = inp.conv2d(l, kernel, kernel_l, params)?; Ok(Self::Metal(s)) } (lhs, rhs) => Err(Error::DeviceMismatchBinaryOp { lhs: lhs.device().location(), rhs: rhs.device().location(), op: "conv2d", } .bt()), } } pub(crate) fn conv_transpose2d( &self, l: &Layout, kernel: &Self, kernel_l: &Layout, params: &crate::conv::ParamsConvTranspose2D, ) -> Result<Self> { self.same_device(kernel, "conv_transpose2d")?; self.same_dtype(kernel, "conv_transpose2d")?; match (self, &kernel) { (Storage::Cpu(inp), Storage::Cpu(kernel)) => { let s = inp.conv_transpose2d(l, kernel, kernel_l, params)?; Ok(Self::Cpu(s)) } (Storage::Cuda(inp), Storage::Cuda(kernel)) => { let s = inp.conv_transpose2d(l, kernel, kernel_l, params)?; Ok(Self::Cuda(s)) } (Storage::Metal(inp), Storage::Metal(kernel)) => { let s = inp.conv_transpose2d(l, kernel, kernel_l, params)?; Ok(Self::Metal(s)) } (lhs, rhs) => Err(Error::DeviceMismatchBinaryOp { lhs: lhs.device().location(), rhs: rhs.device().location(), op: "conv_transpose2d", } .bt()), } } pub(crate) fn avg_pool2d( &self, layout: &Layout, kernel_size: (usize, usize), stride: (usize, usize), ) -> Result<Self> { match self { Storage::Cpu(storage) => { let storage = storage.avg_pool2d(layout, kernel_size, stride)?; Ok(Self::Cpu(storage)) } Self::Cuda(storage) => { let storage = storage.avg_pool2d(layout, kernel_size, stride)?; Ok(Self::Cuda(storage)) } Self::Metal(storage) => { let storage = storage.avg_pool2d(layout, kernel_size, stride)?; Ok(Self::Metal(storage)) } } } pub(crate) fn max_pool2d( &self, layout: &Layout, kernel_size: (usize, usize), stride: (usize, usize), ) -> Result<Self> { match self { Storage::Cpu(storage) => { let storage = storage.max_pool2d(layout, kernel_size, stride)?; Ok(Self::Cpu(storage)) } Self::Cuda(storage) => { let storage = storage.max_pool2d(layout, kernel_size, stride)?; Ok(Self::Cuda(storage)) } Self::Metal(storage) => { let storage = storage.max_pool2d(layout, kernel_size, stride)?; Ok(Self::Metal(storage)) } } } pub(crate) fn upsample_nearest1d(&self, layout: &Layout, sz: usize) -> Result<Self> { match self { Storage::Cpu(storage) => { let storage = storage.upsample_nearest1d(layout, sz)?; Ok(Self::Cpu(storage)) } Self::Cuda(storage) => { let storage = storage.upsample_nearest1d(layout, sz)?; Ok(Self::Cuda(storage)) } Self::Metal(storage) => { let storage = storage.upsample_nearest1d(layout, sz)?; Ok(Self::Metal(storage)) } } } pub(crate) fn upsample_nearest2d(&self, layout: &Layout, h: usize, w: usize) -> Result<Self> { match self { Storage::Cpu(storage) => { let storage = storage.upsample_nearest2d(layout, h, w)?; Ok(Self::Cpu(storage)) } Self::Cuda(storage) => { let storage = storage.upsample_nearest2d(layout, h, w)?; Ok(Self::Cuda(storage)) } Self::Metal(storage) => { let storage = storage.upsample_nearest2d(layout, h, w)?; Ok(Self::Metal(storage)) } } } pub(crate) fn where_cond( &self, layout: &Layout, t: &Self, layout_t: &Layout, f: &Self, layout_f: &Layout, ) -> Result<Self> { self.same_device(t, "where")?; self.same_device(f, "where")?; t.same_dtype(f, "where")?; match (self, t, f) { (Storage::Cpu(cond), Storage::Cpu(t), Storage::Cpu(f)) => { let storage = cond.where_cond(layout, t, layout_t, f, layout_f)?; Ok(Self::Cpu(storage)) } (Self::Cuda(cond), Self::Cuda(t), Self::Cuda(f)) => { let storage = cond.where_cond(layout, t, layout_t, f, layout_f)?; Ok(Self::Cuda(storage)) } (Self::Metal(cond), Self::Metal(t), Self::Metal(f)) => { let storage = cond.where_cond(layout, t, layout_t, f, layout_f)?; Ok(Self::Metal(storage)) } (_, lhs, rhs) => Err(Error::DeviceMismatchBinaryOp { lhs: lhs.device().location(), rhs: rhs.device().location(), op: "where", } .bt()), } } pub(crate) fn gather( &self, l: &Layout, indexes: &Self, indexes_l: &Layout, d: usize, ) -> Result<Self> { self.same_device(indexes, "index-add")?; match (self, indexes) { (Self::Cpu(s), Self::Cpu(indexes)) => { let storage = s.gather(l, indexes, indexes_l, d)?; Ok(Self::Cpu(storage)) } (Self::Cuda(s), Self::Cuda(indexes)) => { let storage = s.gather(l, indexes, indexes_l, d)?; Ok(Self::Cuda(storage)) } (Self::Metal(s), Self::Metal(indexes)) => { let storage = s.gather(l, indexes, indexes_l, d)?; Ok(Self::Metal(storage)) } _ => unreachable!(), } } pub(crate) fn scatter_set( &mut self, l: &Layout, indexes: &Self, indexes_l: &Layout, source: &Self, source_l: &Layout, d: usize, ) -> Result<()> { self.same_device(indexes, "scatter-set")?; self.same_device(source, "scatter-set")?; match (self, indexes, source) { (Self::Cpu(s), Self::Cpu(indexes), Self::Cpu(source)) => { s.scatter_set(l, indexes, indexes_l, source, source_l, d)?; } (Self::Cuda(s), Self::Cuda(indexes), Self::Cuda(source)) => { s.scatter_set(l, indexes, indexes_l, source, source_l, d)?; } (Self::Metal(s), Self::Metal(indexes), Self::Metal(source)) => { s.scatter_set(l, indexes, indexes_l, source, source_l, d)?; } _ => unreachable!(), } Ok(()) } pub(crate) fn scatter_add( &mut self, l: &Layout, indexes: &Self, indexes_l: &Layout, source: &Self, source_l: &Layout, d: usize, ) -> Result<()> { self.same_device(indexes, "scatter-add")?; self.same_device(source, "scatter-add")?; match (self, indexes, source) { (Self::Cpu(s), Self::Cpu(indexes), Self::Cpu(source)) => { s.scatter_add_set(l, indexes, indexes_l, source, source_l, d)?; } (Self::Cuda(s), Self::Cuda(indexes), Self::Cuda(source)) => { s.scatter_add_set(l, indexes, indexes_l, source, source_l, d)?; } (Self::Metal(s), Self::Metal(indexes), Self::Metal(source)) => { s.scatter_add_set(l, indexes, indexes_l, source, source_l, d)?; } _ => unreachable!(), } Ok(()) } pub(crate) fn index_add( &self, l: &Layout, indexes: &Self, indexes_l: &Layout, source: &Self, source_l: &Layout, d: usize, ) -> Result<Self> { self.same_device(indexes, "index-add")?; self.same_device(source, "index-add")?; match (self, indexes, source) { (Self::Cpu(s), Self::Cpu(indexes), Self::Cpu(source)) => { let storage = s.index_add(l, indexes, indexes_l, source, source_l, d)?; Ok(Self::Cpu(storage)) } (Self::Cuda(s), Self::Cuda(indexes), Self::Cuda(source)) => { let storage = s.index_add(l, indexes, indexes_l, source, source_l, d)?; Ok(Self::Cuda(storage)) } (Self::Metal(s), Self::Metal(indexes), Self::Metal(source)) => { let storage = s.index_add(l, indexes, indexes_l, source, source_l, d)?; Ok(Self::Metal(storage)) } _ => unreachable!(), } } pub(crate) fn index_select( &self, rhs: &Self, lhs_l: &Layout, rhs_l: &Layout, d: usize, ) -> Result<Self> { self.same_device(rhs, "index-select")?; match (self, rhs) { (Self::Cpu(lhs), Self::Cpu(rhs)) => { let storage = lhs.index_select(rhs, lhs_l, rhs_l, d)?; Ok(Self::Cpu(storage)) } (Self::Cuda(lhs), Self::Cuda(rhs)) => { let storage = lhs.index_select(rhs, lhs_l, rhs_l, d)?; Ok(Self::Cuda(storage)) } (Self::Metal(lhs), Self::Metal(rhs)) => { let storage = lhs.index_select(rhs, lhs_l, rhs_l, d)?; Ok(Self::Metal(storage)) } (lhs, rhs) => Err(Error::DeviceMismatchBinaryOp { lhs: lhs.device().location(), rhs: rhs.device().location(), op: "index-select", } .bt()), } } pub(crate) fn matmul( &self, rhs: &Self, bmnk: (usize, usize, usize, usize), lhs_layout: &Layout, rhs_layout: &Layout, ) -> Result<Self> { self.same_device(rhs, "matmul")?; self.same_dtype(rhs, "matmul")?; match (self, rhs) { (Self::Cpu(lhs), Self::Cpu(rhs)) => { let storage = lhs.matmul(rhs, bmnk, lhs_layout, rhs_layout)?; Ok(Self::Cpu(storage)) } (Self::Cuda(lhs), Self::Cuda(rhs)) => { let storage = lhs.matmul(rhs, bmnk, lhs_layout, rhs_layout)?; Ok(Self::Cuda(storage)) } (Self::Metal(lhs), Self::Metal(rhs)) => { let storage = lhs.matmul(rhs, bmnk, lhs_layout, rhs_layout)?; Ok(Self::Metal(storage)) } (lhs, rhs) => Err(Error::DeviceMismatchBinaryOp { lhs: lhs.device().location(), rhs: rhs.device().location(), op: "matmul", } .bt()), } } // self, the source can be strided whereas dst is contiguous. pub(crate) fn copy_strided_src( &self, dst: &mut Self, dst_offset: usize, src_l: &Layout, ) -> Result<()> { match (self, dst) { (Self::Cpu(src), Self::Cpu(dst)) => src.copy_strided_src(dst, dst_offset, src_l), (Self::Cuda(src), Self::Cuda(dst)) => Ok(src.copy_strided_src(dst, dst_offset, src_l)?), (Self::Metal(src), Self::Metal(dst)) => { Ok(src.copy_strided_src(dst, dst_offset, src_l)?) } (lhs, rhs) => Err(Error::DeviceMismatchBinaryOp { lhs: lhs.device().location(), rhs: rhs.device().location(), op: "copy", } .bt()), } } #[allow(clippy::too_many_arguments)] pub(crate) fn copy2d( &self, dst: &mut Self, d1: usize, d2: usize, src_s: usize, dst_s: usize, src_o: usize, dst_o: usize, ) -> Result<()> { match (self, dst) { (Self::Cpu(src), Self::Cpu(dst)) => src.copy2d(dst, d1, d2, src_s, dst_s, src_o, dst_o), (Self::Cuda(src), Self::Cuda(dst)) => { Ok(src.copy2d(dst, d1, d2, src_s, dst_s, src_o, dst_o)?) } (Self::Metal(src), Self::Metal(dst)) => { Ok(src.copy2d(dst, d1, d2, src_s, dst_s, src_o, dst_o)?) } (lhs, rhs) => Err(Error::DeviceMismatchBinaryOp { lhs: lhs.device().location(), rhs: rhs.device().location(), op: "copy2d", } .bt()), } } }
candle/candle-core/src/storage.rs/0
{ "file_path": "candle/candle-core/src/storage.rs", "repo_id": "candle", "token_count": 16174 }
29
import numpy as np x = np.arange(10) # Write a npy file. np.save("test.npy", x) # Write multiple values to a npz file. values = { "x": x, "x_plus_one": x + 1 } np.savez("test.npz", **values)
candle/candle-core/tests/npy.py/0
{ "file_path": "candle/candle-core/tests/npy.py", "repo_id": "candle", "token_count": 83 }
30
pub mod tinystories;
candle/candle-datasets/src/nlp/mod.rs/0
{ "file_path": "candle/candle-datasets/src/nlp/mod.rs", "repo_id": "candle", "token_count": 6 }
31
#[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::bigcode::{Config, GPTBigCode}; use candle::{DType, Device, Tensor}; use candle_nn::VarBuilder; use candle_transformers::generation::LogitsProcessor; use hf_hub::{api::sync::Api, Repo, RepoType}; use tokenizers::Tokenizer; struct TextGeneration { model: GPTBigCode, device: Device, tokenizer: Tokenizer, logits_processor: LogitsProcessor, } impl TextGeneration { fn new( model: GPTBigCode, tokenizer: Tokenizer, seed: u64, temp: Option<f64>, top_p: Option<f64>, device: &Device, ) -> Self { let logits_processor = LogitsProcessor::new(seed, temp, top_p); Self { model, tokenizer, logits_processor, device: device.clone(), } } fn run(&mut self, prompt: &str, sample_len: usize) -> Result<()> { use std::io::Write; println!("starting the inference loop"); print!("{prompt}"); std::io::stdout().flush()?; let mut tokens = self .tokenizer .encode(prompt, true) .map_err(E::msg)? .get_ids() .to_vec(); let mut new_tokens = vec![]; let start_gen = std::time::Instant::now(); for index in 0..sample_len { let (context_size, past_len) = if self.model.config().use_cache && index > 0 { (1, tokens.len().saturating_sub(1)) } else { (tokens.len(), 0) }; let ctxt = &tokens[tokens.len().saturating_sub(context_size)..]; let input = Tensor::new(ctxt, &self.device)?.unsqueeze(0)?; let logits = self.model.forward(&input, past_len)?; let logits = logits.squeeze(0)?.to_dtype(DType::F32)?; let next_token = self.logits_processor.sample(&logits)?; tokens.push(next_token); new_tokens.push(next_token); let token = self.tokenizer.decode(&[next_token], true).map_err(E::msg)?; print!("{token}"); std::io::stdout().flush()?; } let dt = start_gen.elapsed(); println!( "{sample_len} tokens generated ({:.3} token/s)", sample_len 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, #[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, default_value_t = 100)] sample_len: usize, #[arg(long, default_value = "bigcode/starcoderbase-1b")] model_id: String, #[arg(long, default_value = "main")] revision: String, #[arg(long)] weight_file: Option<String>, } fn main() -> Result<()> { let args = Args::parse(); let start = std::time::Instant::now(); let api = Api::new()?; let repo = api.repo(Repo::with_revision( args.model_id, RepoType::Model, args.revision, )); let tokenizer_filename = repo.get("tokenizer.json")?; let filenames = match args.weight_file { Some(weight_file) => vec![std::path::PathBuf::from(weight_file)], None => ["model.safetensors"] .iter() .map(|f| repo.get(f)) .collect::<std::result::Result<Vec<_>, _>>()?, }; 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 device = candle_examples::device(args.cpu)?; let vb = unsafe { VarBuilder::from_mmaped_safetensors(&filenames, DType::F32, &device)? }; let config = Config::starcoder_1b(); let model = GPTBigCode::load(vb, config)?; println!("loaded the model in {:?}", start.elapsed()); let mut pipeline = TextGeneration::new( model, tokenizer, args.seed, args.temperature, args.top_p, &device, ); pipeline.run(&args.prompt, args.sample_len)?; Ok(()) }
candle/candle-examples/examples/bigcode/main.rs/0
{ "file_path": "candle/candle-examples/examples/bigcode/main.rs", "repo_id": "candle", "token_count": 2134 }
32
#[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; use clap::{Parser, ValueEnum}; use candle::{DType, IndexOp, D}; use candle_nn::{Module, VarBuilder}; use candle_transformers::models::convnext; #[derive(Clone, Copy, Debug, ValueEnum)] enum Which { Atto, Femto, Pico, Nano, Tiny, Small, Base, Large, AttoV2, FemtoV2, PicoV2, NanoV2, TinyV2, BaseV2, LargeV2, XLarge, Huge, } impl Which { fn model_filename(&self) -> String { let name = match self { Self::Atto => "convnext_atto.d2_in1k", Self::Femto => "convnext_femto.d1_in1k", Self::Pico => "convnext_pico.d1_in1k", Self::Nano => "convnext_nano.d1h_in1k", Self::Tiny => "convnext_tiny.fb_in1k", Self::Small => "convnext_small.fb_in1k", Self::Base => "convnext_base.fb_in1k", Self::Large => "convnext_large.fb_in1k", Self::AttoV2 => "convnextv2_atto.fcmae_ft_in1k", Self::FemtoV2 => "convnextv2_femto.fcmae_ft_in1k", Self::PicoV2 => "convnextv2_pico.fcmae_ft_in1k", Self::NanoV2 => "convnextv2_nano.fcmae_ft_in1k", Self::TinyV2 => "convnextv2_tiny.fcmae_ft_in1k", Self::BaseV2 => "convnextv2_base.fcmae_ft_in1k", Self::LargeV2 => "convnextv2_large.fcmae_ft_in1k", Self::XLarge => "convnext_xlarge.fb_in22k_ft_in1k", Self::Huge => "convnextv2_huge.fcmae_ft_in1k", }; format!("timm/{name}") } fn config(&self) -> convnext::Config { match self { Self::Atto | Self::AttoV2 => convnext::Config::atto(), Self::Femto | Self::FemtoV2 => convnext::Config::femto(), Self::Pico | Self::PicoV2 => convnext::Config::pico(), Self::Nano | Self::NanoV2 => convnext::Config::nano(), Self::Tiny | Self::TinyV2 => convnext::Config::tiny(), Self::Small => convnext::Config::small(), Self::Base | Self::BaseV2 => convnext::Config::base(), Self::Large | Self::LargeV2 => convnext::Config::large(), Self::XLarge => convnext::Config::xlarge(), Self::Huge => convnext::Config::huge(), } } } #[derive(Parser)] struct Args { #[arg(long)] model: Option<String>, #[arg(long)] image: String, /// Run on CPU rather than on GPU. #[arg(long)] cpu: bool, #[arg(value_enum, long, default_value_t=Which::Tiny)] which: Which, } pub fn main() -> anyhow::Result<()> { let args = Args::parse(); let device = candle_examples::device(args.cpu)?; let image = candle_examples::imagenet::load_image224(args.image)?.to_device(&device)?; println!("loaded image {image:?}"); let model_file = match args.model { None => { let model_name = args.which.model_filename(); let api = hf_hub::api::sync::Api::new()?; let api = api.model(model_name); api.get("model.safetensors")? } Some(model) => model.into(), }; let vb = unsafe { VarBuilder::from_mmaped_safetensors(&[model_file], DType::F32, &device)? }; let model = convnext::convnext(&args.which.config(), 1000, vb)?; println!("model built"); let logits = model.forward(&image.unsqueeze(0)?)?; let prs = candle_nn::ops::softmax(&logits, D::Minus1)? .i(0)? .to_vec1::<f32>()?; let mut prs = prs.iter().enumerate().collect::<Vec<_>>(); prs.sort_by(|(_, p1), (_, p2)| p2.total_cmp(p1)); for &(category_idx, pr) in prs.iter().take(5) { println!( "{:24}: {:.2}%", candle_examples::imagenet::CLASSES[category_idx], 100. * pr ); } Ok(()) }
candle/candle-examples/examples/convnext/main.rs/0
{ "file_path": "candle/candle-examples/examples/convnext/main.rs", "repo_id": "candle", "token_count": 1926 }
33
# candle-falcon Falcon is a general large language model. ## Running an example Make sure to include the `--use-f32` flag if using CPU, because there isn't a BFloat16 implementation yet. ``` cargo run --example falcon --release -- --prompt "Flying monkeys are" --use-f32 ```
candle/candle-examples/examples/falcon/README.md/0
{ "file_path": "candle/candle-examples/examples/falcon/README.md", "repo_id": "candle", "token_count": 82 }
34
# candle-helium: 2b LLM with CC-BY licensed weights Helium-1 is a lightweight model with around 2B parameters, the preview version currently supports 6 languages, showing strong capabilities in those languages compared to existing open weights models. - [Blog Post](https://kyutai.org/2025/01/13/helium.html) announcing the model release. - [Model card](https://huggingface.co/kyutai/helium-1-preview-2b) on the HuggingFace Hub. ## Running the example ```bash $ cargo run --example helium --release --features cuda -- --prompt 'Write helloworld code in Rust' --sample-len 150 ```
candle/candle-examples/examples/helium/README.md/0
{ "file_path": "candle/candle-examples/examples/helium/README.md", "repo_id": "candle", "token_count": 174 }
35
# candle-llava LLaVA (Large Language-and-Vision Assistant) is an end-to-end trained large multimodal model. This example is from [candle-llava](https://github.com/chenwanqq/candle-llava) The code is based on [https://github.com/haotian-liu/LLaVA](https://github.com/haotian-liu/LLaVA), Hence the llava-hf version of config may perform differently. ## model zoo * [liuhaotian/LLaVA](https://huggingface.co/liuhaotian) * [llava-hf](https://huggingface.co/llava-hf) Right now this has been tested on `liuhaotian/llava-v1.6-vicuna-7b` and `llava-hf/llava-v1.6-vicuna-7b-hf`. Memory usage might have room for optimization. ## Tokenizer Setup The llava-hf models contain a `tokenizer.json` file so can be used directly with the `-hf` command line flag. For the original llava models, you can use the following code to generate the `tokenizer.json` file. ```bash conda create -n llava python=3.10 pip install transformers protobuf conda activate llava python -c "from transformers import AutoTokenizer;tokenizer=AutoTokenizer.from_pretrained('liuhaotian/llava-v1.6-vicuna-7b');tokenizer.save_pretrained('tokenizer')" ``` Then the `tokenizer.json` file should be in `tokenizer/tokenizer.json` (which is the default path). ## eval ```bash cargo run --example llava --features cuda -- --image-file "llava_logo.png" --prompt "is this a cat?" --hf # default args, use llava-hf/llava-v1.6-vicuna-7b-hf. image-file is required^_^ cargo run --example llava --features cuda -- --model-path liuhaotian/llava-v1.6-vicuna-7b --image-file "llava_logo.png" --prompt "is this a cat?" # use liuhaotian/llava-v1.6-vicuna-7b, tokenizer setup should be done ``` ## Major Limitations 1. Currently only support llama-2/vicuna llm. Haven't supoort Mistral yet. 2. There are some ops like split, nonzero and where are not supported by candle. 3. Lack of quantization and LoRA support.
candle/candle-examples/examples/llava/readme.md/0
{ "file_path": "candle/candle-examples/examples/llava/readme.md", "repo_id": "candle", "token_count": 671 }
36
#![allow(dead_code)] // https://huggingface.co/facebook/musicgen-small/tree/main // https://github.com/huggingface/transformers/blob/cd4584e3c809bb9e1392ccd3fe38b40daba5519a/src/transformers/models/musicgen/modeling_musicgen.py // TODO: Add an offline mode. // TODO: Add a KV cache. #[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; mod musicgen_model; use musicgen_model::{GenConfig, MusicgenForConditionalGeneration}; use anyhow::{Error as E, Result}; use candle::{DType, Tensor}; use candle_nn::VarBuilder; use clap::Parser; use hf_hub::{api::sync::Api, Repo, RepoType}; const DTYPE: DType = DType::F32; #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] struct Args { /// Run on CPU rather than on GPU. #[arg(long)] cpu: bool, /// The model weight file, in safetensor format. #[arg(long)] model: Option<String>, /// The tokenizer config. #[arg(long)] tokenizer: Option<String>, #[arg( long, default_value = "90s rock song with loud guitars and heavy drums" )] prompt: String, } fn main() -> Result<()> { use tokenizers::Tokenizer; let args = Args::parse(); let device = candle_examples::device(args.cpu)?; let tokenizer = match args.tokenizer { Some(tokenizer) => std::path::PathBuf::from(tokenizer), None => Api::new()? .model("facebook/musicgen-small".to_string()) .get("tokenizer.json")?, }; let mut tokenizer = Tokenizer::from_file(tokenizer).map_err(E::msg)?; let tokenizer = tokenizer .with_padding(None) .with_truncation(None) .map_err(E::msg)?; let model = match args.model { Some(model) => std::path::PathBuf::from(model), None => Api::new()? .repo(Repo::with_revision( "facebook/musicgen-small".to_string(), RepoType::Model, "refs/pr/13".to_string(), )) .get("model.safetensors")?, }; let vb = unsafe { VarBuilder::from_mmaped_safetensors(&[model], DTYPE, &device)? }; let config = GenConfig::small(); let mut model = MusicgenForConditionalGeneration::load(vb, config)?; let tokens = tokenizer .encode(args.prompt.as_str(), true) .map_err(E::msg)? .get_ids() .to_vec(); println!("tokens: {tokens:?}"); let tokens = Tensor::new(tokens.as_slice(), &device)?.unsqueeze(0)?; println!("{tokens:?}"); let embeds = model.text_encoder.forward(&tokens)?; println!("{embeds}"); Ok(()) }
candle/candle-examples/examples/musicgen/main.rs/0
{ "file_path": "candle/candle-examples/examples/musicgen/main.rs", "repo_id": "candle", "token_count": 1151 }
37
# candle-quantized-llama: Fast Inference of quantized LLaMA models This example provides a quantized LLaMA model similar to [llama.cpp](https://github.com/ggerganov/llama.cpp). This is based on candle built-in quantization methods. Supported features include: - 2-bit, 3-bit, 4-bit, 5-bit, 6-bit and 8-bit integer quantization support. - SIMD optimizations on Apple Silicon and x86. - Support using the `gguf` and `ggml` file formats. The weights are automatically downloaded for you from the [HuggingFace Hub](https://huggingface.co/) on the first run. There are various command line flags to use local files instead, run with `--help` to learn about them. ![Axiom of Choice](./assets/aoc.gif) ## Running some example. ```bash cargo run --example quantized --release -- --prompt "The best thing about coding in rust is " > avx: true, neon: false, simd128: false, f16c: true > temp: 0.80 repeat-penalty: 1.10 repeat-last-n: 64 > loaded 291 tensors (3.79GB) in 2.17s > params: HParams { n_vocab: 32000, n_embd: 4096, n_mult: 256, n_head: 32, n_layer: 32, n_rot: 128, ftype: 2 } > The best thing about coding in rust is 1.) that I don’t need to worry about memory leaks, 2.) speed and 3.) my program will compile even on old machines. ``` Using the mixtral sparse mixture of expert model: ```bash $ cargo run --example quantized --release -- --which mixtral --prompt "Lebesgue's integral is superior to Riemann's because " > avx: true, neon: false, simd128: false, f16c: true > temp: 0.80 repeat-penalty: 1.10 repeat-last-n: 64 > loaded 995 tensors (26.44GB) in 0.03s Lebesgue's integral is superior to Riemann's because 1. it is defined for a wider class of functions, those which are absolutely integrable; 2. the definition does not involve limits in two variables---one being computed before the other (which makes some computations more difficult); and 3. interchange of order of integration is easier to establish than with Riemann's integral. On the other hand, Lebesgue's integral applies only for bounded functions defined on finite intervals; it does not provide numerical values for improper integrals. The latter are best evaluated using Cauchy's limit definition. The reason $f(x) = x^2$ is discontinuous at the ends of its interval of definition, and Riemann's integral requires continuity on the whole of an open interval containing it (see our earlier post), sine no such function exists with this property, is that the endpoints are infinite in measure for Lebesgue's integral. ``` ## Command-line flags Run with `--help` to see all options. - `--which`: specify the model to use, e.g. `7b`, `13-chat`, `7b-code`. - `--prompt interactive`: interactive mode where multiple prompts can be entered. - `--model mymodelfile.gguf`: use a local model file rather than getting one from the hub.
candle/candle-examples/examples/quantized/README.md/0
{ "file_path": "candle/candle-examples/examples/quantized/README.md", "repo_id": "candle", "token_count": 820 }
38
#[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::mpt::{Config, Model as M}; use candle_transformers::models::quantized_mpt::Model as Q; use candle::{DType, Device, Tensor}; use candle_nn::VarBuilder; use candle_transformers::generation::LogitsProcessor; use hf_hub::{api::sync::Api, Repo, RepoType}; use tokenizers::Tokenizer; enum Model { M(M), Q(Q), } impl Model { fn forward(&mut self, xs: &Tensor) -> candle::Result<Tensor> { match self { Self::M(model) => model.forward(xs), Self::Q(model) => model.forward(xs), } } } struct TextGeneration { model: Model, device: Device, tokenizer: Tokenizer, logits_processor: LogitsProcessor, repeat_penalty: f32, repeat_last_n: usize, verbose_prompt: bool, } 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, verbose_prompt: bool, device: &Device, ) -> Self { let logits_processor = LogitsProcessor::new(seed, temp, top_p); Self { model, tokenizer, logits_processor, repeat_penalty, repeat_last_n, verbose_prompt, device: device.clone(), } } fn run(&mut self, prompt: &str, sample_len: usize) -> Result<()> { use std::io::Write; println!("starting the inference loop"); let tokens = self.tokenizer.encode(prompt, true).map_err(E::msg)?; if tokens.is_empty() { anyhow::bail!("Empty prompts are not supported in the phi model.") } if self.verbose_prompt { for (token, id) in tokens.get_tokens().iter().zip(tokens.get_ids().iter()) { let token = token.replace('▁', " ").replace("<0x0A>", "\n"); println!("{id:7} -> '{token}'"); } } let mut tokens = tokens.get_ids().to_vec(); let mut generated_tokens = 0usize; let eos_token = match self.tokenizer.get_vocab(true).get("<|endoftext|>") { Some(token) => *token, None => anyhow::bail!("cannot find the endoftext token"), }; print!("{prompt}"); std::io::stdout().flush()?; let start_gen = std::time::Instant::now(); for index in 0..sample_len { let context_size = if index > 0 { 1 } else { tokens.len() }; let ctxt = &tokens[tokens.len().saturating_sub(context_size)..]; let input = Tensor::new(ctxt, &self.device)?.unsqueeze(0)?; let logits = self.model.forward(&input)?; let logits = logits.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; } let token = self.tokenizer.decode(&[next_token], true).map_err(E::msg)?; print!("{token}"); std::io::stdout().flush()?; } let dt = start_gen.elapsed(); 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, /// Display the token for the specified prompt. #[arg(long)] verbose_prompt: 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 = 1000)] sample_len: usize, #[arg(long)] model_id: Option<String>, #[arg(long)] revision: Option<String>, #[arg(long)] quantized: bool, #[arg(long)] weight_file: Option<String>, #[arg(long)] tokenizer: Option<String>, /// Penalty to be applied for repeating tokens, 1. means no penalty. #[arg(long, default_value_t = 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.to_string(), None => "lmz/candle-replit-code".to_string(), }; let revision = match args.revision { Some(rev) => rev.to_string(), None => "main".to_string(), }; let repo = api.repo(Repo::with_revision(model_id, RepoType::Model, revision)); let tokenizer_filename = match args.tokenizer { Some(file) => std::path::PathBuf::from(file), None => repo.get("tokenizer.json")?, }; let filename = match args.weight_file { Some(weight_file) => std::path::PathBuf::from(weight_file), None => { if args.quantized { repo.get("model-replit-code-v1_5-q4k.gguf")? } else { repo.get("model.safetensors")? } } }; 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 device = candle_examples::device(args.cpu)?; let config = Config::replit_code_v1_5_3b(); let model = if args.quantized { let vb = candle_transformers::quantized_var_builder::VarBuilder::from_gguf(&filename, &device)?; Model::Q(Q::new(&config, vb.pp("transformer"))?) } else { let vb = unsafe { VarBuilder::from_mmaped_safetensors(&[filename], DType::F32, &device)? }; Model::M(M::new(&config, vb.pp("transformer"))?) }; 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, args.verbose_prompt, &device, ); pipeline.run(&args.prompt, args.sample_len)?; Ok(()) }
candle/candle-examples/examples/replit-code/main.rs/0
{ "file_path": "candle/candle-examples/examples/replit-code/main.rs", "repo_id": "candle", "token_count": 3752 }
39
## SigLIP SigLIP is multi-modal text-vision model that improves over CLIP by using a sigmoid based loss, [HuggingFace](https://huggingface.co/google/siglip-base-patch16-224). ### Running an example ``` $ cargo run --features cuda -r --example siglip softmax_image_vec: [2.1912122e-14, 2.3624872e-14, 1.0, 1.0, 2.4787932e-8, 3.2784535e-12] Results for image: candle-examples/examples/stable-diffusion/assets/stable-diffusion-xl.jpg Probability: 0.0000% Text: a cycling race Probability: 0.0000% Text: a photo of two cats Probability: 100.0000% Text: a robot holding a candle Results for image: candle-examples/examples/yolo-v8/assets/bike.jpg Probability: 100.0000% Text: a cycling race Probability: 0.0000% Text: a photo of two cats Probability: 0.0000% Text: a robot holding a candle ```
candle/candle-examples/examples/siglip/README.md/0
{ "file_path": "candle/candle-examples/examples/siglip/README.md", "repo_id": "candle", "token_count": 297 }
40
#[cfg(feature = "accelerate")] extern crate accelerate_src; #[cfg(feature = "mkl")] extern crate intel_mkl_src; use candle_transformers::models::stable_diffusion; use std::ops::Div; use anyhow::{Error as E, Result}; use candle::{DType, Device, IndexOp, Module, Tensor, D}; use clap::Parser; use rand::Rng; use stable_diffusion::vae::AutoEncoderKL; use tokenizers::Tokenizer; #[derive(Parser)] #[command(author, version, about, long_about = None)] struct Args { /// The prompt to be used for image generation. #[arg( long, default_value = "A very realistic photo of a rusty robot walking on a sandy beach" )] prompt: String, #[arg(long, default_value = "")] uncond_prompt: String, /// Run on CPU rather than on GPU. #[arg(long)] cpu: bool, /// Enable tracing (generates a trace-timestamp.json file). #[arg(long)] tracing: bool, /// The height in pixels of the generated image. #[arg(long)] height: Option<usize>, /// The width in pixels of the generated image. #[arg(long)] width: Option<usize>, /// The UNet weight file, in .safetensors format. #[arg(long, value_name = "FILE")] unet_weights: Option<String>, /// The CLIP weight file, in .safetensors format. #[arg(long, value_name = "FILE")] clip_weights: Option<String>, /// The CLIP2 weight file, in .safetensors format. #[arg(long, value_name = "FILE")] clip2_weights: Option<String>, /// The VAE weight file, in .safetensors format. #[arg(long, value_name = "FILE")] vae_weights: Option<String>, #[arg(long, value_name = "FILE")] /// The file specifying the tokenizer to used for tokenization. tokenizer: Option<String>, /// The size of the sliced attention or 0 for automatic slicing (disabled by default) #[arg(long)] sliced_attention_size: Option<usize>, /// The number of steps to run the diffusion for. #[arg(long)] n_steps: Option<usize>, /// The number of samples to generate iteratively. #[arg(long, default_value_t = 1)] num_samples: usize, /// The numbers of samples to generate simultaneously. #[arg[long, default_value_t = 1]] bsize: usize, /// The name of the final image to generate. #[arg(long, value_name = "FILE", default_value = "sd_final.png")] final_image: String, #[arg(long, value_enum, default_value = "v2-1")] sd_version: StableDiffusionVersion, /// Generate intermediary images at each step. #[arg(long, action)] intermediary_images: bool, #[arg(long)] use_flash_attn: bool, #[arg(long)] use_f16: bool, #[arg(long)] guidance_scale: Option<f64>, /// Path to the mask image for inpainting. #[arg(long, value_name = "FILE")] mask_path: Option<String>, /// Path to the image used to initialize the latents. For inpainting, this is the image to be masked. #[arg(long, value_name = "FILE")] img2img: Option<String>, /// The strength, indicates how much to transform the initial image. The /// value must be between 0 and 1, a value of 1 discards the initial image /// information. #[arg(long, default_value_t = 0.8)] img2img_strength: f64, /// The seed to use when generating random samples. #[arg(long)] seed: Option<u64>, /// Force the saved image to update only the masked region #[arg(long)] only_update_masked: bool, } #[derive(Debug, Clone, Copy, clap::ValueEnum, PartialEq, Eq)] enum StableDiffusionVersion { V1_5, V1_5Inpaint, V2_1, V2Inpaint, Xl, XlInpaint, Turbo, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum ModelFile { Tokenizer, Tokenizer2, Clip, Clip2, Unet, Vae, } impl StableDiffusionVersion { fn repo(&self) -> &'static str { match self { Self::XlInpaint => "diffusers/stable-diffusion-xl-1.0-inpainting-0.1", Self::Xl => "stabilityai/stable-diffusion-xl-base-1.0", Self::V2Inpaint => "stabilityai/stable-diffusion-2-inpainting", Self::V2_1 => "stabilityai/stable-diffusion-2-1", Self::V1_5 => "runwayml/stable-diffusion-v1-5", Self::V1_5Inpaint => "stable-diffusion-v1-5/stable-diffusion-inpainting", Self::Turbo => "stabilityai/sdxl-turbo", } } fn unet_file(&self, use_f16: bool) -> &'static str { match self { Self::V1_5 | Self::V1_5Inpaint | Self::V2_1 | Self::V2Inpaint | Self::Xl | Self::XlInpaint | Self::Turbo => { if use_f16 { "unet/diffusion_pytorch_model.fp16.safetensors" } else { "unet/diffusion_pytorch_model.safetensors" } } } } fn vae_file(&self, use_f16: bool) -> &'static str { match self { Self::V1_5 | Self::V1_5Inpaint | Self::V2_1 | Self::V2Inpaint | Self::Xl | Self::XlInpaint | Self::Turbo => { if use_f16 { "vae/diffusion_pytorch_model.fp16.safetensors" } else { "vae/diffusion_pytorch_model.safetensors" } } } } fn clip_file(&self, use_f16: bool) -> &'static str { match self { Self::V1_5 | Self::V1_5Inpaint | Self::V2_1 | Self::V2Inpaint | Self::Xl | Self::XlInpaint | Self::Turbo => { if use_f16 { "text_encoder/model.fp16.safetensors" } else { "text_encoder/model.safetensors" } } } } fn clip2_file(&self, use_f16: bool) -> &'static str { match self { Self::V1_5 | Self::V1_5Inpaint | Self::V2_1 | Self::V2Inpaint | Self::Xl | Self::XlInpaint | Self::Turbo => { if use_f16 { "text_encoder_2/model.fp16.safetensors" } else { "text_encoder_2/model.safetensors" } } } } } impl ModelFile { fn get( &self, filename: Option<String>, version: StableDiffusionVersion, use_f16: bool, ) -> Result<std::path::PathBuf> { use hf_hub::api::sync::Api; match filename { Some(filename) => Ok(std::path::PathBuf::from(filename)), None => { let (repo, path) = match self { Self::Tokenizer => { let tokenizer_repo = match version { StableDiffusionVersion::V1_5 | StableDiffusionVersion::V2_1 | StableDiffusionVersion::V1_5Inpaint | StableDiffusionVersion::V2Inpaint => "openai/clip-vit-base-patch32", StableDiffusionVersion::Xl | StableDiffusionVersion::XlInpaint | StableDiffusionVersion::Turbo => { // This seems similar to the patch32 version except some very small // difference in the split regex. "openai/clip-vit-large-patch14" } }; (tokenizer_repo, "tokenizer.json") } Self::Tokenizer2 => { ("laion/CLIP-ViT-bigG-14-laion2B-39B-b160k", "tokenizer.json") } Self::Clip => (version.repo(), version.clip_file(use_f16)), Self::Clip2 => (version.repo(), version.clip2_file(use_f16)), Self::Unet => (version.repo(), version.unet_file(use_f16)), Self::Vae => { // Override for SDXL when using f16 weights. // See https://github.com/huggingface/candle/issues/1060 if matches!( version, StableDiffusionVersion::Xl | StableDiffusionVersion::Turbo, ) && use_f16 { ( "madebyollin/sdxl-vae-fp16-fix", "diffusion_pytorch_model.safetensors", ) } else { (version.repo(), version.vae_file(use_f16)) } } }; let filename = Api::new()?.model(repo.to_string()).get(path)?; Ok(filename) } } } } fn output_filename( basename: &str, sample_idx: usize, num_samples: usize, timestep_idx: Option<usize>, ) -> String { let filename = if num_samples > 1 { match basename.rsplit_once('.') { None => format!("{basename}.{sample_idx}.png"), Some((filename_no_extension, extension)) => { format!("{filename_no_extension}.{sample_idx}.{extension}") } } } else { basename.to_string() }; match timestep_idx { None => filename, Some(timestep_idx) => match filename.rsplit_once('.') { None => format!("{filename}-{timestep_idx}.png"), Some((filename_no_extension, extension)) => { format!("{filename_no_extension}-{timestep_idx}.{extension}") } }, } } #[allow(clippy::too_many_arguments)] fn save_image( vae: &AutoEncoderKL, latents: &Tensor, vae_scale: f64, bsize: usize, idx: usize, final_image: &str, num_samples: usize, timestep_ids: Option<usize>, ) -> Result<()> { let images = vae.decode(&(latents / vae_scale)?)?; let images = ((images / 2.)? + 0.5)?.to_device(&Device::Cpu)?; let images = (images.clamp(0f32, 1.)? * 255.)?.to_dtype(DType::U8)?; for batch in 0..bsize { let image = images.i(batch)?; let image_filename = output_filename( final_image, (bsize * idx) + batch + 1, batch + num_samples, timestep_ids, ); candle_examples::save_image(&image, image_filename)?; } Ok(()) } #[allow(clippy::too_many_arguments)] fn text_embeddings( prompt: &str, uncond_prompt: &str, tokenizer: Option<String>, clip_weights: Option<String>, clip2_weights: Option<String>, sd_version: StableDiffusionVersion, sd_config: &stable_diffusion::StableDiffusionConfig, use_f16: bool, device: &Device, dtype: DType, use_guide_scale: bool, first: bool, ) -> Result<Tensor> { let tokenizer_file = if first { ModelFile::Tokenizer } else { ModelFile::Tokenizer2 }; let tokenizer = tokenizer_file.get(tokenizer, sd_version, use_f16)?; let tokenizer = Tokenizer::from_file(tokenizer).map_err(E::msg)?; let pad_id = match &sd_config.clip.pad_with { Some(padding) => *tokenizer.get_vocab(true).get(padding.as_str()).unwrap(), None => *tokenizer.get_vocab(true).get("<|endoftext|>").unwrap(), }; println!("Running with prompt \"{prompt}\"."); let mut tokens = tokenizer .encode(prompt, true) .map_err(E::msg)? .get_ids() .to_vec(); if tokens.len() > sd_config.clip.max_position_embeddings { anyhow::bail!( "the prompt is too long, {} > max-tokens ({})", tokens.len(), sd_config.clip.max_position_embeddings ) } while tokens.len() < sd_config.clip.max_position_embeddings { tokens.push(pad_id) } let tokens = Tensor::new(tokens.as_slice(), device)?.unsqueeze(0)?; println!("Building the Clip transformer."); let clip_weights_file = if first { ModelFile::Clip } else { ModelFile::Clip2 }; let clip_weights = if first { clip_weights_file.get(clip_weights, sd_version, use_f16)? } else { clip_weights_file.get(clip2_weights, sd_version, use_f16)? }; let clip_config = if first { &sd_config.clip } else { sd_config.clip2.as_ref().unwrap() }; let text_model = stable_diffusion::build_clip_transformer(clip_config, clip_weights, device, DType::F32)?; let text_embeddings = text_model.forward(&tokens)?; let text_embeddings = if use_guide_scale { let mut uncond_tokens = tokenizer .encode(uncond_prompt, true) .map_err(E::msg)? .get_ids() .to_vec(); if uncond_tokens.len() > sd_config.clip.max_position_embeddings { anyhow::bail!( "the negative prompt is too long, {} > max-tokens ({})", uncond_tokens.len(), sd_config.clip.max_position_embeddings ) } while uncond_tokens.len() < sd_config.clip.max_position_embeddings { uncond_tokens.push(pad_id) } let uncond_tokens = Tensor::new(uncond_tokens.as_slice(), device)?.unsqueeze(0)?; let uncond_embeddings = text_model.forward(&uncond_tokens)?; Tensor::cat(&[uncond_embeddings, text_embeddings], 0)?.to_dtype(dtype)? } else { text_embeddings.to_dtype(dtype)? }; Ok(text_embeddings) } fn image_preprocess<T: AsRef<std::path::Path>>(path: T) -> anyhow::Result<Tensor> { let img = image::ImageReader::open(path)?.decode()?; let (height, width) = (img.height() as usize, img.width() as usize); let height = height - height % 32; let width = width - width % 32; let img = img.resize_to_fill( width as u32, height as u32, image::imageops::FilterType::CatmullRom, ); let img = img.to_rgb8(); let img = img.into_raw(); let img = Tensor::from_vec(img, (height, width, 3), &Device::Cpu)? .permute((2, 0, 1))? .to_dtype(DType::F32)? .affine(2. / 255., -1.)? .unsqueeze(0)?; Ok(img) } /// Convert the mask image to a single channel tensor. Also ensure the image is a multiple of 32 in both dimensions. fn mask_preprocess<T: AsRef<std::path::Path>>(path: T) -> anyhow::Result<Tensor> { let img = image::open(path)?.to_luma8(); let (new_width, new_height) = { let (width, height) = img.dimensions(); (width - width % 32, height - height % 32) }; let img = image::imageops::resize( &img, new_width, new_height, image::imageops::FilterType::CatmullRom, ) .into_raw(); let mask = Tensor::from_vec(img, (new_height as usize, new_width as usize), &Device::Cpu)? .unsqueeze(0)? .to_dtype(DType::F32)? .div(255.0)? .unsqueeze(0)?; Ok(mask) } /// Generates the mask latents, scaled mask and mask_4 for inpainting. Returns a tuple of None if inpainting is not /// being used. #[allow(clippy::too_many_arguments)] fn inpainting_tensors( sd_version: StableDiffusionVersion, mask_path: Option<String>, dtype: DType, device: &Device, use_guide_scale: bool, vae: &AutoEncoderKL, image: Option<Tensor>, vae_scale: f64, ) -> Result<(Option<Tensor>, Option<Tensor>, Option<Tensor>)> { match sd_version { StableDiffusionVersion::XlInpaint | StableDiffusionVersion::V2Inpaint | StableDiffusionVersion::V1_5Inpaint => { let inpaint_mask = mask_path.ok_or_else(|| { anyhow::anyhow!("An inpainting model was requested but mask-path is not provided.") })?; // Get the mask image with shape [1, 1, 128, 128] let mask = mask_preprocess(inpaint_mask)? .to_device(device)? .to_dtype(dtype)?; // Generate the masked image from the image and the mask with shape [1, 3, 1024, 1024] let xmask = mask.le(0.5)?.repeat(&[1, 3, 1, 1])?.to_dtype(dtype)?; let image = &image .ok_or_else(|| anyhow::anyhow!( "An inpainting model was requested but img2img which is used as the input image is not provided." ))?; let masked_img = (image * xmask)?; // Scale down the mask let shape = masked_img.shape(); let (w, h) = (shape.dims()[3] / 8, shape.dims()[2] / 8); let mask = mask.interpolate2d(w, h)?; // shape: [1, 4, 128, 128] let mask_latents = vae.encode(&masked_img)?; let mask_latents = (mask_latents.sample()? * vae_scale)?.to_device(device)?; let mask_4 = mask.as_ref().repeat(&[1, 4, 1, 1])?; let (mask_latents, mask) = if use_guide_scale { ( Tensor::cat(&[&mask_latents, &mask_latents], 0)?, Tensor::cat(&[&mask, &mask], 0)?, ) } else { (mask_latents, mask) }; Ok((Some(mask_latents), Some(mask), Some(mask_4))) } _ => Ok((None, None, None)), } } fn run(args: Args) -> Result<()> { use tracing_chrome::ChromeLayerBuilder; use tracing_subscriber::prelude::*; let Args { prompt, uncond_prompt, cpu, height, width, n_steps, tokenizer, final_image, sliced_attention_size, num_samples, bsize, sd_version, clip_weights, clip2_weights, vae_weights, unet_weights, tracing, use_f16, guidance_scale, use_flash_attn, mask_path, img2img, img2img_strength, seed, .. } = args; if !(0. ..=1.).contains(&img2img_strength) { anyhow::bail!("img2img-strength should be between 0 and 1, got {img2img_strength}") } let _guard = if tracing { let (chrome_layer, guard) = ChromeLayerBuilder::new().build(); tracing_subscriber::registry().with(chrome_layer).init(); Some(guard) } else { None }; let guidance_scale = match guidance_scale { Some(guidance_scale) => guidance_scale, None => match sd_version { StableDiffusionVersion::V1_5 | StableDiffusionVersion::V1_5Inpaint | StableDiffusionVersion::V2_1 | StableDiffusionVersion::V2Inpaint | StableDiffusionVersion::XlInpaint | StableDiffusionVersion::Xl => 7.5, StableDiffusionVersion::Turbo => 0., }, }; let n_steps = match n_steps { Some(n_steps) => n_steps, None => match sd_version { StableDiffusionVersion::V1_5 | StableDiffusionVersion::V1_5Inpaint | StableDiffusionVersion::V2_1 | StableDiffusionVersion::V2Inpaint | StableDiffusionVersion::XlInpaint | StableDiffusionVersion::Xl => 30, StableDiffusionVersion::Turbo => 1, }, }; let dtype = if use_f16 { DType::F16 } else { DType::F32 }; let sd_config = match sd_version { StableDiffusionVersion::V1_5 | StableDiffusionVersion::V1_5Inpaint => { stable_diffusion::StableDiffusionConfig::v1_5(sliced_attention_size, height, width) } StableDiffusionVersion::V2_1 | StableDiffusionVersion::V2Inpaint => { stable_diffusion::StableDiffusionConfig::v2_1(sliced_attention_size, height, width) } StableDiffusionVersion::Xl | StableDiffusionVersion::XlInpaint => { stable_diffusion::StableDiffusionConfig::sdxl(sliced_attention_size, height, width) } StableDiffusionVersion::Turbo => stable_diffusion::StableDiffusionConfig::sdxl_turbo( sliced_attention_size, height, width, ), }; let mut scheduler = sd_config.build_scheduler(n_steps)?; let device = candle_examples::device(cpu)?; // If a seed is not given, generate a random seed and print it let seed = seed.unwrap_or_else(|| { #[cfg(feature = "metal")] { // Metal backend requires seed to be within u32 range rand::rng().random_range(0u64..u32::MAX as u64) } #[cfg(not(feature = "metal"))] { rand::rng().random_range(0u64..u64::MAX) } }); println!("Using seed {seed}"); device.set_seed(seed)?; let use_guide_scale = guidance_scale > 1.0; let which = match sd_version { StableDiffusionVersion::Xl | StableDiffusionVersion::XlInpaint | StableDiffusionVersion::Turbo => vec![true, false], _ => vec![true], }; let text_embeddings = which .iter() .map(|first| { text_embeddings( &prompt, &uncond_prompt, tokenizer.clone(), clip_weights.clone(), clip2_weights.clone(), sd_version, &sd_config, use_f16, &device, dtype, use_guide_scale, *first, ) }) .collect::<Result<Vec<_>>>()?; let text_embeddings = Tensor::cat(&text_embeddings, D::Minus1)?; let text_embeddings = text_embeddings.repeat((bsize, 1, 1))?; println!("{text_embeddings:?}"); println!("Building the autoencoder."); let vae_weights = ModelFile::Vae.get(vae_weights, sd_version, use_f16)?; let vae = sd_config.build_vae(vae_weights, &device, dtype)?; let (image, init_latent_dist) = match &img2img { None => (None, None), Some(image) => { let image = image_preprocess(image)? .to_device(&device)? .to_dtype(dtype)?; (Some(image.clone()), Some(vae.encode(&image)?)) } }; println!("Building the unet."); let unet_weights = ModelFile::Unet.get(unet_weights, sd_version, use_f16)?; let in_channels = match sd_version { StableDiffusionVersion::XlInpaint | StableDiffusionVersion::V2Inpaint | StableDiffusionVersion::V1_5Inpaint => 9, _ => 4, }; let unet = sd_config.build_unet(unet_weights, &device, in_channels, use_flash_attn, dtype)?; let t_start = if img2img.is_some() { n_steps - (n_steps as f64 * img2img_strength) as usize } else { 0 }; let vae_scale = match sd_version { StableDiffusionVersion::V1_5 | StableDiffusionVersion::V1_5Inpaint | StableDiffusionVersion::V2_1 | StableDiffusionVersion::V2Inpaint | StableDiffusionVersion::XlInpaint | StableDiffusionVersion::Xl => 0.18215, StableDiffusionVersion::Turbo => 0.13025, }; let (mask_latents, mask, mask_4) = inpainting_tensors( sd_version, mask_path, dtype, &device, use_guide_scale, &vae, image, vae_scale, )?; for idx in 0..num_samples { let timesteps = scheduler.timesteps().to_vec(); let latents = match &init_latent_dist { Some(init_latent_dist) => { let latents = (init_latent_dist.sample()? * vae_scale)?.to_device(&device)?; if t_start < timesteps.len() { let noise = latents.randn_like(0f64, 1f64)?; scheduler.add_noise(&latents, noise, timesteps[t_start])? } else { latents } } None => { let latents = Tensor::randn( 0f32, 1f32, (bsize, 4, sd_config.height / 8, sd_config.width / 8), &device, )?; // scale the initial noise by the standard deviation required by the scheduler (latents * scheduler.init_noise_sigma())? } }; let mut latents = latents.to_dtype(dtype)?; println!("starting sampling"); for (timestep_index, &timestep) in timesteps.iter().enumerate() { if timestep_index < t_start { continue; } let start_time = std::time::Instant::now(); let latent_model_input = if use_guide_scale { Tensor::cat(&[&latents, &latents], 0)? } else { latents.clone() }; let latent_model_input = scheduler.scale_model_input(latent_model_input, timestep)?; let latent_model_input = match sd_version { StableDiffusionVersion::XlInpaint | StableDiffusionVersion::V2Inpaint | StableDiffusionVersion::V1_5Inpaint => Tensor::cat( &[ &latent_model_input, mask.as_ref().unwrap(), mask_latents.as_ref().unwrap(), ], 1, )?, _ => latent_model_input, } .to_device(&device)?; let noise_pred = unet.forward(&latent_model_input, timestep as f64, &text_embeddings)?; let noise_pred = if use_guide_scale { let noise_pred = noise_pred.chunk(2, 0)?; let (noise_pred_uncond, noise_pred_text) = (&noise_pred[0], &noise_pred[1]); (noise_pred_uncond + ((noise_pred_text - noise_pred_uncond)? * guidance_scale)?)? } else { noise_pred }; latents = scheduler.step(&noise_pred, timestep, &latents)?; let dt = start_time.elapsed().as_secs_f32(); println!("step {}/{n_steps} done, {:.2}s", timestep_index + 1, dt); // Replace all pixels in the unmasked region with the original pixels discarding any changes. if args.only_update_masked { let mask = mask_4.as_ref().unwrap(); let latent_to_keep = mask_latents .as_ref() .unwrap() .get_on_dim(0, 0)? // shape: [4, H, W] .unsqueeze(0)?; // shape: [1, 4, H, W] latents = ((&latents * mask)? + &latent_to_keep * (1.0 - mask))?; } if args.intermediary_images { save_image( &vae, &latents, vae_scale, bsize, idx, &final_image, num_samples, Some(timestep_index + 1), )?; } } println!( "Generating the final image for sample {}/{}.", idx + 1, num_samples ); save_image( &vae, &latents, vae_scale, bsize, idx, &final_image, num_samples, None, )?; } Ok(()) } fn main() -> Result<()> { let args = Args::parse(); run(args) }
candle/candle-examples/examples/stable-diffusion/main.rs/0
{ "file_path": "candle/candle-examples/examples/stable-diffusion/main.rs", "repo_id": "candle", "token_count": 14170 }
41
# candle-vit Vision Transformer (ViT) model implementation following the lines of [vit-base-patch16-224](https://huggingface.co/google/vit-base-patch16-224) This uses a classification head trained on the ImageNet dataset and returns the probabilities for the top-5 classes. ## Running an example ```bash $ cargo run --example vit --release -- --image candle-examples/examples/yolo-v8/assets/bike.jpg loaded image Tensor[dims 3, 224, 224; f32] model built tiger, Panthera tigris : 100.00% tiger cat : 0.00% jaguar, panther, Panthera onca, Felis onca: 0.00% leopard, Panthera pardus: 0.00% lion, king of beasts, Panthera leo: 0.00% ```
candle/candle-examples/examples/vit/README.md/0
{ "file_path": "candle/candle-examples/examples/vit/README.md", "repo_id": "candle", "token_count": 236 }
42
# candle-wuerstchen: Efficient Pretraining of Text-to-Image Models ![anthropomorphic cat dressed as a fire fighter](./assets/cat.jpg) The `wuerstchen` example is a port of the [diffusers implementation](https://github.com/huggingface/diffusers/tree/19edca82f1ff194c07317369a92b470dbae97f34/src/diffusers/pipelines/wuerstchen) for Würstchen v2. The candle implementation reproduces the same structure/files for models and pipelines. Useful resources: - [Official implementation](https://github.com/dome272/Wuerstchen). - [Arxiv paper](https://arxiv.org/abs/2306.00637). - Blog post: [Introducing Würstchen: Fast Diffusion for Image Generation](https://huggingface.co/blog/wuerstchen). ## Getting the weights The weights are automatically downloaded for you from the [HuggingFace Hub](https://huggingface.co/) on the first run. There are various command line flags to use local files instead, run with `--help` to learn about them. ## Running some example. ```bash cargo run --example wuerstchen --release --features cuda,cudnn -- \ --prompt "Anthropomorphic cat dressed as a fire fighter" ``` The final image is named `sd_final.png` by default.
candle/candle-examples/examples/wuerstchen/README.md/0
{ "file_path": "candle/candle-examples/examples/wuerstchen/README.md", "repo_id": "candle", "token_count": 358 }
43
/****************************************************************************** * Copyright (c) 2024, Tri Dao. ******************************************************************************/ #pragma once #include "philox.cuh" #include "utils.h" namespace flash { struct Dropout { const unsigned long long seed, offset; const uint8_t p_dropout_in_uint8_t; __forceinline__ __device__ Dropout(const unsigned long long seed, const unsigned long long offset, const uint8_t p_dropout_in_uint8_t, const int bid, const int hid, const int tid, const int nheads) : seed(seed) , offset(offset + (bid * nheads + hid) * 32 + tid % 32) , p_dropout_in_uint8_t(p_dropout_in_uint8_t) { } template <bool encode_dropout_in_sign_bit=false, typename Engine, typename Layout> __forceinline__ __device__ void apply_dropout(Tensor<Engine, Layout> &tensor_, int block_row_start, int block_col_start, int block_row_stride) { // convert shape from (4, MMA_M, MMA_N) to (8, MMA_M, MMA_N / 2) Tensor tensor = make_tensor(tensor_.data(), flash::convert_layout_acc_dropout(tensor_.layout())); using T = typename Engine::value_type; auto encode_dropout = [](bool keep, T val) { return keep ? val : (encode_dropout_in_sign_bit ? -val : T(0)); }; static_assert(decltype(size<2>(tensor))::value % 2 == 0); const uint16_t p_dropout_8bit_in_uint16_t = uint16_t(p_dropout_in_uint8_t); const uint32_t p_dropout_8bit_in_uint32_t = (uint32_t(p_dropout_8bit_in_uint16_t) << 16) | uint32_t(p_dropout_8bit_in_uint16_t); // if (cute::thread0()) { printf("threshold2 = 0x%x\n", p_dropout_8bit_in_uint32_t); } #pragma unroll for (int m = 0; m < size<1>(tensor); ++m, block_row_start += block_row_stride) { uint2 rowcol = make_uint2(block_row_start, block_col_start); #pragma unroll for (int n = 0; n < size<2>(tensor) / 2; ++n, ++rowcol.y) { // if (cute::thread(32, 0)) { printf("m = %d, n = %d, row = %d, col = %d\n", m, n, int(rowcol.x), int(rowcol.y));} uint4 random_uint4 = flash::philox(seed, reinterpret_cast<unsigned long long&>(rowcol), offset); // if (cute::thread0()) { printf("philox = %u, %d, %d, %d\n", random_uint4.x, random_uint4.y, random_uint4.z, random_uint4.w);} uint8_t (&rnd_8)[16] = reinterpret_cast<uint8_t (&)[16]>(random_uint4); // Special implementation for 16-bit types: we duplicate the threshold to the // low and high 16 bits of a 32-bit value, then use the f16x2 comparison instruction // to get a mask. The low 16 bits of the mask will be either 0xffff or 0x0000, // and the high 16 bits will be either 0xffff or 0x0000, depending on whether // the random value is less than the threshold. // We then do a bit-wise AND between the mask and the original value (in 32-bit). // We're exploiting the fact that floating point comparison is equivalent to integer // comparison, since we're comparing unsigned integers whose top 8-bits are zero. if (!encode_dropout_in_sign_bit && (std::is_same<T, cutlass::half_t>::value || std::is_same<T, cutlass::bfloat16_t>::value)) { uint16_t rnd_16[16]; #pragma unroll for (int i = 0; i < 16; i++) { rnd_16[i] = uint16_t(rnd_8[i]); } uint32_t (&rnd_32)[8] = reinterpret_cast<uint32_t (&)[8]>(rnd_16); #pragma unroll for (int j = 0; j < 2; j++) { Tensor tensor_uint32 = recast<uint32_t>(tensor(_, m, n * 2 + j)); // if (cute::thread0()) { printf("random = 0x%x, 0x%x, 0x%x, 0x%x\n", rnd_32[j * 4 + 0], rnd_32[j * 4 + 1], rnd_32[j * 4 + 2], rnd_32[j * 4 + 3]); } // if (cute::thread0()) { printf("tensor_uint32 = 0x%x, 0x%x, 0x%x, 0x%x\n", tensor_uint32(0), tensor_uint32(1), tensor_uint32(2), tensor_uint32(3)); } #pragma unroll for (int i = 0; i < 4; i++) { uint32_t mask; asm volatile("set.le.u32.f16x2 %0, %1, %2;\n" : "=r"(mask) : "r"(rnd_32[j * 4 + i]), "r"(p_dropout_8bit_in_uint32_t)); tensor_uint32(i) &= mask; } // if (cute::thread0()) { printf("tensor_uint32 = 0x%x, 0x%x, 0x%x, 0x%x\n", tensor_uint32(0), tensor_uint32(1), tensor_uint32(2), tensor_uint32(3)); } } } else { #pragma unroll for (int j = 0; j < 2; j++) { #pragma unroll for (int i = 0; i < 8; i++) { tensor(i, m, n * 2 + j) = encode_dropout(rnd_8[j * 8 + i] <= p_dropout_in_uint8_t, tensor(i, m, n * 2 + j)); } Tensor tensor_uint32 = recast<uint32_t>(tensor(_, m, n * 2 + j)); // if (cute::thread0()) { printf("tensor_uint32 = 0x%x, 0x%x, 0x%x, 0x%x\n", tensor_uint32(0), tensor_uint32(1), tensor_uint32(2), tensor_uint32(3)); } } } // // if ((threadIdx.x == 0) && (blockIdx.x == 0) && (blockIdx.y == 0)) { // // printf("n = %d, ph Philox: %u, %u, %u, %u\n", n, rnd_8.x, rnd_8.y, rnd_8.z, rnd_8.w); // // } } } } }; } // namespace flash
candle/candle-flash-attn/kernels/dropout.h/0
{ "file_path": "candle/candle-flash-attn/kernels/dropout.h", "repo_id": "candle", "token_count": 3021 }
44
/****************************************************************************** * Copyright (c) 2023, Tri Dao. ******************************************************************************/ #pragma once #include <assert.h> #include <stdint.h> #include <stdlib.h> #include <cuda_fp16.h> #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 #include <cuda_bf16.h> #endif #include <cute/tensor.hpp> #include <cutlass/array.h> #include <cutlass/cutlass.h> #include <cutlass/numeric_conversion.h> #include <cutlass/numeric_types.h> //////////////////////////////////////////////////////////////////////////////////////////////////// namespace flash { //////////////////////////////////////////////////////////////////////////////////////////////////// template<typename T> __forceinline__ __device__ uint32_t relu2(const uint32_t x); template<> __forceinline__ __device__ uint32_t relu2<cutlass::half_t>(const uint32_t x) { uint32_t res; const uint32_t zero = 0u; #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 asm volatile("max.f16x2 %0, %1, %2;\n" : "=r"(res) : "r"(x), "r"(zero)); #else asm volatile( \ "{\n" \ "\t .reg .f16x2 sela;\n" \ "\t set.gtu.u32.f16x2 sela, %1, %2;\n" \ "\t and.b32 %0, sela, %1;\n" "}\n" : "=r"(res) : "r"(x), "r"(zero)); #endif return res; } #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 template<> __forceinline__ __device__ uint32_t relu2<cutlass::bfloat16_t>(const uint32_t x) { uint32_t res; const uint32_t zero = 0u; asm volatile("max.bf16x2 %0, %1, %2;\n" : "=r"(res) : "r"(x), "r"(zero)); return res; } #endif //////////////////////////////////////////////////////////////////////////////////////////////////// #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 template<typename T> __forceinline__ __device__ uint32_t convert_relu2(const float2 x); template<> __forceinline__ __device__ uint32_t convert_relu2<cutlass::half_t>(const float2 x) { uint32_t res; const uint32_t a = reinterpret_cast<const uint32_t&>(x.x); const uint32_t b = reinterpret_cast<const uint32_t&>(x.y); asm volatile("cvt.rn.relu.f16x2.f32 %0, %1, %2;\n" : "=r"(res) : "r"(b), "r"(a)); return res; } template<> __forceinline__ __device__ uint32_t convert_relu2<cutlass::bfloat16_t>(const float2 x) { uint32_t res; const uint32_t a = reinterpret_cast<const uint32_t&>(x.x); const uint32_t b = reinterpret_cast<const uint32_t&>(x.y); asm volatile("cvt.rn.relu.bf16x2.f32 %0, %1, %2;\n" : "=r"(res) : "r"(b), "r"(a)); return res; } #endif //////////////////////////////////////////////////////////////////////////////////////////////////// template<typename T> struct MaxOp { __device__ __forceinline__ T operator()(T const & x, T const & y) { return x > y ? x : y; } }; template <> struct MaxOp<float> { // This is slightly faster __device__ __forceinline__ float operator()(float const &x, float const &y) { return max(x, y); } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<typename T> struct SumOp { __device__ __forceinline__ T operator()(T const & x, T const & y) { return x + y; } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<int THREADS> struct Allreduce { static_assert(THREADS == 32 || THREADS == 16 || THREADS == 8 || THREADS == 4); template<typename T, typename Operator> static __device__ __forceinline__ T run(T x, Operator &op) { constexpr int OFFSET = THREADS / 2; x = op(x, __shfl_xor_sync(uint32_t(-1), x, OFFSET)); return Allreduce<OFFSET>::run(x, op); } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<> struct Allreduce<2> { template<typename T, typename Operator> static __device__ __forceinline__ T run(T x, Operator &op) { x = op(x, __shfl_xor_sync(uint32_t(-1), x, 1)); return x; } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<bool A_in_regs=false, bool B_in_regs=false, typename Tensor0, typename Tensor1, typename Tensor2, typename Tensor3, typename Tensor4, typename TiledMma, typename TiledCopyA, typename TiledCopyB, typename ThrCopyA, typename ThrCopyB> __forceinline__ __device__ void gemm(Tensor0 &acc, Tensor1 &tCrA, Tensor2 &tCrB, Tensor3 const& tCsA, Tensor4 const& tCsB, TiledMma tiled_mma, TiledCopyA smem_tiled_copy_A, TiledCopyB smem_tiled_copy_B, ThrCopyA smem_thr_copy_A, ThrCopyB smem_thr_copy_B) { CUTE_STATIC_ASSERT_V(size<1>(tCrA) == size<1>(acc)); // MMA_M CUTE_STATIC_ASSERT_V(size<1>(tCrB) == size<2>(acc)); // MMA_N CUTE_STATIC_ASSERT_V(size<2>(tCrA) == size<2>(tCrB)); // MMA_K Tensor tCrA_copy_view = smem_thr_copy_A.retile_D(tCrA); CUTE_STATIC_ASSERT_V(size<1>(tCsA) == size<1>(tCrA_copy_view)); // M Tensor tCrB_copy_view = smem_thr_copy_B.retile_D(tCrB); CUTE_STATIC_ASSERT_V(size<1>(tCsB) == size<1>(tCrB_copy_view)); // N if (!A_in_regs) { cute::copy(smem_tiled_copy_A, tCsA(_, _, _0{}), tCrA_copy_view(_, _, _0{})); } if (!B_in_regs) { cute::copy(smem_tiled_copy_B, tCsB(_, _, _0{}), tCrB_copy_view(_, _, _0{})); } #pragma unroll for (int i = 0; i < size<2>(tCrA); ++i) { if (i < size<2>(tCrA) - 1) { if (!A_in_regs) { cute::copy(smem_tiled_copy_A, tCsA(_, _, i + 1), tCrA_copy_view(_, _, i + 1)); } if (!B_in_regs) { cute::copy(smem_tiled_copy_B, tCsB(_, _, i + 1), tCrB_copy_view(_, _, i + 1)); } } cute::gemm(tiled_mma, tCrA(_, _, i), tCrB(_, _, i), acc); } } //////////////////////////////////////////////////////////////////////////////////////////////////// template<typename Tensor0, typename Tensor1, typename Tensor2, typename Tensor3, typename TiledMma, typename TiledCopy, typename ThrCopy> __forceinline__ __device__ void gemm_rs(Tensor0 &acc, Tensor1 &tCrA, Tensor2 &tCrB, Tensor3 const& tCsB, TiledMma tiled_mma, TiledCopy smem_tiled_copy_B, ThrCopy smem_thr_copy_B) { CUTE_STATIC_ASSERT_V(size<1>(tCrA) == size<1>(acc)); // MMA_M CUTE_STATIC_ASSERT_V(size<1>(tCrB) == size<2>(acc)); // MMA_N CUTE_STATIC_ASSERT_V(size<2>(tCrA) == size<2>(tCrB)); // MMA_K Tensor tCrB_copy_view = smem_thr_copy_B.retile_D(tCrB); CUTE_STATIC_ASSERT_V(size<1>(tCsB) == size<1>(tCrB_copy_view)); // N cute::copy(smem_tiled_copy_B, tCsB(_, _, _0{}), tCrB_copy_view(_, _, _0{})); #pragma unroll for (int i = 0; i < size<2>(tCrA); ++i) { if (i < size<2>(tCrA) - 1) { cute::copy(smem_tiled_copy_B, tCsB(_, _, i + 1), tCrB_copy_view(_, _, i + 1)); } cute::gemm(tiled_mma, tCrA(_, _, i), tCrB(_, _, i), acc); } } //////////////////////////////////////////////////////////////////////////////////////////////////// // Convert acc_layout from (MMA=4, MMA_M, MMA_N) to (nrow=(2, MMA_M), ncol=(2, MMA_N)) template<typename Layout> __forceinline__ __device__ auto convert_layout_acc_rowcol(Layout acc_layout) { static_assert(decltype(size<0>(acc_layout))::value == 4); static_assert(decltype(rank(acc_layout))::value == 3); auto l = logical_divide(acc_layout, Shape<_2>{}); // ((2, 2), MMA_M, MMA_N) return make_layout(make_layout(get<0, 1>(l), get<1>(l)), make_layout(get<0, 0>(l), get<2>(l))); }; //////////////////////////////////////////////////////////////////////////////////////////////////// // Convert acc_layout from (MMA=4, MMA_M, MMA_N) to ((4, 2), MMA_M, MMA_N / 2) // if using m16n8k16, or to (4, MMA_M, MMA_N) if using m16n8k8. template<typename MMA_traits, typename Layout> __forceinline__ __device__ auto convert_layout_acc_Aregs(Layout acc_layout) { using X = Underscore; static_assert(decltype(size<0>(acc_layout))::value == 4); static_assert(decltype(rank(acc_layout))::value == 3); constexpr int mma_shape_K = get<2>(typename MMA_traits::Shape_MNK{}); static_assert(mma_shape_K == 8 || mma_shape_K == 16); if constexpr (mma_shape_K == 8) { return acc_layout; } else { auto l = logical_divide(acc_layout, Shape<X, X, _2>{}); // (4, MMA_M, (2, MMA_N / 2))) return make_layout(make_layout(get<0>(l), get<2, 0>(l)), get<1>(l), get<2, 1>(l)); } }; //////////////////////////////////////////////////////////////////////////////////////////////////// // Convert acc_layout from (MMA=4, MMA_M, MMA_N) to ((4, 2), MMA_M, MMA_N / 2) template<typename Layout> __forceinline__ __device__ auto convert_layout_acc_dropout(Layout acc_layout) { using X = Underscore; static_assert(decltype(size<0>(acc_layout))::value == 4); static_assert(decltype(rank(acc_layout))::value == 3); auto l = logical_divide(acc_layout, Shape<X, X, _2>{}); // (4, MMA_M, (2, MMA_N / 2))) return make_layout(make_layout(get<0>(l), get<2, 0>(l)), get<1>(l), get<2, 1>(l)); }; //////////////////////////////////////////////////////////////////////////////////////////////////// template <typename To_type, typename Engine, typename Layout> __forceinline__ __device__ auto convert_type(Tensor<Engine, Layout> const &tensor) { using From_type = typename Engine::value_type; constexpr int numel = decltype(size(tensor))::value; cutlass::NumericArrayConverter<To_type, From_type, numel> convert_op; // HACK: this requires tensor to be "contiguous" auto frag = convert_op(*reinterpret_cast<const cutlass::Array<From_type, numel> *>(tensor.data())); return make_tensor(make_rmem_ptr<To_type>(&frag), tensor.layout()); } //////////////////////////////////////////////////////////////////////////////////////////////////// template <typename Engine, typename Layout> __forceinline__ __device__ void relu_(Tensor<Engine, Layout> &tensor) { constexpr int numel = decltype(size(tensor))::value; static_assert(numel % 2 == 0); using value_t = typename Engine::value_type; // HACK: this requires tensor to be "contiguous" Tensor tensor_uint32 = recast<uint32_t>(tensor); #pragma unroll for (int i = 0; i < size(tensor_uint32); ++i) { tensor_uint32(i) = relu2<value_t>(tensor_uint32(i)); } } //////////////////////////////////////////////////////////////////////////////////////////////////// // On SM80 and above, we can fuse fp32 -> fp16/bf16 conversion and relu into 1 instruction template <typename To_type, typename Engine, typename Layout> __forceinline__ __device__ auto convert_type_relu(Tensor<Engine, Layout> const &tensor) { using From_type = typename Engine::value_type; static_assert(std::is_same_v<To_type, cutlass::half_t> || std::is_same_v<To_type, cutlass::bfloat16_t>); static_assert(std::is_same_v<float, From_type>); constexpr int numel = decltype(size(tensor))::value; static_assert(numel % 2 == 0); #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 // HACK: this requires tensor to be "contiguous" Tensor tensor_float2 = recast<float2>(tensor); Tensor out_uint32 = make_tensor<uint32_t>(tensor_float2.layout()); #pragma unroll for (int i = 0; i < size(out_uint32); ++i) { out_uint32(i) = convert_relu2<To_type>(tensor_float2(i)); } Tensor out = make_tensor(make_rmem_ptr<To_type>(out_uint32.data()), tensor.layout()); #else Tensor out = flash::convert_type<To_type>(tensor); flash::relu_(out); #endif return out; } //////////////////////////////////////////////////////////////////////////////////////////////////// // Blocks until all but N previous cp.async.commit_group operations have committed. // This differs from cute::cp_async_wait in that when N = 0 we don't call cp.async.wait_all // (which is equivalent to commit_group then wait_group 0). // Instead we just call cp.async.wait_group 0, which is slightly faster. // https://github.com/NVIDIA/cutlass/blob/master/include/cute/arch/copy_sm80.hpp#L113 template <int N> CUTE_HOST_DEVICE void cp_async_wait() { #if defined(CUTE_ARCH_CP_ASYNC_SM80_ENABLED) asm volatile("cp.async.wait_group %0;\n" :: "n"(N)); #endif } //////////////////////////////////////////////////////////////////////////////////////////////////// template <bool Is_even_MN=true, bool Is_even_K=true, bool Clear_OOB_MN=false, bool Clear_OOB_K=true, typename TiledCopy, typename Engine0, typename Layout0, typename Engine1, typename Layout1, typename Engine2, typename Layout2, typename Engine3, typename Layout3> __forceinline__ __device__ void copy(TiledCopy tiled_copy, Tensor<Engine0, Layout0> const &S, Tensor<Engine1, Layout1> &D, Tensor<Engine2, Layout2> const &identity_MN, Tensor<Engine3, Layout3> const &predicate_K, const int max_MN=0) { CUTE_STATIC_ASSERT_V(rank(S) == Int<3>{}); CUTE_STATIC_ASSERT_V(rank(D) == Int<3>{}); CUTE_STATIC_ASSERT_V(size<0>(S) == size<0>(D)); // MMA CUTE_STATIC_ASSERT_V(size<1>(S) == size<1>(D)); // MMA_M CUTE_STATIC_ASSERT_V(size<2>(S) == size<2>(D)); // MMA_K // There's no case where !Clear_OOB_K && Clear_OOB_MN static_assert(!(Clear_OOB_MN && !Clear_OOB_K)); #pragma unroll for (int m = 0; m < size<1>(S); ++m) { if (Is_even_MN || get<0>(identity_MN(0, m, 0)) < max_MN) { #pragma unroll for (int k = 0; k < size<2>(S); ++k) { if (Is_even_K || predicate_K(k)) { cute::copy(tiled_copy, S(_, m, k), D(_, m, k)); } else if (Clear_OOB_K) { cute::clear(D(_, m, k)); } } } else if (Clear_OOB_MN) { cute::clear(D(_, m, _)); } } // TD [2023-04-13]: Strange that the code below can cause race condition. // I think it's because the copies are under an if statement. // if (Is_even_K) { // #pragma unroll // for (int m = 0; m < size<1>(S); ++m) { // if (Is_even_MN || get<0>(identity_MN(0, m, 0)) < max_MN) { // copy(tiled_copy, S(_, m, _), D(_, m, _)); // } else if (Clear_OOB_MN) { // clear(D(_, m, _)); // } // } // } else { // It's slightly faster in this case if iterate over K first // #pragma unroll // for (int k = 0; k < size<2>(S); ++k) { // if (predicate_K(k)) { // #pragma unroll // for (int m = 0; m < size<1>(S); ++m) { // if (Is_even_MN || get<0>(identity_MN(0, m, 0)) < max_MN) { // copy(tiled_copy, S(_, m, k), D(_, m, k)); // } else if (Clear_OOB_MN) { // clear(D(_, m, k)); // } // } // } else if (Clear_OOB_K) { // There's no case where !Clear_OOB_K && Clear_OOB_MN // if (Clear_OOB_MN || Is_even_MN) { // clear(D(_, _, k)); // } else { // #pragma unroll // for (int m = 0; m < size<1>(S); ++m) { // if (!(Is_even_MN || get<0>(identity_MN(0, m, 0)) < max_MN)) { // clear(D(_, m, k)); // } // } // } // } // } // } } //////////////////////////////////////////////////////////////////////////////////////////////////// template <bool Is_even_K=true, typename Engine0, typename Layout0, typename Engine1, typename Layout1, typename Engine2, typename Layout2, typename Engine3, typename Layout3> __forceinline__ __device__ void copy_w_min_idx(Tensor<Engine0, Layout0> const &S, Tensor<Engine1, Layout1> &D, Tensor<Engine2, Layout2> const &identity_MN, Tensor<Engine3, Layout3> const &predicate_K, const int max_MN=0, const int min_MN=0) { CUTE_STATIC_ASSERT_V(rank(S) == Int<3>{}); CUTE_STATIC_ASSERT_V(rank(D) == Int<3>{}); CUTE_STATIC_ASSERT_V(size<0>(S) == size<0>(D)); // MMA CUTE_STATIC_ASSERT_V(size<1>(S) == size<1>(D)); // MMA_M CUTE_STATIC_ASSERT_V(size<2>(S) == size<2>(D)); // MMA_K // if (threadIdx.x == 0 && blockIdx.z == 0) { printf("blockIdx.y = %d, max_MN = %d, min_MN = %d\n", blockIdx.y, max_MN, min_MN); } #pragma unroll for (int m = 0; m < size<1>(S); ++m) { // if (threadIdx.x == 0 && blockIdx.z == 0) { printf("blockIdx.y = %d, m = %d\n", blockIdx.y, get<0>(identity_MN(0, m, 0))); } if (get<0>(identity_MN(0, m, 0)) >= min_MN && get<0>(identity_MN(0, m, 0)) < max_MN) { // if (threadIdx.x == 0 && blockIdx.z == 0) { printf("Inner loop, blockIdx.y = %d, m = %d\n", blockIdx.y, get<0>(identity_MN(0, m, 0))); } #pragma unroll for (int k = 0; k < size<2>(S); ++k) { if (Is_even_K || predicate_K(k)) { cute::copy(S(_, m, k), D(_, m, k)); } } } } } //////////////////////////////////////////////////////////////////////////////////////////////////// template <typename Engine, typename Layout> __forceinline__ __device__ void apply_softcap(Tensor<Engine, Layout> &tensor, const float softcap){ #pragma unroll for (int i = 0; i < size(tensor); ++i) { tensor(i) = cutlass::fast_tanh(tensor(i) * softcap); } } template <typename Engine0, typename Layout0, typename Engine1, typename Layout1> __forceinline__ __device__ void calculate_dtanh(Tensor<Engine0, Layout0> &src_tensor, Tensor<Engine1, Layout1> &dst_tensor, const float softcap){ #pragma unroll for (int i = 0; i < size(src_tensor); ++i) { dst_tensor(i) = (1.f - (src_tensor(i) * src_tensor(i))) * softcap; } } //////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace flash
candle/candle-flash-attn/kernels/utils.h/0
{ "file_path": "candle/candle-flash-attn/kernels/utils.h", "repo_id": "candle", "token_count": 8100 }
45
mod ptx; #[repr(u32)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Id { Affine, Binary, Cast, Conv, Fill, Indexing, Quantized, Reduce, Sort, Ternary, Unary, } pub const ALL_IDS: [Id; 11] = [ Id::Affine, Id::Binary, Id::Cast, Id::Conv, Id::Fill, Id::Indexing, Id::Quantized, Id::Reduce, Id::Sort, Id::Ternary, Id::Unary, ]; pub struct Module { index: usize, ptx: &'static str, } impl Module { pub fn index(&self) -> usize { self.index } pub fn ptx(&self) -> &'static str { self.ptx } } const fn module_index(id: Id) -> usize { let mut i = 0; while i < ALL_IDS.len() { if ALL_IDS[i] as u32 == id as u32 { return i; } i += 1; } panic!("id not found") } macro_rules! mdl { ($cst:ident, $id:ident) => { pub const $cst: Module = Module { index: module_index(Id::$id), ptx: ptx::$cst, }; }; } mdl!(AFFINE, Affine); mdl!(BINARY, Binary); mdl!(CAST, Cast); mdl!(CONV, Conv); mdl!(FILL, Fill); mdl!(INDEXING, Indexing); mdl!(QUANTIZED, Quantized); mdl!(REDUCE, Reduce); mdl!(SORT, Sort); mdl!(TERNARY, Ternary); mdl!(UNARY, Unary);
candle/candle-kernels/src/lib.rs/0
{ "file_path": "candle/candle-kernels/src/lib.rs", "repo_id": "candle", "token_count": 675 }
46
use metal::{ Buffer, CompileOptions, ComputeCommandEncoderRef, ComputePipelineState, Device, Function, FunctionConstantValues, Library, MTLDataType, MTLSize, NSUInteger, }; use std::collections::HashMap; use std::ffi::c_void; use std::sync::RwLock; pub mod mlx_gemm; pub mod sort; pub mod utils; pub use mlx_gemm::{call_mlx_gemm, GemmDType}; pub use sort::{call_arg_sort, call_mlx_arg_sort}; pub use utils::BufferOffset; use utils::{get_block_dims, linear_split, EncoderParam, EncoderProvider}; const AFFINE: &str = include_str!("affine.metal"); const BINARY: &str = include_str!("binary.metal"); const CAST: &str = include_str!("cast.metal"); const CONV: &str = include_str!("conv.metal"); const FILL: &str = include_str!("fill.metal"); const INDEXING: &str = include_str!("indexing.metal"); const MLX_GEMM: &str = include_str!("mlx_gemm.metal"); const MLX_SORT: &str = include_str!("mlx_sort.metal"); const QUANTIZED: &str = include_str!("quantized.metal"); const RANDOM: &str = include_str!("random.metal"); const REDUCE: &str = include_str!("reduce.metal"); const SORT: &str = include_str!("sort.metal"); const TERNARY: &str = include_str!("ternary.metal"); const UNARY: &str = include_str!("unary.metal"); const SDPA: &str = include_str!("scaled_dot_product_attention.metal"); #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum DType { BF16, F16, F32, I64, U32, U8, } impl DType { fn size_in_bytes(&self) -> usize { match self { Self::U8 => 1, Self::U32 => 4, Self::I64 => 8, Self::BF16 => 2, Self::F16 => 2, Self::F32 => 4, } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Source { Affine, Binary, Cast, Conv, Fill, Gemm, Indexing, MlxSort, Quantized, Random, Reduce, Sort, Ternary, Unary, Sdpa, } pub mod copy2d { pub struct Kernel(pub &'static str); pub const FLOAT: Kernel = Kernel("copy2d_f32"); pub const HALF: Kernel = Kernel("copy2d_f16"); pub const BFLOAT: Kernel = Kernel("copy2d_bf16"); pub const I64: Kernel = Kernel("copy2d_i64"); pub const U32: Kernel = Kernel("copy2d_u32"); pub const U8: Kernel = Kernel("copy2d_u8"); } macro_rules! ops{ ($($name:ident),+) => { pub mod contiguous { pub struct Kernel(pub &'static str); $( pub mod $name { use super::Kernel; pub const FLOAT: Kernel = Kernel(concat!(stringify!($name), "_f32")); pub const HALF: Kernel = Kernel(concat!(stringify!($name), "_f16")); pub const BFLOAT: Kernel = Kernel(concat!(stringify!($name), "_bf16")); pub const I64: Kernel = Kernel(concat!(stringify!($name), "_i64")); pub const U32: Kernel = Kernel(concat!(stringify!($name), "_u32")); pub const U8: Kernel = Kernel(concat!(stringify!($name), "_u8")); } )+ pub mod copy { use super::Kernel; pub const FLOAT: Kernel = Kernel("copy_f32"); pub const HALF: Kernel = Kernel("copy_f16"); pub const BFLOAT: Kernel = Kernel("copy_bf16"); pub const I64: Kernel = Kernel("copy_i64"); pub const U32: Kernel = Kernel("copy_u32"); pub const U8: Kernel = Kernel("copy_u8"); } } pub mod contiguous_tiled { pub struct Kernel(pub &'static str); $( pub mod $name { use super::Kernel; pub const FLOAT: Kernel = Kernel(concat!(stringify!($name), "_f32_tiled")); pub const HALF: Kernel = Kernel(concat!(stringify!($name), "_f16_tiled")); pub const BFLOAT: Kernel = Kernel(concat!(stringify!($name), "_bf16_tiled")); pub const I64: Kernel = Kernel(concat!(stringify!($name), "_i64_tiled")); pub const U32: Kernel = Kernel(concat!(stringify!($name), "_u32_tiled")); pub const U8: Kernel = Kernel(concat!(stringify!($name), "_u8_tiled")); } )+ pub mod copy { use super::Kernel; pub const FLOAT: Kernel = Kernel("copy_f32_tiled"); pub const HALF: Kernel = Kernel("copy_f16_tiled"); pub const BFLOAT: Kernel = Kernel("copy_bf16_tiled"); pub const I64: Kernel = Kernel("copy_i64_tiled"); pub const U32: Kernel = Kernel("copy_u32_tiled"); pub const U8: Kernel = Kernel("copy_u8_tiled"); } } pub mod strided { pub struct Kernel(pub &'static str); $( pub mod $name { use super::Kernel; pub const FLOAT: Kernel = Kernel(concat!(stringify!($name), "_f32_strided")); pub const HALF: Kernel = Kernel(concat!(stringify!($name), "_f16_strided")); pub const BFLOAT: Kernel = Kernel(concat!(stringify!($name), "_bf16_strided")); pub const I64: Kernel = Kernel(concat!(stringify!($name), "_i64_strided")); pub const U32: Kernel = Kernel(concat!(stringify!($name), "_u32_strided")); pub const U8: Kernel = Kernel(concat!(stringify!($name), "_u8_strided")); } )+ pub mod copy { use super::Kernel; pub const FLOAT: Kernel = Kernel("copy_f32_strided"); pub const HALF: Kernel = Kernel("copy_f16_strided"); pub const BFLOAT: Kernel = Kernel("copy_bf16_strided"); pub const I64: Kernel = Kernel("copy_i64_strided"); pub const U32: Kernel = Kernel("copy_u32_strided"); pub const U8: Kernel = Kernel("copy_u8_strided"); } } }; } pub mod unary { ops!( cos, sin, exp, sqr, sqrt, neg, log, gelu, abs, ceil, floor, relu, round, erf, gelu_erf, tanh, recip, silu, sign, sigmoid, const_set ); } pub mod binary { ops!(add, sub, mul, div, min, max, eq, ne, le, lt, ge, gt); } #[derive(thiserror::Error, Debug)] pub enum MetalKernelError { #[error("Could not lock kernel map: {0}")] LockError(String), #[error("Error while loading library: {0}")] LoadLibraryError(String), #[error("Error while loading function: {0}")] LoadFunctionError(String), #[error("Failed to create compute function")] FailedToCreateComputeFunction, #[error("Failed to create pipeline")] FailedToCreatePipeline(String), #[error("Invalid matmul arguments {lhs_stride:?} {rhs_stride:?} {mnk:?}")] MatMulNonContiguous { lhs_stride: Vec<usize>, rhs_stride: Vec<usize>, mnk: (usize, usize, usize), }, #[error("Sdpa {variation} head size was {got}, expectd {expected:?}")] SdpaHeadSizeMismatch { variation: &'static str, got: usize, expected: Vec<usize>, }, #[error("Sdpa {variation} got dtype {got:?}")] SdpaHeadDTypeMismatch { variation: &'static str, got: SdpaDType, }, } impl<T> From<std::sync::PoisonError<T>> for MetalKernelError { fn from(e: std::sync::PoisonError<T>) -> Self { Self::LockError(e.to_string()) } } #[derive(Debug, Clone)] pub enum KernelName { Ref(&'static str), Value(String), } impl AsRef<str> for KernelName { fn as_ref(&self) -> &str { match self { Self::Ref(r) => r, Self::Value(v) => v.as_str(), } } } impl std::hash::Hash for KernelName { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { match self { Self::Ref(r) => r.hash(state), Self::Value(v) => v.hash(state), } } } impl PartialEq for KernelName { fn eq(&self, other: &Self) -> bool { let v1: &str = self.as_ref(); let v2: &str = other.as_ref(); v1 == v2 } } impl Eq for KernelName {} impl From<&'static str> for KernelName { fn from(value: &'static str) -> Self { Self::Ref(value) } } impl From<String> for KernelName { fn from(value: String) -> Self { Self::Value(value) } } type Libraries = HashMap<Source, Library>; type Pipelines = HashMap<(KernelName, Option<ConstantValues>), ComputePipelineState>; #[derive(Debug)] pub struct Kernels { libraries: RwLock<Libraries>, pipelines: RwLock<Pipelines>, } impl Default for Kernels { fn default() -> Self { Self::new() } } impl Kernels { pub fn new() -> Self { let libraries = RwLock::new(Libraries::new()); let pipelines = RwLock::new(Pipelines::new()); Self { libraries, pipelines, } } fn get_library_source(&self, source: Source) -> &'static str { match source { Source::Affine => AFFINE, Source::Binary => BINARY, Source::Cast => CAST, Source::Conv => CONV, Source::Fill => FILL, Source::Gemm => MLX_GEMM, Source::Indexing => INDEXING, Source::MlxSort => MLX_SORT, Source::Quantized => QUANTIZED, Source::Random => RANDOM, Source::Reduce => REDUCE, Source::Sort => SORT, Source::Ternary => TERNARY, Source::Unary => UNARY, Source::Sdpa => SDPA, } } /// Load the give library from its [`source`]. /// If this has been previously loaded it will just fetch it from cache. pub fn load_library( &self, device: &Device, source: Source, ) -> Result<Library, MetalKernelError> { let mut libraries = self.libraries.write()?; if let Some(lib) = libraries.get(&source) { Ok(lib.clone()) } else { let lib = { let source_content = self.get_library_source(source); device .new_library_with_source(source_content, &CompileOptions::new()) .map_err(|e| MetalKernelError::LoadLibraryError(e.to_string()))? }; libraries.insert(source, lib.clone()); Ok(lib) } } fn load_function( &self, device: &Device, source: Source, name: &str, constants: Option<FunctionConstantValues>, ) -> Result<Function, MetalKernelError> { let func = self .load_library(device, source)? .get_function(name, constants) .map_err(|e| MetalKernelError::LoadFunctionError(e.to_string()))?; Ok(func) } /// Load the give pipeline /// loads the library from source, then gets the function [`name`] from /// that source fn load_pipeline_with_constants( &self, device: &Device, source: Source, name: impl Into<KernelName>, constants: Option<ConstantValues>, ) -> Result<ComputePipelineState, MetalKernelError> { let mut pipelines = self.pipelines.write()?; let key = (name.into(), constants); if let Some(pipeline) = pipelines.get(&key) { Ok(pipeline.clone()) } else { let (name, constants) = key; let func = self.load_function( device, source, name.as_ref(), constants.as_ref().map(|c| c.function_constant_values()), )?; let pipeline = device .new_compute_pipeline_state_with_function(&func) .map_err(|e| MetalKernelError::FailedToCreatePipeline(e.to_string()))?; pipelines.insert((name, constants), pipeline.clone()); Ok(pipeline) } } /// Load the give pipeline /// loads the library from source, then gets the function [`name`] from /// that source (without constants) pub fn load_pipeline( &self, device: &Device, source: Source, name: impl Into<KernelName>, ) -> Result<ComputePipelineState, MetalKernelError> { self.load_pipeline_with_constants(device, source, name, None) } } #[allow(clippy::too_many_arguments)] pub fn call_copy2d( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, name: copy2d::Kernel, input: &Buffer, output: &Buffer, d1: usize, d2: usize, src_s: usize, dst_s: usize, src_o_in_bytes: usize, dst_o_in_bytes: usize, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Unary, name.0)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, ( d1 as i64, d2 as i64, src_s as i64, dst_s as i64, (input, src_o_in_bytes), (output, dst_o_in_bytes) ) ); let grid_dims = MTLSize { width: d1 as u64, height: d2 as u64, depth: 1, }; let group_dims = get_block_dims(d1 as u64, d2 as u64, 1); encoder.use_resource(input, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_threads(grid_dims, group_dims); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_const_set_contiguous_tiled( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, kernel_name: unary::contiguous_tiled::Kernel, length: usize, input: impl EncoderParam, output: BufferOffset, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Unary, kernel_name.0)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); let tile_size = 2; let tiles = length.div_ceil(tile_size); encoder.set_compute_pipeline_state(&pipeline); set_params!(encoder, (length, input, &output)); let (thread_group_count, thread_group_size) = linear_split(&pipeline, tiles); encoder.use_resource(output.buffer, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_const_set_contiguous( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, kernel_name: unary::contiguous::Kernel, length: usize, input: impl EncoderParam, output: BufferOffset, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Unary, kernel_name.0)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!(encoder, (length, input, &output)); let (thread_group_count, thread_group_size) = linear_split(&pipeline, length); encoder.use_resource(output.buffer, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_const_set_strided( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, name: unary::strided::Kernel, shape: &[usize], input: impl EncoderParam, strides: &[usize], output: BufferOffset, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Unary, name.0)?; let length: usize = shape.iter().product(); let num_dims: usize = shape.len(); let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); let (thread_group_count, thread_group_size) = linear_split(&pipeline, length); encoder.set_compute_pipeline_state(&pipeline); set_params!(encoder, (length, num_dims, shape, strides, input, &output)); encoder.use_resource(output.buffer, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_unary_contiguous_tiled( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, kernel_name: unary::contiguous_tiled::Kernel, length: usize, input: BufferOffset, output: &Buffer, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Unary, kernel_name.0)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); let tile_size = 2; let tiles = length.div_ceil(tile_size); encoder.set_compute_pipeline_state(&pipeline); set_params!(encoder, (length, &input, output)); let (thread_group_count, thread_group_size) = linear_split(&pipeline, tiles); encoder.use_resource(input.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_unary_contiguous( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, kernel_name: unary::contiguous::Kernel, length: usize, input: BufferOffset, output: &Buffer, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Unary, kernel_name.0)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!(encoder, (length, &input, output)); let (thread_group_count, thread_group_size) = linear_split(&pipeline, length); encoder.use_resource(input.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_unary_strided( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, name: unary::strided::Kernel, shape: &[usize], input: BufferOffset, strides: &[usize], output: BufferOffset, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Unary, name.0)?; let length: usize = shape.iter().product(); let num_dims: usize = shape.len(); let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); let (thread_group_count, thread_group_size) = linear_split(&pipeline, length); encoder.set_compute_pipeline_state(&pipeline); set_params!(encoder, (length, num_dims, shape, strides, &input, &output)); encoder.use_resource(input.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(output.buffer, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_binary_contiguous( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, kernel_name: binary::contiguous::Kernel, length: usize, left: BufferOffset, right: BufferOffset, output: &Buffer, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Binary, kernel_name.0)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!(encoder, (length, &left, &right, output)); let (thread_group_count, thread_group_size) = linear_split(&pipeline, length); encoder.use_resource(left.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(right.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_binary_strided( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, name: binary::strided::Kernel, shape: &[usize], left_input: BufferOffset, left_strides: &[usize], right_input: BufferOffset, right_strides: &[usize], output: &Buffer, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Binary, name.0)?; let num_dims: usize = shape.len(); let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); let width: usize = shape.iter().product(); let length: usize = shape.iter().product(); let (thread_group_count, thread_group_size) = linear_split(&pipeline, width); encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, ( length, num_dims, shape, left_strides, right_strides, &left_input, &right_input, output ) ); encoder.use_resource(left_input.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(right_input.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_cast_contiguous( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, kernel_name: &'static str, length: usize, input: BufferOffset, output: &Buffer, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Cast, kernel_name)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!(encoder, (length, &input, output)); let (thread_group_count, thread_group_size) = linear_split(&pipeline, length); encoder.use_resource(input.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_cast_strided( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, kernel_name: &'static str, shape: &[usize], input: BufferOffset, input_strides: &[usize], output: &Buffer, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Cast, kernel_name)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); let length: usize = shape.iter().product(); set_params!( encoder, (length, shape.len(), shape, input_strides, &input, output) ); let (thread_group_count, thread_group_size) = linear_split(&pipeline, length); encoder.use_resource(input.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_reduce_contiguous( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, kernel_name: &'static str, shape: &[usize], out_length: usize, input: BufferOffset, output: &Buffer, ) -> Result<(), MetalKernelError> { let length = shape.iter().product::<usize>(); let num_dims = shape.len(); let work_per_threadgroup = length / out_length; let pipeline = kernels.load_pipeline(device, Source::Reduce, kernel_name)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, ( length, num_dims, shape, work_per_threadgroup, &input, output ) ); let thread_group_count = MTLSize { width: out_length as u64, height: 1, depth: 1, }; let width = std::cmp::min( pipeline.max_total_threads_per_threadgroup(), (work_per_threadgroup / 2).next_power_of_two() as NSUInteger, ); let thread_group_size = MTLSize { width, height: 1, depth: 1, }; encoder.use_resource(input.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_reduce_strided( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, kernel_name: &'static str, shape: &[usize], strides: &[usize], out_length: usize, input: BufferOffset, output: &Buffer, ) -> Result<(), MetalKernelError> { let length: usize = shape.iter().product(); let num_dims = shape.len(); let work_per_threadgroup = length / out_length; let pipeline = kernels.load_pipeline(device, Source::Reduce, kernel_name)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, ( length, num_dims, shape, strides, work_per_threadgroup, &input, output ) ); let thread_group_count = MTLSize { width: out_length as u64, height: 1, depth: 1, }; let width = std::cmp::min( pipeline.max_total_threads_per_threadgroup(), (work_per_threadgroup / 2).next_power_of_two() as NSUInteger, ); let thread_group_size = MTLSize { width, height: 1, depth: 1, }; encoder.use_resource(input.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_last_softmax( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, kernel_name: &'static str, length: usize, elements: usize, input: &Buffer, input_offset: usize, output: &Buffer, ) -> Result<(), MetalKernelError> { let work_per_threadgroup = elements; let pipeline = kernels.load_pipeline(device, Source::Reduce, kernel_name)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, (length, work_per_threadgroup, (input, input_offset), output) ); let out_length = length / work_per_threadgroup; let thread_group_count = MTLSize { width: out_length as NSUInteger, height: 1, depth: 1, }; let width = std::cmp::min( pipeline.max_total_threads_per_threadgroup(), (work_per_threadgroup / 2).next_power_of_two() as NSUInteger, ); let thread_group_size = MTLSize { width, height: 1, depth: 1, }; encoder.use_resource(input, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_rms_norm( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, kernel_name: &'static str, length: usize, elements_to_sum: usize, eps: f32, input: &Buffer, input_offset: usize, alpha: &Buffer, alpha_offset: usize, output: &Buffer, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Reduce, kernel_name)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, ( length, elements_to_sum, (input, input_offset), output, (alpha, alpha_offset), eps ) ); let out_length = length / elements_to_sum; let thread_group_count = MTLSize { width: out_length as u64, height: 1, depth: 1, }; let width = std::cmp::min( pipeline.max_total_threads_per_threadgroup(), elements_to_sum as u64, ) .next_power_of_two(); let thread_group_size = MTLSize { width, height: 1, depth: 1, }; encoder.use_resource(input, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.set_threadgroup_memory_length(0, (width * 4).max(16) as u64); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_layer_norm( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, kernel_name: &'static str, length: usize, elements_to_sum: usize, eps: f32, input: &Buffer, input_offset: usize, alpha: &Buffer, alpha_offset: usize, beta: &Buffer, beta_offset: usize, output: &Buffer, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Reduce, kernel_name)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, ( length, elements_to_sum, (input, input_offset), output, (alpha, alpha_offset), (beta, beta_offset), eps ) ); let out_length = length / elements_to_sum; let thread_group_count = MTLSize { width: out_length as u64, height: 1, depth: 1, }; let width = std::cmp::min( pipeline.max_total_threads_per_threadgroup(), elements_to_sum as u64, ) .next_power_of_two(); let thread_group_size = MTLSize { width, height: 1, depth: 1, }; encoder.use_resource(input, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.set_threadgroup_memory_length(0, (width * 8).max(32) as u64); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_rope_i( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, kernel_name: &'static str, bh: usize, td: usize, stride_b: usize, src: &Buffer, src_offset: usize, cos: &Buffer, cos_offset: usize, sin: &Buffer, sin_offset: usize, output: &Buffer, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Reduce, kernel_name)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, ( bh, td, stride_b, (src, src_offset), (cos, cos_offset), (sin, sin_offset), output ) ); let (thread_group_count, thread_group_size) = linear_split(&pipeline, (bh * td) / 2); encoder.use_resource(src, metal::MTLResourceUsage::Read); encoder.use_resource(cos, metal::MTLResourceUsage::Read); encoder.use_resource(sin, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_rope_thd( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, kernel_name: &'static str, b: usize, t: usize, h: usize, d: usize, stride_b: usize, src: &Buffer, src_offset: usize, cos: &Buffer, cos_offset: usize, sin: &Buffer, sin_offset: usize, output: &Buffer, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Reduce, kernel_name)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, ( b, t, h, d, stride_b, (src, src_offset), (cos, cos_offset), (sin, sin_offset), output ) ); let (thread_group_count, thread_group_size) = linear_split(&pipeline, (b * t * h * d) / 2); encoder.use_resource(src, metal::MTLResourceUsage::Read); encoder.use_resource(cos, metal::MTLResourceUsage::Read); encoder.use_resource(sin, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_rope( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, kernel_name: &'static str, bh: usize, td: usize, d: usize, stride_b: usize, src: &Buffer, src_offset: usize, cos: &Buffer, cos_offset: usize, sin: &Buffer, sin_offset: usize, output: &Buffer, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Reduce, kernel_name)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, ( bh, td, d, stride_b, (src, src_offset), (cos, cos_offset), (sin, sin_offset), output ) ); let (thread_group_count, thread_group_size) = linear_split(&pipeline, (bh * td) / 2); encoder.use_resource(src, metal::MTLResourceUsage::Read); encoder.use_resource(cos, metal::MTLResourceUsage::Read); encoder.use_resource(sin, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_affine( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, name: &'static str, size: usize, input: BufferOffset, output: &Buffer, mul: f32, add: f32, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Affine, name)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!(encoder, (size, mul, add, &input, output)); let (thread_group_count, thread_group_size) = linear_split(&pipeline, size); encoder.use_resource(input.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_affine_strided( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, name: &'static str, shape: &[usize], input: BufferOffset, input_stride: &[usize], output: &Buffer, mul: f32, add: f32, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Affine, name)?; let size: usize = shape.iter().product(); let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, ( size, shape.len(), shape, input_stride, mul, add, &input, output ) ); let (thread_group_count, thread_group_size) = linear_split(&pipeline, size); encoder.use_resource(input.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_powf( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, name: &'static str, size: usize, input: BufferOffset, output: &Buffer, mul: f32, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Affine, name)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!(encoder, (size, mul, &input, output)); let (thread_group_count, thread_group_size) = linear_split(&pipeline, size); encoder.use_resource(input.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_powf_strided( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, name: &'static str, shape: &[usize], input: BufferOffset, input_stride: &[usize], output: &Buffer, mul: f32, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Affine, name)?; let size: usize = shape.iter().product(); let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, (size, shape.len(), shape, input_stride, mul, &input, output) ); let (thread_group_count, thread_group_size) = linear_split(&pipeline, size); encoder.use_resource(input.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_elu( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, name: &'static str, size: usize, input: BufferOffset, output: &Buffer, mul: f32, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Affine, name)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!(encoder, (size, mul, &input, output)); let (thread_group_count, thread_group_size) = linear_split(&pipeline, size); encoder.use_resource(input.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_elu_strided( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, name: &'static str, shape: &[usize], input: BufferOffset, input_stride: &[usize], output: &Buffer, mul: f32, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Affine, name)?; let size: usize = shape.iter().product(); let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, (size, shape.len(), shape, input_stride, mul, &input, output) ); let (thread_group_count, thread_group_size) = linear_split(&pipeline, size); encoder.use_resource(input.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_where_cond_strided( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, name: &'static str, shape: &[usize], cond: BufferOffset, cond_stride: &[usize], left: BufferOffset, left_stride: &[usize], right: BufferOffset, right_stride: &[usize], output: &Buffer, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Ternary, name)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); let size: usize = shape.iter().product(); let rank = shape.len(); set_params!( encoder, ( size, rank, shape, cond_stride, left_stride, right_stride, &cond, &left, &right, output ) ); let (thread_group_count, thread_group_size) = linear_split(&pipeline, size); encoder.use_resource(cond.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(left.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(right.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_index_select( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, name: &'static str, shape: &[usize], ids_size: usize, dim: usize, contiguous: bool, src_dims: &[usize], src_strides: &[usize], input: BufferOffset, ids: BufferOffset, output: &Buffer, ) -> Result<(), MetalKernelError> { let left_size: usize = shape[..dim].iter().product(); let right_size: usize = shape[dim + 1..].iter().product(); let src_dim_size = shape[dim]; let dst_el = ids_size * left_size * right_size; let pipeline = kernels.load_pipeline(device, Source::Indexing, name)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, ( dst_el, left_size, src_dim_size, right_size, ids_size, contiguous, src_dims, src_strides, &input, &ids, output ) ); let (thread_group_count, thread_group_size) = linear_split(&pipeline, dst_el); encoder.use_resource(input.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(ids.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_gather( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, name: &'static str, shape: &[usize], ids_size: usize, dim: usize, input: BufferOffset, ids: BufferOffset, output: &Buffer, ) -> Result<(), MetalKernelError> { let left_size: usize = shape[..dim].iter().product(); let right_size: usize = shape[dim + 1..].iter().product(); let src_dim_size = shape[dim]; let dst_el = ids_size * left_size * right_size; let pipeline = kernels.load_pipeline(device, Source::Indexing, name)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, ( dst_el, left_size, src_dim_size, right_size, ids_size, &input, &ids, output ) ); let (thread_group_count, thread_group_size) = linear_split(&pipeline, dst_el); encoder.use_resource(input.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(ids.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_scatter( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, name: &'static str, src_shape: &[usize], dst_shape: &[usize], dim: usize, input: BufferOffset, ids: BufferOffset, output: BufferOffset, ) -> Result<(), MetalKernelError> { let left_size: usize = src_shape[..dim].iter().product(); let right_size: usize = src_shape[dim + 1..].iter().product(); let src_dim_size = src_shape[dim]; let dst_el = left_size * right_size; let dst_dim_size = dst_shape[dim]; let pipeline = kernels.load_pipeline(device, Source::Indexing, name)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, ( dst_el, left_size, src_dim_size, right_size, dst_dim_size, &input, &ids, &output ) ); let (thread_group_count, thread_group_size) = linear_split(&pipeline, dst_el); encoder.use_resource(input.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(ids.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(output.buffer, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_index_add( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, name: &'static str, src_shape: &[usize], dst_shape: &[usize], ids_shape: &[usize], dim: usize, input: BufferOffset, ids: BufferOffset, output: &Buffer, ) -> Result<(), MetalKernelError> { let left_size: usize = src_shape[..dim].iter().product(); let right_size: usize = src_shape[dim + 1..].iter().product(); let src_dim_size = src_shape[dim]; let dst_el = left_size * right_size; let dst_dim_size = dst_shape[dim]; let ids_dim_size = ids_shape[0]; let pipeline = kernels.load_pipeline(device, Source::Indexing, name)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, ( dst_el, left_size, src_dim_size, right_size, dst_dim_size, ids_dim_size, &input, &ids, output ) ); let (thread_group_count, thread_group_size) = linear_split(&pipeline, dst_el); encoder.use_resource(input.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(ids.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[derive(Debug, PartialEq)] pub enum Value { USize(usize), Bool(bool), F32(f32), U16(u16), } impl std::hash::Hash for Value { fn hash<H: std::hash::Hasher>(&self, state: &mut H) { match self { Value::F32(v) => v.to_bits().hash(state), Value::USize(v) => v.hash(state), Value::U16(v) => v.hash(state), Value::Bool(v) => v.hash(state), } } } impl Value { fn data_type(&self) -> MTLDataType { match self { Value::USize(_) => MTLDataType::UInt, Value::F32(_) => MTLDataType::Float, Value::U16(_) => MTLDataType::UShort, Value::Bool(_) => MTLDataType::Bool, } } } /// Not true, good enough for our purposes. impl Eq for Value {} #[derive(Debug, Eq, PartialEq, Hash)] struct ConstantValues(Vec<(usize, Value)>); impl ConstantValues { pub fn new(values: Vec<(usize, Value)>) -> Self { Self(values) } fn function_constant_values(&self) -> FunctionConstantValues { let f = FunctionConstantValues::new(); for (index, value) in &self.0 { let ty = value.data_type(); match value { Value::USize(v) => { f.set_constant_value_at_index( v as *const usize as *const c_void, ty, *index as u64, ); } Value::F32(v) => { f.set_constant_value_at_index( v as *const f32 as *const c_void, ty, *index as u64, ); } Value::U16(v) => { f.set_constant_value_at_index( v as *const u16 as *const c_void, ty, *index as u64, ); } Value::Bool(v) => { f.set_constant_value_at_index( v as *const bool as *const c_void, ty, *index as u64, ); } } } f } } #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub enum SdpaDType { BF16, F16, F32, } /// SDPA full is supported when: /// - q head dim == 64, 128 /// - no mask /// - q heads == kv heads /// - final type != bf16 (TODO maybe just template this kernel too?) /// - q,k,v are contiguous #[allow(clippy::too_many_arguments)] pub fn call_sdpa_full( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, q_offset: usize, q_shape: &[usize], q_buffer: &Buffer, k_offset: usize, k_buffer: &Buffer, v_offset: usize, v_buffer: &Buffer, output: &Buffer, alpha: f32, softcapping: f32, itype: SdpaDType, ) -> Result<(), MetalKernelError> { #[derive(Debug)] #[repr(C)] struct MLXFastAttentionParams { m: i32, n: i32, k: i32, ldq: i32, // ldq == ldo ldk: i32, ldv: i32, lds: i32, ldo: i32, tiles_n: i32, tiles_m: i32, batch_stride_q: i32, batch_stride_k: i32, batch_stride_v: i32, batch_stride_o: i32, swizzle_log: i32, gemm_n_iterations_aligned: i32, gemm_k_iterations_aligned: i32, gemm_sv_m_block_iterations: i32, batch_ndim: i32, alpha: f32, softcapping: f32, } let bk = q_shape.last().unwrap(); const BN: usize = 16; const BM: usize = 16; const WM: usize = 2; const WN: usize = 2; let name = match (bk, itype) { (32, SdpaDType::F16) => "steel_gemm_attention_bm_16_bn_16_bk_32_itype_half", (64, SdpaDType::F16) => "steel_gemm_attention_bm_16_bn_16_bk_64_itype_half", (96, SdpaDType::F16) => "steel_gemm_attention_bm_16_bn_16_bk_96_itype_half", (128, SdpaDType::F16) => "steel_gemm_attention_bm_16_bn_16_bk_128_itype_half", (256, SdpaDType::F16) => "steel_gemm_attention_bm_16_bn_16_bk_256_itype_half", (32, SdpaDType::F32) => "steel_gemm_attention_bm_16_bn_16_bk_32_itype_float", (64, SdpaDType::F32) => "steel_gemm_attention_bm_16_bn_16_bk_64_itype_float", (96, SdpaDType::F32) => "steel_gemm_attention_bm_16_bn_16_bk_96_itype_float", (128, SdpaDType::F32) => "steel_gemm_attention_bm_16_bn_16_bk_128_itype_float", (256, SdpaDType::F32) => "steel_gemm_attention_bm_16_bn_16_bk_256_itype_float", (other, SdpaDType::F16 | SdpaDType::F32) => { return Err(MetalKernelError::SdpaHeadSizeMismatch { variation: "full", got: *other, expected: vec![32, 64, 96, 128, 256], }) } (_, SdpaDType::BF16) => { return Err(MetalKernelError::SdpaHeadDTypeMismatch { variation: "full", got: SdpaDType::BF16, }) } }; let pipeline = kernels.load_pipeline(device, Source::Sdpa, name)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); // q = (bs, qhead, seq, hidden) // k/v = (bs, kv_head, seq, hidden) let qseq = q_shape[q_shape.len() - 2]; let m = q_shape[q_shape.len() - 2]; let n = m; let k = q_shape[q_shape.len() - 1]; let bs_out = q_shape[0] * q_shape[1]; let batch_shape = [q_shape[0] * q_shape[1]]; let dk = q_shape[q_shape.len() - 1]; let ldq = dk; let ldk = dk; let ldv = dk; let lds = BN; let ldo = dk; let tn = 1; let tm = m.div_ceil(BM); let b_stride_q = dk * qseq; let b_stride_k = dk * qseq; let b_stride_v = dk * qseq; let b_stride_o = dk * qseq; let swizzle_log = 0; let gemm_n_iterations_aligned = n.div_ceil(BN); let gemm_k_iterations_aligned = k.div_ceil(*bk); let gemm_sv_m_block_iterations = m.div_ceil(BM); let batch_ndim = batch_shape.len(); let alpha = if softcapping != 1. { alpha / softcapping } else { alpha }; let params = MLXFastAttentionParams { m: m as i32, n: n as i32, k: k as i32, ldq: ldq as i32, ldk: ldk as i32, ldv: ldv as i32, lds: lds as i32, ldo: ldo as i32, tiles_n: tn, tiles_m: tm as i32, batch_stride_q: b_stride_q as i32, batch_stride_k: b_stride_k as i32, batch_stride_v: b_stride_v as i32, batch_stride_o: b_stride_o as i32, swizzle_log, gemm_n_iterations_aligned: gemm_n_iterations_aligned as i32, gemm_k_iterations_aligned: gemm_k_iterations_aligned as i32, gemm_sv_m_block_iterations: gemm_sv_m_block_iterations as i32, batch_ndim: batch_ndim as i32, alpha, softcapping, }; let batch_strides = [b_stride_q, b_stride_k, b_stride_v, b_stride_o]; impl EncoderParam for MLXFastAttentionParams { fn set_param(encoder: &ComputeCommandEncoderRef, position: u64, data: Self) { encoder.set_bytes( position, core::mem::size_of::<MLXFastAttentionParams>() as u64, &data as *const MLXFastAttentionParams as *const c_void, ); } } set_params!( encoder, ( (q_buffer, q_offset), (k_buffer, k_offset), (v_buffer, v_offset), output, params, &batch_shape[..], &batch_strides[..] ) ); let grid_dims = MTLSize { width: 1, height: tm as u64, depth: bs_out as u64, }; let group_dims = MTLSize { width: 32, height: WM as u64, depth: WN as u64, }; encoder.use_resource(q_buffer, metal::MTLResourceUsage::Read); encoder.use_resource(k_buffer, metal::MTLResourceUsage::Read); encoder.use_resource(v_buffer, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(grid_dims, group_dims); Ok(()) } /// SDPA full is supported when: /// - q head dim == 64, 96, 128 /// - no mask /// - q,k,v are contiguous #[allow(clippy::too_many_arguments)] pub fn call_sdpa_vector( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, q_offset: usize, q_shape: &[usize], q_buffer: &Buffer, k_offset: usize, k_shape: &[usize], k_stride: &[usize], k_buffer: &Buffer, v_offset: usize, v_stride: &[usize], v_buffer: &Buffer, output: &Buffer, alpha: f32, softcapping: f32, itype: SdpaDType, ) -> Result<(), MetalKernelError> { let bk = q_shape.last().unwrap(); let gqa_factor = (q_shape[1] / k_shape[1]) as i32; let n = k_shape[2] as i32; let b = (q_shape[0] * q_shape[1]) as i32; let kstride = k_stride[1]; let vstride = v_stride[1]; let name = match (bk, itype) { (32, SdpaDType::F16) => "sdpa_vector_float16_t_32", (64, SdpaDType::F16) => "sdpa_vector_float16_t_64", (96, SdpaDType::F16) => "sdpa_vector_float16_t_96", (128, SdpaDType::F16) => "sdpa_vector_float16_t_128", (256, SdpaDType::F16) => "sdpa_vector_float16_t_256", (32, SdpaDType::BF16) => "sdpa_vector_bfloat16_t_32", (64, SdpaDType::BF16) => "sdpa_vector_bfloat16_t_64", (96, SdpaDType::BF16) => "sdpa_vector_bfloat16_t_96", (128, SdpaDType::BF16) => "sdpa_vector_bfloat16_t_128", (256, SdpaDType::BF16) => "sdpa_vector_bfloat16_t_256", (32, SdpaDType::F32) => "sdpa_vector_float_32", (64, SdpaDType::F32) => "sdpa_vector_float_64", (96, SdpaDType::F32) => "sdpa_vector_float_96", (128, SdpaDType::F32) => "sdpa_vector_float_128", (256, SdpaDType::F32) => "sdpa_vector_float_256", (other, _) => { return Err(MetalKernelError::SdpaHeadSizeMismatch { variation: "vector", got: *other, expected: vec![32, 64, 96, 128, 256], }) } }; let alpha = if softcapping != 1. { alpha / softcapping } else { alpha }; let constants = Some(ConstantValues::new(vec![( 20, Value::Bool(/* sdpa_vector_has_mask */ false), )])); let pipeline = kernels.load_pipeline_with_constants(device, Source::Sdpa, name, constants)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); // q = (bs, qhead, seq, hidden) // k/v = (bs, kv_head, kv_seq, hidden) set_params!( encoder, ( (q_buffer, q_offset), (k_buffer, k_offset), (v_buffer, v_offset), output, gqa_factor, n, kstride, vstride, alpha, softcapping ) ); let grid_dims = MTLSize { width: 1, height: b as u64, depth: 1_u64, }; let group_dims = MTLSize { width: 1024, height: 1, depth: 1, }; encoder.use_resource(q_buffer, metal::MTLResourceUsage::Read); encoder.use_resource(k_buffer, metal::MTLResourceUsage::Read); encoder.use_resource(v_buffer, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(grid_dims, group_dims); Ok(()) } pub const SDPA_2PASS_BLOCKS: usize = 32; /// SDPA vector 2pass is supported when: /// - q head dim == 64, 96, 128 /// - no mask /// - q,k,v are contiguous #[allow(clippy::too_many_arguments)] pub fn call_sdpa_vector_2pass( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, q_offset: usize, q_shape: &[usize], q_buffer: &Buffer, k_offset: usize, k_shape: &[usize], k_stride: &[usize], k_buffer: &Buffer, v_offset: usize, v_stride: &[usize], v_buffer: &Buffer, output: &Buffer, intermediate: &Buffer, sums: &Buffer, maxs: &Buffer, alpha: f32, softcapping: f32, itype: SdpaDType, ) -> Result<(), MetalKernelError> { let bk = q_shape.last().unwrap(); // First pass { let name_pass1 = match (bk, itype) { (32, SdpaDType::F16) => "sdpa_vector_2pass_1_float16_t_32", (64, SdpaDType::F16) => "sdpa_vector_2pass_1_float16_t_64", (96, SdpaDType::F16) => "sdpa_vector_2pass_1_float16_t_96", (128, SdpaDType::F16) => "sdpa_vector_2pass_1_float16_t_128", (256, SdpaDType::F16) => "sdpa_vector_2pass_1_float16_t_256", (32, SdpaDType::BF16) => "sdpa_vector_2pass_1_bfloat16_t_32", (64, SdpaDType::BF16) => "sdpa_vector_2pass_1_bfloat16_t_64", (96, SdpaDType::BF16) => "sdpa_vector_2pass_1_bfloat16_t_96", (128, SdpaDType::BF16) => "sdpa_vector_2pass_1_bfloat16_t_128", (256, SdpaDType::BF16) => "sdpa_vector_2pass_1_bfloat16_t_256", (32, SdpaDType::F32) => "sdpa_vector_2pass_1_float_32", (64, SdpaDType::F32) => "sdpa_vector_2pass_1_float_64", (96, SdpaDType::F32) => "sdpa_vector_2pass_1_float_96", (128, SdpaDType::F32) => "sdpa_vector_2pass_1_float_128", (256, SdpaDType::F32) => "sdpa_vector_2pass_1_float_256", (other, _) => { return Err(MetalKernelError::SdpaHeadSizeMismatch { variation: "vector_2pass_1", got: *other, expected: vec![32, 64, 96, 128, 256], }) } }; let gqa_factor = (q_shape[1] / k_shape[1]) as i32; let n = k_shape[2] as i32; let b = (q_shape[0] * q_shape[1]) as i32; let kstride = k_stride[1]; let vstride = v_stride[1]; let alpha = if softcapping != 1. { alpha / softcapping } else { alpha }; let constants = Some(ConstantValues::new(vec![( 20, Value::Bool(/* sdpa_vector_has_mask */ false), )])); let pipeline = kernels.load_pipeline_with_constants(device, Source::Sdpa, name_pass1, constants)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); // q = (bs, qhead, seq, hidden) // k/v = (bs, kv_head, kv_seq, hidden) set_params!( encoder, ( (q_buffer, q_offset), (k_buffer, k_offset), (v_buffer, v_offset), intermediate, sums, maxs, gqa_factor, n, kstride, vstride, alpha, softcapping ) ); let grid_dims = MTLSize { width: 1, height: b as u64, depth: SDPA_2PASS_BLOCKS as u64, }; let group_dims = MTLSize { width: 8 * 32, height: 1, depth: 1, }; encoder.use_resource(q_buffer, metal::MTLResourceUsage::Read); encoder.use_resource(k_buffer, metal::MTLResourceUsage::Read); encoder.use_resource(v_buffer, metal::MTLResourceUsage::Read); encoder.use_resource(intermediate, metal::MTLResourceUsage::Write); encoder.use_resource(sums, metal::MTLResourceUsage::Write); encoder.use_resource(maxs, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(grid_dims, group_dims); } // Final pass { let name_pass2 = match (bk, itype) { (32, SdpaDType::F16) => "sdpa_vector_2pass_2_float16_t_32", (64, SdpaDType::F16) => "sdpa_vector_2pass_2_float16_t_64", (96, SdpaDType::F16) => "sdpa_vector_2pass_2_float16_t_96", (128, SdpaDType::F16) => "sdpa_vector_2pass_2_float16_t_128", (256, SdpaDType::F16) => "sdpa_vector_2pass_2_float16_t_256", (32, SdpaDType::BF16) => "sdpa_vector_2pass_2_bfloat16_t_32", (64, SdpaDType::BF16) => "sdpa_vector_2pass_2_bfloat16_t_64", (96, SdpaDType::BF16) => "sdpa_vector_2pass_2_bfloat16_t_96", (128, SdpaDType::BF16) => "sdpa_vector_2pass_2_bfloat16_t_128", (256, SdpaDType::BF16) => "sdpa_vector_2pass_2_bfloat16_t_256", (32, SdpaDType::F32) => "sdpa_vector_2pass_2_float_32", (64, SdpaDType::F32) => "sdpa_vector_2pass_2_float_64", (96, SdpaDType::F32) => "sdpa_vector_2pass_2_float_96", (128, SdpaDType::F32) => "sdpa_vector_2pass_2_float_128", (256, SdpaDType::F32) => "sdpa_vector_2pass_2_float_256", (other, _) => { return Err(MetalKernelError::SdpaHeadSizeMismatch { variation: "vector_2pass_2", got: *other, expected: vec![32, 64, 96, 128, 256], }) } }; let b = (q_shape[0] * q_shape[1]) as i32; let pipeline = kernels.load_pipeline(device, Source::Sdpa, name_pass2)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); // q = (bs, qhead, seq, hidden) // k/v = (bs, kv_head, kv_seq, hidden) set_params!(encoder, (intermediate, sums, maxs, output)); let grid_dims = MTLSize { width: 1, height: b as u64, depth: 1, }; let group_dims = MTLSize { width: 1024, height: 1, depth: 1, }; encoder.use_resource(intermediate, metal::MTLResourceUsage::Write); encoder.use_resource(sums, metal::MTLResourceUsage::Write); encoder.use_resource(maxs, metal::MTLResourceUsage::Write); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(grid_dims, group_dims); } Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_im2col1d_strided( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, name: &'static str, shape: &[usize], strides: &[usize], (k_size, stride, padding, dilation): (usize, usize, usize, usize), input: BufferOffset, output: &Buffer, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Conv, name)?; let l_out = (shape[2] + 2 * padding - dilation * (k_size - 1) - 1) / stride + 1; let dst_el = shape[0] * l_out * shape[1] * k_size; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); let (thread_group_count, thread_group_size) = linear_split(&pipeline, dst_el); encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, (dst_el, l_out, k_size, stride, padding, dilation, shape, strides, &input, output) ); encoder.use_resource(input.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_col2im1d( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, name: &'static str, shape: &[usize], k_size: usize, stride: usize, input: BufferOffset, output: &Buffer, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Conv, name)?; let l_in = shape[1]; let c_out = shape[2]; let l_out = (l_in - 1) * stride + k_size; let dst_el = shape[0] * c_out * l_out; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); let (thread_group_count, thread_group_size) = linear_split(&pipeline, dst_el); encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, (dst_el, l_out, l_in, c_out, k_size, stride, &input, output) ); encoder.use_resource(input.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_im2col_strided( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, name: &'static str, shape: &[usize], strides: &[usize], (h_k, w_k, stride, padding, dilation): (usize, usize, usize, usize, usize), input: BufferOffset, output: &Buffer, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Conv, name)?; let h = shape[2]; let w = shape[3]; let h_out = (h + 2 * padding - dilation * (h_k - 1) - 1) / stride + 1; let w_out = (w + 2 * padding - dilation * (w_k - 1) - 1) / stride + 1; let dst_el = shape[0] * h_out * w_out * shape[1] * h_k * w_k; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); let (thread_group_count, thread_group_size) = linear_split(&pipeline, dst_el); encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, ( dst_el, h_out, w_out, h_k, w_k, stride, padding, dilation, shape, strides, &input, output ) ); encoder.use_resource(input.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_upsample_nearest_2d( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, name: &'static str, shape: &[usize], strides: &[usize], out_w: usize, out_h: usize, input: BufferOffset, output: &Buffer, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Conv, name)?; let dst_el = out_w * out_h * shape[0] * shape[1]; let scale_w = shape[2] as f32 / out_w as f32; let scale_h = shape[3] as f32 / out_h as f32; let (thread_group_count, thread_group_size) = linear_split(&pipeline, dst_el); let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, (out_w, out_h, scale_w, scale_h, shape, strides, &input, output) ); encoder.use_resource(input.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_random_uniform( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, name: &'static str, min: f32, max: f32, length: usize, seed: &Buffer, buffer: &Buffer, ) -> Result<(), MetalKernelError> { if min >= max { return Err(MetalKernelError::LoadLibraryError( "min must be less than max".to_string(), )); } let pipeline = kernels.load_pipeline(device, Source::Random, name)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); let odd = (length % 2 != 0) as usize; let (thread_group_count, thread_group_size) = linear_split(&pipeline, length / 2 + odd); encoder.set_compute_pipeline_state(&pipeline); set_params!(encoder, (length, min, max, seed, buffer)); encoder.use_resource( seed, metal::MTLResourceUsage::Read | metal::MTLResourceUsage::Write, ); encoder.use_resource(buffer, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_random_normal( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, name: &'static str, mean: f32, stddev: f32, length: usize, seed: &Buffer, buffer: &Buffer, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Random, name)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); let odd = (length % 2 != 0) as usize; let (thread_group_count, thread_group_size) = linear_split(&pipeline, length / 2 + odd); encoder.set_compute_pipeline_state(&pipeline); set_params!(encoder, (length, mean, stddev, seed, buffer)); encoder.use_resource( seed, metal::MTLResourceUsage::Read | metal::MTLResourceUsage::Write, ); encoder.use_resource(buffer, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[derive(Debug, Clone, Copy)] pub enum GgmlDType { Q4_0, Q4_1, Q5_0, Q5_1, Q8_0, Q8_1, Q2K, Q3K, Q4K, Q5K, Q6K, Q8K, F16, F32, BF16, } #[allow(clippy::too_many_arguments)] pub fn call_quantized_matmul_mv_t( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, dtype: GgmlDType, (b, m, n, k): (usize, usize, usize, usize), lhs: &Buffer, lhs_offset: usize, rhs: &Buffer, dst_offset: usize, dst: &Buffer, ) -> Result<(), MetalKernelError> { // Everything is in reverse let ne00 = k as i64; let ne01 = n as i64; let ne02 = b as i64; let ne03 = 1i64; let nb00 = 0i64; let nb01 = 0i64; let nb02 = 0i64; let ne10 = k as i64; let ne11 = m as i64; let ne12 = b as i64; let ne13 = 1i64; let nb10 = 0i64; let nb11 = 0i64; let nb12 = 0i64; let ne0 = n as i64; let ne1 = m as i64; let r2: u32 = (ne12 / ne02) as u32; let r3: u32 = (ne13 / ne03) as u32; let (nth0, nth1, align) = match dtype { GgmlDType::Q4_0 | GgmlDType::Q4_1 | GgmlDType::Q5_0 | GgmlDType::Q5_1 | GgmlDType::Q8_0 | GgmlDType::Q8_1 => { let nth0 = 8; let nth1 = 8; let align = 8; (nth0, nth1, align) } GgmlDType::Q2K => { // Fixing a bug in Metal for GGML // https://github.com/ggerganov/llama.cpp/blob/b8109bc0139f15a5b321909f47510b89dca47ffc/ggml-metal.m#L1576 let nth0 = 2; let nth1 = 32; let align = 4; (nth0, nth1, align) } GgmlDType::Q4K => { let nth0 = 4; let nth1 = 8; let align = 4; (nth0, nth1, align) } GgmlDType::Q3K | GgmlDType::Q5K => { let nth0 = 2; let nth1 = 32; let align = 4; (nth0, nth1, align) } GgmlDType::Q6K => { let nth0 = 2; let nth1 = 32; let align = 2; (nth0, nth1, align) } GgmlDType::F16 | GgmlDType::BF16 | GgmlDType::Q8K => { // Original implem uses rows let nth0 = 32; let nth1 = 1; let align = 8; (nth0, nth1, align) } GgmlDType::F32 => { let nth0 = 32; let nth1 = 1; let align = 8; (nth0, nth1, align) } }; let thread_groups_count = MTLSize { width: divide(ne01 as usize, align), height: ne11 as u64, depth: (ne12 * ne13) as u64, }; let threads_per_threadgroup = MTLSize { width: nth0, height: nth1, depth: 1, }; let name = match dtype { GgmlDType::Q4_0 => "kernel_mul_mv_q4_0_f32", GgmlDType::Q4_1 => "kernel_mul_mv_q4_1_f32", GgmlDType::Q5_0 => "kernel_mul_mv_q5_0_f32", GgmlDType::Q5_1 => "kernel_mul_mv_q5_1_f32", GgmlDType::Q8_0 => "kernel_mul_mv_q8_0_f32", GgmlDType::Q8_1 => "kernel_mul_mv_q8_1_f32", GgmlDType::Q2K => "kernel_mul_mv_q2_K_f32", GgmlDType::Q3K => "kernel_mul_mv_q3_K_f32", GgmlDType::Q4K => "kernel_mul_mv_q4_K_f32", GgmlDType::Q5K => "kernel_mul_mv_q5_K_f32", GgmlDType::Q6K => "kernel_mul_mv_q6_K_f32", GgmlDType::Q8K => "kernel_mul_mv_q8_K_f32", GgmlDType::F16 => "kernel_mul_mv_f16_f32", GgmlDType::BF16 => "kernel_mul_mv_bf16_f32", GgmlDType::F32 => "kernel_mul_mv_f32_f32", }; let pipeline = kernels.load_pipeline(device, Source::Quantized, name)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, ( rhs, (lhs, lhs_offset), (dst, dst_offset), ne00, ne01, ne02, nb00, nb01, nb02, ne10, ne11, ne12, nb10, nb11, nb12, ne0, ne1, r2, r3 ) ); encoder.use_resource(lhs, metal::MTLResourceUsage::Read); encoder.use_resource(rhs, metal::MTLResourceUsage::Read); encoder.use_resource(dst, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_groups_count, threads_per_threadgroup); Ok(()) } /// - src0 is usually weight /// - src1 is usually xs #[allow(clippy::too_many_arguments)] pub fn call_quantized_matmul_mm_t( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, dtype: GgmlDType, src0_shape: &[usize], src0_stride: &[usize], src0: &Buffer, src1_shape: &[usize], src1_stride: &[usize], src1: &Buffer, src1_offset: usize, dst_shape: &[usize], dst_offset: usize, dst: &Buffer, ) -> Result<(), MetalKernelError> { // Everything is in reverse let ne00 = src0_shape[src0_shape.len() - 1] as i64; let ne01 = src0_shape[src0_shape.len() - 2] as i64; let ne02 = src0_shape[src0_shape.len() - 3] as i64; let ne03 = src0_shape[src0_shape.len() - 4] as i64; let nb01 = src0_stride[src0_stride.len() - 2] as i64; let nb02 = src0_stride[src0_stride.len() - 3] as i64; let nb03 = src0_stride[src0_stride.len() - 4] as i64; let ne11 = src1_shape[src1_shape.len() - 2] as i64; let ne12 = src1_shape[src1_shape.len() - 3] as i64; let ne13 = src1_shape[src1_shape.len() - 4] as i64; let nb10 = src1_stride[src1_stride.len() - 1] as i64; let nb11 = src1_stride[src1_stride.len() - 2] as i64; let nb12 = src1_stride[src1_stride.len() - 3] as i64; let nb13 = src1_stride[src1_stride.len() - 4] as i64; let ne0 = dst_shape[dst_shape.len() - 1] as i64; let ne1 = dst_shape[dst_shape.len() - 2] as i64; let r2 = (ne12 / ne02) as u32; let r3 = (ne13 / ne03) as u32; let thread_groups_count = MTLSize { width: divide(ne11 as usize, 32), height: divide(ne01 as usize, 64), depth: (ne12 * ne13) as u64, }; let threads_per_threadgroup = MTLSize { width: 128, height: 1, depth: 1, }; let name = match dtype { GgmlDType::Q4_0 => "kernel_mul_mm_q4_0_f32", GgmlDType::Q4_1 => "kernel_mul_mm_q4_1_f32", GgmlDType::Q5_0 => "kernel_mul_mm_q5_0_f32", GgmlDType::Q5_1 => "kernel_mul_mm_q5_1_f32", GgmlDType::Q8_0 => "kernel_mul_mm_q8_0_f32", GgmlDType::Q8_1 => "kernel_mul_mm_q8_1_f32", GgmlDType::Q2K => "kernel_mul_mm_q2_K_f32", GgmlDType::Q3K => "kernel_mul_mm_q3_K_f32", GgmlDType::Q4K => "kernel_mul_mm_q4_K_f32", GgmlDType::Q5K => "kernel_mul_mm_q5_K_f32", GgmlDType::Q6K => "kernel_mul_mm_q6_K_f32", GgmlDType::Q8K => "kernel_mul_mm_q8_K_f32", GgmlDType::F16 => "kernel_mul_mm_f16_f32", GgmlDType::BF16 => "kernel_mul_mm_bf16_f32", GgmlDType::F32 => "kernel_mul_mm_f32_f32", }; let pipeline = kernels.load_pipeline(device, Source::Quantized, name)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, ( src0, (src1, src1_offset), (dst, dst_offset), ne00, ne02, nb01, nb02, nb03, ne12, nb10, nb11, nb12, nb13, ne0, ne1, r2, r3 ) ); encoder.use_resource(src0, metal::MTLResourceUsage::Read); encoder.use_resource(src1, metal::MTLResourceUsage::Read); encoder.use_resource(dst, metal::MTLResourceUsage::Write); encoder.set_threadgroup_memory_length(0, 8192); encoder.dispatch_thread_groups(thread_groups_count, threads_per_threadgroup); Ok(()) } fn divide(m: usize, b: usize) -> NSUInteger { m.div_ceil(b) as NSUInteger } #[allow(clippy::too_many_arguments)] pub fn call_pool2d( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, name: &'static str, shape: &[usize], strides: &[usize], out_w: usize, out_h: usize, w_k: usize, h_k: usize, w_stride: usize, h_stride: usize, input: &Buffer, output: &Buffer, ) -> Result<(), MetalKernelError> { let dst_el = out_w * out_h * shape[0] * shape[1]; let pipeline: ComputePipelineState = kernels.load_pipeline(device, Source::Conv, name)?; let (thread_group_count, thread_group_size) = linear_split(&pipeline, dst_el); let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, (w_k, h_k, w_stride, h_stride, shape, strides, input, output) ); encoder.use_resource(input, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_conv_transpose1d( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, name: &'static str, dilation: usize, stride: usize, padding: usize, out_padding: usize, c_out: usize, l_out: usize, b_size: usize, src_shape: &[usize], src_strides: &[usize], kernel_shape: &[usize], kernel_strides: &[usize], input: &Buffer, input_offset: usize, kernel: &Buffer, kernel_offset: usize, output: &Buffer, ) -> Result<(), MetalKernelError> { let dst_el = c_out * l_out * b_size; let pipeline: ComputePipelineState = kernels.load_pipeline(device, Source::Conv, name)?; let (thread_group_count, thread_group_size) = linear_split(&pipeline, dst_el); let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, ( l_out, stride, padding, out_padding, dilation, src_shape, src_strides, kernel_shape, kernel_strides, (input, input_offset), (kernel, kernel_offset), output ) ); encoder.use_resource(input, metal::MTLResourceUsage::Read); encoder.use_resource(kernel, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } pub struct CallConvTranspose2dCfg<'a> { pub dilation: usize, pub stride: usize, pub padding: usize, pub output_padding: usize, pub c_out: usize, pub out_w: usize, pub out_h: usize, pub b_size: usize, pub input_dims: &'a [usize], pub input_stride: &'a [usize], pub kernel_dims: &'a [usize], pub kernel_stride: &'a [usize], pub input_offset: usize, pub kernel_offset: usize, } #[allow(clippy::too_many_arguments)] pub fn call_conv_transpose2d( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, name: &'static str, cfg: CallConvTranspose2dCfg, input: &Buffer, kernel: &Buffer, output: &Buffer, ) -> Result<(), MetalKernelError> { let dst_el = cfg.c_out * cfg.out_w * cfg.out_h * cfg.b_size; let pipeline: ComputePipelineState = kernels.load_pipeline(device, Source::Conv, name)?; let (thread_group_count, thread_group_size) = linear_split(&pipeline, dst_el); let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, ( cfg.out_w, cfg.out_h, cfg.stride, cfg.padding, cfg.output_padding, cfg.dilation, cfg.input_dims, cfg.input_stride, cfg.kernel_dims, cfg.kernel_stride, (input, cfg.input_offset), (kernel, cfg.kernel_offset), output ) ); encoder.use_resource(input, metal::MTLResourceUsage::Read); encoder.use_resource(kernel, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } pub fn call_const_fill( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, name: &'static str, length: usize, output: &Buffer, v: impl EncoderParam, ) -> Result<(), MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Fill, name)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!(encoder, (output, v, length)); let (thread_group_count, thread_group_size) = linear_split(&pipeline, length); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[cfg(test)] mod tests;
candle/candle-metal-kernels/src/lib.rs/0
{ "file_path": "candle/candle-metal-kernels/src/lib.rs", "repo_id": "candle", "token_count": 40673 }
47
use candle_metal_kernels::{binary, call_binary_contiguous, call_binary_strided, Kernels}; use half::{bf16, f16}; use metal::objc::rc::autoreleasepool; use metal::{Device, MTLResourceOptions}; use rand; use std::any::type_name; use std::time::Instant; fn main() { let device = Device::system_default().unwrap(); let kernels = Kernels::new(); let f32_1k = (0..1000).map(|_| rand::random::<f32>()).collect::<Vec<_>>(); let f32_10k = (0..10000) .map(|_| rand::random::<f32>()) .collect::<Vec<_>>(); let f32_100k = (0..100000) .map(|_| rand::random::<f32>()) .collect::<Vec<_>>(); let f16_map = |v: &[f32]| v.iter().map(|v| f16::from_f32(*v)).collect::<Vec<_>>(); let f16_1k = f16_map(&f32_1k); let f16_10k = f16_map(&f32_10k); let f16_100k = f16_map(&f32_100k); let bf16_map = |v: &[f32]| v.iter().map(|v| bf16::from_f32(*v)).collect::<Vec<_>>(); let bf16_1k = bf16_map(&f32_1k); let bf16_10k = bf16_map(&f32_10k); let bf16_100k = bf16_map(&f32_100k); let f32_ckernels = [ binary::contiguous::add::FLOAT, binary::contiguous::sub::FLOAT, binary::contiguous::mul::FLOAT, binary::contiguous::div::FLOAT, ]; let f32_skernels = [ binary::strided::add::FLOAT, binary::strided::sub::FLOAT, binary::strided::mul::FLOAT, binary::strided::div::FLOAT, ]; let f16_ckernels = [ binary::contiguous::add::HALF, binary::contiguous::sub::HALF, binary::contiguous::mul::HALF, binary::contiguous::div::HALF, ]; let f16_skernels = [ binary::strided::add::HALF, binary::strided::sub::HALF, binary::strided::mul::HALF, binary::strided::div::HALF, ]; let bf16_ckernels = [ binary::contiguous::add::BFLOAT, binary::contiguous::sub::BFLOAT, binary::contiguous::mul::BFLOAT, binary::contiguous::div::BFLOAT, ]; let bf16_skernels = [ binary::strided::add::BFLOAT, binary::strided::sub::BFLOAT, binary::strided::mul::BFLOAT, binary::strided::div::BFLOAT, ]; println!( "{0: <5} | {1: <19} | {2: <6} | {3: <5} | {4: <11} | {5: <11}", "dtype", "kernel", "size", "runs", "total time", "avg time" ); // f32 run_binary_bench(&device, &kernels, &f32_1k, f32_ckernels, f32_skernels); run_binary_bench(&device, &kernels, &f32_10k, f32_ckernels, f32_skernels); run_binary_bench(&device, &kernels, &f32_100k, f32_ckernels, f32_skernels); // f16 run_binary_bench(&device, &kernels, &f16_1k, f16_ckernels, f16_skernels); run_binary_bench(&device, &kernels, &f16_10k, f16_ckernels, f16_skernels); run_binary_bench(&device, &kernels, &f16_100k, f16_ckernels, f16_skernels); // bf16 run_binary_bench(&device, &kernels, &bf16_1k, bf16_ckernels, bf16_skernels); run_binary_bench(&device, &kernels, &bf16_10k, bf16_ckernels, bf16_skernels); run_binary_bench(&device, &kernels, &bf16_100k, bf16_ckernels, bf16_skernels); } fn run_binary_bench<T: Clone>( device: &Device, kernels: &Kernels, v: &[T], contiguous: [binary::contiguous::Kernel; 4], strided: [binary::strided::Kernel; 4], ) { let command_queue = device.new_command_queue(); let options = MTLResourceOptions::StorageModeManaged; let iterations = 1000; let input = device.new_buffer_with_data( v.as_ptr() as *const core::ffi::c_void, core::mem::size_of_val(v) as u64, options, ); let mut output = device.new_buffer(core::mem::size_of_val(v) as u64, options); // Contiguous for kernel_name in contiguous { let total_time = autoreleasepool(|| { let command_buffer = command_queue.new_command_buffer(); let start = Instant::now(); for _ in 0..iterations { call_binary_contiguous( device, &command_buffer, kernels, kernel_name, v.len(), &input, &input, &mut output, ) .unwrap(); } command_buffer.commit(); command_buffer.wait_until_completed(); start.elapsed() }); println!( "{0: <5} | {1: <19} | {2: <6} | {3: <5} | {4: <11?} | {5: <11?}", type_name::<T>().split("::").last().unwrap(), kernel_name.to_string(), v.len(), iterations, total_time, total_time / iterations ); } // Strided let shape = vec![2, 5_000]; let strides = vec![2, 1]; let offset = 0; for kernel_name in strided { let total_time = autoreleasepool(|| { let command_buffer = command_queue.new_command_buffer(); let start = Instant::now(); for _ in 0..iterations { call_binary_strided( device, command_buffer, &kernels, kernel_name, &shape, &input, &strides, offset, &input, &strides, offset, &mut output, ) .unwrap(); } command_buffer.commit(); command_buffer.wait_until_completed(); start.elapsed() }); println!( "{0: <5} | {1: <19} | {2: <6} | {3: <5} | {4: <11?} | {5: <11?}", type_name::<T>().split("::").last().unwrap(), kernel_name.to_string(), v.len(), iterations, total_time, total_time / iterations ); } }
candle/candle-metal-kernels/tmp/binary.rs/0
{ "file_path": "candle/candle-metal-kernels/tmp/binary.rs", "repo_id": "candle", "token_count": 3149 }
48
//! Encoding Utilities. (e.g., one-hot/cold encoding) use candle::{bail, DType, Result, Tensor, WithDType}; /// One-hot/cold encoding. /// /// Given an input tensor of indices, this function returns a tensor of the same shape as the input /// tensor with an additional dimension of the given depth size. The values in the returned tensor are /// all set to the `off_value` except for the positions represented by the indices, which are set to the `on_value`. /// /// This method returns a tensor with a rank that is one rank larger than the input tensor. /// /// As an example, the following tensor will be encoded to a one-hot matrix: /// /// `[[0i64, 2], [1, -1]]` /// /// with a depth of 4 will be encoded to: /// /// `[[[1, 0, 0, 0], [0, 0, 1, 0]], [[0, 1, 0, 0], [0, 0, 0, 0]]]` /// /// When the input tensor index has a value of -1, the corresponding one-hot vector will be ignored, /// resulting in a vector of values set to the `off_value`. /// /// /// This method supports one-cold encoding by setting `on_value` to `0` and `off_value` to `1`. /// By default `on_value` is `1` and `off_value` is `0`. /// /// Other encoding values can be used by setting `on_value` and `off_value` to the desired values. /// /// # Examples /// /// ## One-hot encoding /// /// ```rust /// use candle::{Shape, Tensor, Device}; /// use candle_nn::encoding::one_hot; /// /// let device = candle::Device::Cpu; /// /// let indices = Tensor::new(vec![vec![0i64, 2], vec![1, -1]], &device).unwrap(); /// let depth = 4; /// let one_hot = one_hot(indices, depth, 1f32, 0f32).unwrap(); /// /// let expected_matrix = [ /// [[1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]], /// [[0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0]], /// ]; /// /// assert_eq!(one_hot.shape(), &Shape::from((2, 2, depth))); /// /// let matrix = one_hot.to_vec3::<f32>().unwrap(); /// /// assert_eq!(matrix, expected_matrix); ///``` /// ## One-cold Encoding /// /// ```rust /// use candle::{Shape, Tensor, Device}; /// use candle_nn::encoding::one_hot; /// /// /// let device = candle::Device::Cpu; /// let depth = 4; /// let indices = Tensor::new(vec![vec![0u8, 2], vec![1, 3]], &device).unwrap(); /// let one_cold = one_hot(indices, depth, 0u8, 1u8).unwrap(); /// /// let expected_matrix = [[[0, 1, 1, 1], [1, 1, 0, 1]], [[1, 0, 1, 1], [1, 1, 1, 0]]]; /// /// assert_eq!(one_cold.shape(), &Shape::from((2, 2, depth))); /// /// let matrix = one_cold.to_vec3::<u8>().unwrap(); /// /// assert_eq!(matrix, expected_matrix); /// ``` /// /// /// # Bails /// /// This method bails if: /// - One of the index value is less than -1. /// - One of the index value is greater than or equal to the depth value. /// - The input data type is not `U8`, `U32`, or `I64`. /// /// # API Design /// /// The api design for this method is loosely based on the [TensorFlow One-Hot](https://www.tensorflow.org/api_docs/python/tf/one_hot) method. pub fn one_hot<D: WithDType>( indices: Tensor, depth: usize, on_value: D, off_value: D, ) -> Result<Tensor> { let mut target_shape = indices.dims().to_vec(); target_shape.push(depth); let indices = indices.flatten_all()?; let mut out = vec![off_value; depth * indices.elem_count()]; match indices.dtype() { DType::U8 => { let indices = indices.to_vec1::<u8>()?; for (i, &index) in indices.iter().enumerate() { set_at_index(index, i * depth, depth, &mut out, on_value)?; } } DType::U32 => { let indices = indices.to_vec1::<u32>()?; for (i, &index) in indices.iter().enumerate() { set_at_index(index, i * depth, depth, &mut out, on_value)?; } } DType::I64 => { let indices = indices.to_vec1::<i64>()?; for (i, &index) in indices.iter().enumerate() { set_at_index(index, i * depth, depth, &mut out, on_value)?; } } dtype => { bail!("one_hot: unsupported data type {dtype:?}, expected U8, U32, or I64") } }; Tensor::from_vec(out, target_shape, indices.device()) } fn set_at_index<D: WithDType, I: Into<i64>>( value: I, offset: usize, depth: usize, v: &mut [D], on_value: D, ) -> Result<()> { let value = value.into(); // Skip for an entire row of off_values if value == -1 { return Ok(()); } if value < -1 { bail!( "one_hot: invalid negative index value {value}, expected a positive index value or -1" ); } let value = value as usize; if value >= depth { bail!("one_hot: index value {value} exceeds depth {depth}") } let idx = offset + value; if idx >= v.len() { bail!("one_hot: index out of bounds {idx}, len {}", v.len()); } v[idx] = on_value; Ok(()) }
candle/candle-nn/src/encoding.rs/0
{ "file_path": "candle/candle-nn/src/encoding.rs", "repo_id": "candle", "token_count": 2025 }
49
//! A `VarMap` is a store that holds named variables. //! use candle::{DType, Device, Result, Shape, Tensor, Var}; use std::collections::HashMap; use std::sync::{Arc, Mutex}; /// A `VarMap` is a store that holds named variables. Variables can be retrieved from the stores /// and new variables can be added by providing some initialization config in case they are /// missing. /// `VarMap` structures can be serialized in the safetensors format. #[derive(Clone)] pub struct VarMap { data: Arc<Mutex<HashMap<String, Var>>>, } impl VarMap { /// Create a new empty `VarMap`. #[allow(clippy::new_without_default)] pub fn new() -> Self { let data = Arc::new(Mutex::new(HashMap::new())); Self { data } } /// Retrieve all the variables currently stored in the map. pub fn all_vars(&self) -> Vec<Var> { let tensor_data = self.data.lock().unwrap(); #[allow(clippy::map_clone)] tensor_data.values().map(|c| c.clone()).collect::<Vec<_>>() } /// Save the map in the safetensors format. pub fn save<P: AsRef<std::path::Path>>(&self, path: P) -> Result<()> { let tensor_data = self.data.lock().unwrap(); let data = tensor_data.iter().map(|(k, v)| (k, v.as_tensor())); safetensors::tensor::serialize_to_file(data, &None, path.as_ref())?; Ok(()) } /// Load some values from a safetensors file and modify the existing variables to have these /// values. /// /// Note that values for variables that are currently not in the map are not kept. pub fn load<P: AsRef<std::path::Path>>(&mut self, path: P) -> Result<()> { let path = path.as_ref(); let data = unsafe { candle::safetensors::MmapedSafetensors::new(path)? }; let mut tensor_data = self.data.lock().unwrap(); for (name, var) in tensor_data.iter_mut() { let data = data.load(name, var.device())?; if let Err(err) = var.set(&data) { candle::bail!("error setting {name} using data from {path:?}: {err}",) } } Ok(()) } /// Set a named variable to some value. pub fn set_one<K: AsRef<str>, V: AsRef<Tensor>>(&mut self, name: K, value: V) -> Result<()> { let tensor_data = self.data.lock().unwrap(); let name = name.as_ref(); match tensor_data.get(name) { None => candle::bail!("cannot find {name} in VarMap"), Some(var) => { if let Err(err) = var.set(value.as_ref()) { candle::bail!("error setting {name}: {err}",) } } } Ok(()) } /// Set some named variables to some values. /// /// If an error is returned, some of the variables might have already been set to their new /// values. pub fn set<I: Iterator<Item = (K, V)>, K: AsRef<str>, V: AsRef<Tensor>>( &mut self, iter: I, ) -> Result<()> { let tensor_data = self.data.lock().unwrap(); for (name, value) in iter { let name = name.as_ref(); match tensor_data.get(name) { None => candle::bail!("cannot find {name} in VarMap"), Some(var) => { if let Err(err) = var.set(value.as_ref()) { candle::bail!("error setting {name}: {err}",) } } } } Ok(()) } /// Retrieve or add a new variable. pub fn get<S: Into<Shape>>( &self, shape: S, path: &str, init: crate::Init, dtype: DType, device: &Device, ) -> Result<Tensor> { let shape = shape.into(); let mut tensor_data = self.data.lock().unwrap(); if let Some(tensor) = tensor_data.get(path) { let tensor_shape = tensor.shape(); if &shape != tensor_shape { candle::bail!("shape mismatch on {path}: {shape:?} <> {tensor_shape:?}") } return Ok(tensor.as_tensor().clone()); } let var = init.var(shape, dtype, device)?; let tensor = var.as_tensor().clone(); tensor_data.insert(path.to_string(), var); Ok(tensor) } pub fn data(&self) -> &Mutex<HashMap<String, Var>> { &self.data } }
candle/candle-nn/src/var_map.rs/0
{ "file_path": "candle/candle-nn/src/var_map.rs", "repo_id": "candle", "token_count": 1992 }
50
// // WARNING: This file is automatically generated! Please edit onnx.in.proto. // // SPDX-License-Identifier: Apache-2.0 syntax = "proto3"; package onnx; // Overview // // ONNX is an open specification that is comprised of the following components: // // 1) A definition of an extensible computation graph model. // 2) Definitions of standard data types. // 3) Definitions of built-in operators. // // This document describes the syntax of models and their computation graphs, // as well as the standard data types. Together, they are referred to as the ONNX // Intermediate Representation, or 'IR' for short. // // The normative semantic specification of the ONNX IR is found in docs/IR.md. // Definitions of the built-in neural network operators may be found in docs/Operators.md. // Notes // // Protobuf compatibility // // To simplify framework compatibility, ONNX is defined using the subset of protobuf // that is compatible with both protobuf v2 and v3. This means that we do not use any // protobuf features that are only available in one of the two versions. // // Here are the most notable contortions we have to carry out to work around // these limitations: // // - No 'map' (added protobuf 3.0). We instead represent mappings as lists // of key-value pairs, where order does not matter and duplicates // are not allowed. // Versioning // // ONNX versioning is specified in docs/IR.md and elaborated on in docs/Versioning.md // // To be compatible with both proto2 and proto3, we will use a version number // that is not defined by the default value but an explicit enum number. enum Version { // proto3 requires the first enum value to be zero. // We add this just to appease the compiler. _START_VERSION = 0; // The version field is always serialized and we will use it to store the // version that the graph is generated from. This helps us set up version // control. // For the IR, we are using simple numbers starting with 0x00000001, // which was the version we published on Oct 10, 2017. IR_VERSION_2017_10_10 = 0x0000000000000001; // IR_VERSION 2 published on Oct 30, 2017 // - Added type discriminator to AttributeProto to support proto3 users IR_VERSION_2017_10_30 = 0x0000000000000002; // IR VERSION 3 published on Nov 3, 2017 // - For operator versioning: // - Added new message OperatorSetIdProto // - Added opset_import in ModelProto // - For vendor extensions, added domain in NodeProto IR_VERSION_2017_11_3 = 0x0000000000000003; // IR VERSION 4 published on Jan 22, 2019 // - Relax constraint that initializers should be a subset of graph inputs // - Add type BFLOAT16 IR_VERSION_2019_1_22 = 0x0000000000000004; // IR VERSION 5 published on March 18, 2019 // - Add message TensorAnnotation. // - Add quantization annotation in GraphProto to map tensor with its scale and zero point quantization parameters. IR_VERSION_2019_3_18 = 0x0000000000000005; // IR VERSION 6 published on Sep 19, 2019 // - Add support for sparse tensor constants stored in model. // - Add message SparseTensorProto // - Add sparse initializers IR_VERSION_2019_9_19 = 0x0000000000000006; // IR VERSION 7 published on May 8, 2020 // - Add support to allow function body graph to rely on multiple external opreator sets. // - Add a list to promote inference graph's initializers to global and // mutable variables. Global variables are visible in all graphs of the // stored models. // - Add message TrainingInfoProto to store initialization // method and training algorithm. The execution of TrainingInfoProto // can modify the values of mutable variables. // - Implicitly add inference graph into each TrainingInfoProto's algorithm. IR_VERSION_2020_5_8 = 0x0000000000000007; // IR VERSION 8 published on July 30, 2021 // Introduce TypeProto.SparseTensor // Introduce TypeProto.Optional // Added a list of FunctionProtos local to the model // Deprecated since_version and operator status from FunctionProto IR_VERSION_2021_7_30 = 0x0000000000000008; // IR VERSION 9 published on May 5, 2023 // Added AttributeProto to FunctionProto so that default attribute values can be set. // Added FLOAT8E4M3FN, FLOAT8E4M3FNUZ, FLOAT8E5M2, FLOAT8E5M2FNUZ. IR_VERSION = 0x0000000000000009; } // Attributes // // A named attribute containing either singular float, integer, string, graph, // and tensor values, or repeated float, integer, string, graph, and tensor values. // An AttributeProto MUST contain the name field, and *only one* of the // following content fields, effectively enforcing a C/C++ union equivalent. message AttributeProto { reserved 12, 16 to 19; reserved "v"; // Note: this enum is structurally identical to the OpSchema::AttrType // enum defined in schema.h. If you rev one, you likely need to rev the other. enum AttributeType { UNDEFINED = 0; FLOAT = 1; INT = 2; STRING = 3; TENSOR = 4; GRAPH = 5; SPARSE_TENSOR = 11; TYPE_PROTO = 13; FLOATS = 6; INTS = 7; STRINGS = 8; TENSORS = 9; GRAPHS = 10; SPARSE_TENSORS = 12; TYPE_PROTOS = 14; } // The name field MUST be present for this version of the IR. string name = 1; // namespace Attribute // if ref_attr_name is not empty, ref_attr_name is the attribute name in parent function. // In this case, this AttributeProto does not contain data, and it's a reference of attribute // in parent scope. // NOTE: This should ONLY be used in function (sub-graph). It's invalid to be used in main graph. string ref_attr_name = 21; // A human-readable documentation for this attribute. Markdown is allowed. string doc_string = 13; // The type field MUST be present for this version of the IR. // For 0.0.1 versions of the IR, this field was not defined, and // implementations needed to use has_field heuristics to determine // which value field was in use. For IR_VERSION 0.0.2 or later, this // field MUST be set and match the f|i|s|t|... field in use. This // change was made to accommodate proto3 implementations. AttributeType type = 20; // discriminator that indicates which field below is in use // Exactly ONE of the following fields must be present for this version of the IR float f = 2; // float int64 i = 3; // int bytes s = 4; // UTF-8 string TensorProto t = 5; // tensor value GraphProto g = 6; // graph SparseTensorProto sparse_tensor = 22; // sparse tensor value // Do not use field below, it's deprecated. // optional ValueProto v = 12; // value - subsumes everything but graph TypeProto tp = 14; // type proto repeated float floats = 7; // list of floats repeated int64 ints = 8; // list of ints repeated bytes strings = 9; // list of UTF-8 strings repeated TensorProto tensors = 10; // list of tensors repeated GraphProto graphs = 11; // list of graph repeated SparseTensorProto sparse_tensors = 23; // list of sparse tensors repeated TypeProto type_protos = 15;// list of type protos } // Defines information on value, including the name, the type, and // the shape of the value. message ValueInfoProto { // This field MUST be present in this version of the IR. string name = 1; // namespace Value // This field MUST be present in this version of the IR for // inputs and outputs of the top-level graph. TypeProto type = 2; // A human-readable documentation for this value. Markdown is allowed. string doc_string = 3; } // Nodes // // Computation graphs are made up of a DAG of nodes, which represent what is // commonly called a "layer" or "pipeline stage" in machine learning frameworks. // // For example, it can be a node of type "Conv" that takes in an image, a filter // tensor and a bias tensor, and produces the convolved output. message NodeProto { repeated string input = 1; // namespace Value repeated string output = 2; // namespace Value // An optional identifier for this node in a graph. // This field MAY be absent in ths version of the IR. string name = 3; // namespace Node // The symbolic identifier of the Operator to execute. string op_type = 4; // namespace Operator // The domain of the OperatorSet that specifies the operator named by op_type. string domain = 7; // namespace Domain // Additional named attributes. repeated AttributeProto attribute = 5; // A human-readable documentation for this node. Markdown is allowed. string doc_string = 6; } // Training information // TrainingInfoProto stores information for training a model. // In particular, this defines two functionalities: an initialization-step // and a training-algorithm-step. Initialization resets the model // back to its original state as if no training has been performed. // Training algorithm improves the model based on input data. // // The semantics of the initialization-step is that the initializers // in ModelProto.graph and in TrainingInfoProto.algorithm are first // initialized as specified by the initializers in the graph, and then // updated by the "initialization_binding" in every instance in // ModelProto.training_info. // // The field "algorithm" defines a computation graph which represents a // training algorithm's step. After the execution of a // TrainingInfoProto.algorithm, the initializers specified by "update_binding" // may be immediately updated. If the targeted training algorithm contains // consecutive update steps (such as block coordinate descent methods), // the user needs to create a TrainingInfoProto for each step. message TrainingInfoProto { // This field describes a graph to compute the initial tensors // upon starting the training process. Initialization graph has no input // and can have multiple outputs. Usually, trainable tensors in neural // networks are randomly initialized. To achieve that, for each tensor, // the user can put a random number operator such as RandomNormal or // RandomUniform in TrainingInfoProto.initialization.node and assign its // random output to the specific tensor using "initialization_binding". // This graph can also set the initializers in "algorithm" in the same // TrainingInfoProto; a use case is resetting the number of training // iteration to zero. // // By default, this field is an empty graph and its evaluation does not // produce any output. Thus, no initializer would be changed by default. GraphProto initialization = 1; // This field represents a training algorithm step. Given required inputs, // it computes outputs to update initializers in its own or inference graph's // initializer lists. In general, this field contains loss node, gradient node, // optimizer node, increment of iteration count. // // An execution of the training algorithm step is performed by executing the // graph obtained by combining the inference graph (namely "ModelProto.graph") // and the "algorithm" graph. That is, the actual // input/initializer/output/node/value_info/sparse_initializer list of // the training graph is the concatenation of // "ModelProto.graph.input/initializer/output/node/value_info/sparse_initializer" // and "algorithm.input/initializer/output/node/value_info/sparse_initializer" // in that order. This combined graph must satisfy the normal ONNX conditions. // Now, let's provide a visualization of graph combination for clarity. // Let the inference graph (i.e., "ModelProto.graph") be // tensor_a, tensor_b -> MatMul -> tensor_c -> Sigmoid -> tensor_d // and the "algorithm" graph be // tensor_d -> Add -> tensor_e // The combination process results // tensor_a, tensor_b -> MatMul -> tensor_c -> Sigmoid -> tensor_d -> Add -> tensor_e // // Notice that an input of a node in the "algorithm" graph may reference the // output of a node in the inference graph (but not the other way round). Also, inference // node cannot reference inputs of "algorithm". With these restrictions, inference graph // can always be run independently without training information. // // By default, this field is an empty graph and its evaluation does not // produce any output. Evaluating the default training step never // update any initializers. GraphProto algorithm = 2; // This field specifies the bindings from the outputs of "initialization" to // some initializers in "ModelProto.graph.initializer" and // the "algorithm.initializer" in the same TrainingInfoProto. // See "update_binding" below for details. // // By default, this field is empty and no initializer would be changed // by the execution of "initialization". repeated StringStringEntryProto initialization_binding = 3; // Gradient-based training is usually an iterative procedure. In one gradient // descent iteration, we apply // // x = x - r * g // // where "x" is the optimized tensor, "r" stands for learning rate, and "g" is // gradient of "x" with respect to a chosen loss. To avoid adding assignments // into the training graph, we split the update equation into // // y = x - r * g // x = y // // The user needs to save "y = x - r * g" into TrainingInfoProto.algorithm. To // tell that "y" should be assigned to "x", the field "update_binding" may // contain a key-value pair of strings, "x" (key of StringStringEntryProto) // and "y" (value of StringStringEntryProto). // For a neural network with multiple trainable (mutable) tensors, there can // be multiple key-value pairs in "update_binding". // // The initializers appears as keys in "update_binding" are considered // mutable variables. This implies some behaviors // as described below. // // 1. We have only unique keys in all "update_binding"s so that two // variables may not have the same name. This ensures that one // variable is assigned up to once. // 2. The keys must appear in names of "ModelProto.graph.initializer" or // "TrainingInfoProto.algorithm.initializer". // 3. The values must be output names of "algorithm" or "ModelProto.graph.output". // 4. Mutable variables are initialized to the value specified by the // corresponding initializer, and then potentially updated by // "initializer_binding"s and "update_binding"s in "TrainingInfoProto"s. // // This field usually contains names of trainable tensors // (in ModelProto.graph), optimizer states such as momentums in advanced // stochastic gradient methods (in TrainingInfoProto.graph), // and number of training iterations (in TrainingInfoProto.graph). // // By default, this field is empty and no initializer would be changed // by the execution of "algorithm". repeated StringStringEntryProto update_binding = 4; } // Models // // ModelProto is a top-level file/container format for bundling a ML model and // associating its computation graph with metadata. // // The semantics of the model are described by the associated GraphProto's. message ModelProto { // The version of the IR this model targets. See Version enum above. // This field MUST be present. int64 ir_version = 1; // The OperatorSets this model relies on. // All ModelProtos MUST have at least one entry that // specifies which version of the ONNX OperatorSet is // being imported. // // All nodes in the ModelProto's graph will bind against the operator // with the same-domain/same-op_type operator with the HIGHEST version // in the referenced operator sets. repeated OperatorSetIdProto opset_import = 8; // The name of the framework or tool used to generate this model. // This field SHOULD be present to indicate which implementation/tool/framework // emitted the model. string producer_name = 2; // The version of the framework or tool used to generate this model. // This field SHOULD be present to indicate which implementation/tool/framework // emitted the model. string producer_version = 3; // Domain name of the model. // We use reverse domain names as name space indicators. For example: // `com.facebook.fair` or `com.microsoft.cognitiveservices` // // Together with `model_version` and GraphProto.name, this forms the unique identity of // the graph. string domain = 4; // The version of the graph encoded. See Version enum below. int64 model_version = 5; // A human-readable documentation for this model. Markdown is allowed. string doc_string = 6; // The parameterized graph that is evaluated to execute the model. GraphProto graph = 7; // Named metadata values; keys should be distinct. repeated StringStringEntryProto metadata_props = 14; // Training-specific information. Sequentially executing all stored // `TrainingInfoProto.algorithm`s and assigning their outputs following // the corresponding `TrainingInfoProto.update_binding`s is one training // iteration. Similarly, to initialize the model // (as if training hasn't happened), the user should sequentially execute // all stored `TrainingInfoProto.initialization`s and assigns their outputs // using `TrainingInfoProto.initialization_binding`s. // // If this field is empty, the training behavior of the model is undefined. repeated TrainingInfoProto training_info = 20; // A list of function protos local to the model. // // Name of the function "FunctionProto.name" should be unique within the domain "FunctionProto.domain". // In case of any conflicts the behavior (whether the model local functions are given higher priority, // or standard operator sets are given higher priotity or this is treated as error) is defined by // the runtimes. // // The operator sets imported by FunctionProto should be compatible with the ones // imported by ModelProto and other model local FunctionProtos. // Example, if same operator set say 'A' is imported by a FunctionProto and ModelProto // or by 2 FunctionProtos then versions for the operator set may be different but, // the operator schema returned for op_type, domain, version combination // for both the versions should be same for every node in the function body. // // One FunctionProto can reference other FunctionProto in the model, however, recursive reference // is not allowed. repeated FunctionProto functions = 25; }; // StringStringEntryProto follows the pattern for cross-proto-version maps. // See https://developers.google.com/protocol-buffers/docs/proto3#maps message StringStringEntryProto { string key = 1; string value = 2; }; message TensorAnnotation { string tensor_name = 1; // <key, value> pairs to annotate tensor specified by <tensor_name> above. // The keys used in the mapping below must be pre-defined in ONNX spec. // For example, for 8-bit linear quantization case, 'SCALE_TENSOR', 'ZERO_POINT_TENSOR' will be pre-defined as // quantization parameter keys. repeated StringStringEntryProto quant_parameter_tensor_names = 2; } // Graphs // // A graph defines the computational logic of a model and is comprised of a parameterized // list of nodes that form a directed acyclic graph based on their inputs and outputs. // This is the equivalent of the "network" or "graph" in many deep learning // frameworks. message GraphProto { // The nodes in the graph, sorted topologically. repeated NodeProto node = 1; // The name of the graph. string name = 2; // namespace Graph // A list of named tensor values, used to specify constant inputs of the graph. // Each initializer (both TensorProto as well SparseTensorProto) MUST have a name. // The name MUST be unique across both initializer and sparse_initializer, // but the name MAY also appear in the input list. repeated TensorProto initializer = 5; // Initializers (see above) stored in sparse format. repeated SparseTensorProto sparse_initializer = 15; // A human-readable documentation for this graph. Markdown is allowed. string doc_string = 10; // The inputs and outputs of the graph. repeated ValueInfoProto input = 11; repeated ValueInfoProto output = 12; // Information for the values in the graph. The ValueInfoProto.name's // must be distinct. It is optional for a value to appear in value_info list. repeated ValueInfoProto value_info = 13; // This field carries information to indicate the mapping among a tensor and its // quantization parameter tensors. For example: // For tensor 'a', it may have {'SCALE_TENSOR', 'a_scale'} and {'ZERO_POINT_TENSOR', 'a_zero_point'} annotated, // which means, tensor 'a_scale' and tensor 'a_zero_point' are scale and zero point of tensor 'a' in the model. repeated TensorAnnotation quantization_annotation = 14; reserved 3, 4, 6 to 9; reserved "ir_version", "producer_version", "producer_tag", "domain"; } // Tensors // // A serialized tensor value. message TensorProto { enum DataType { UNDEFINED = 0; // Basic types. FLOAT = 1; // float UINT8 = 2; // uint8_t INT8 = 3; // int8_t UINT16 = 4; // uint16_t INT16 = 5; // int16_t INT32 = 6; // int32_t INT64 = 7; // int64_t STRING = 8; // string BOOL = 9; // bool // IEEE754 half-precision floating-point format (16 bits wide). // This format has 1 sign bit, 5 exponent bits, and 10 mantissa bits. FLOAT16 = 10; DOUBLE = 11; UINT32 = 12; UINT64 = 13; COMPLEX64 = 14; // complex with float32 real and imaginary components COMPLEX128 = 15; // complex with float64 real and imaginary components // Non-IEEE floating-point format based on IEEE754 single-precision // floating-point number truncated to 16 bits. // This format has 1 sign bit, 8 exponent bits, and 7 mantissa bits. BFLOAT16 = 16; // Non-IEEE floating-point format based on papers // FP8 Formats for Deep Learning, https://arxiv.org/abs/2209.05433, // 8-bit Numerical Formats For Deep Neural Networks, https://arxiv.org/pdf/2206.02915.pdf. // Operators supported FP8 are Cast, CastLike, QuantizeLinear, DequantizeLinear. // The computation usually happens inside a block quantize / dequantize // fused by the runtime. FLOAT8E4M3FN = 17; // float 8, mostly used for coefficients, supports nan, not inf FLOAT8E4M3FNUZ = 18; // float 8, mostly used for coefficients, supports nan, not inf, no negative zero FLOAT8E5M2 = 19; // follows IEEE 754, supports nan, inf, mostly used for gradients FLOAT8E5M2FNUZ = 20; // follows IEEE 754, supports nan, inf, mostly used for gradients, no negative zero // Future extensions go here. } // The shape of the tensor. repeated int64 dims = 1; // The data type of the tensor. // This field MUST have a valid TensorProto.DataType value int32 data_type = 2; // For very large tensors, we may want to store them in chunks, in which // case the following fields will specify the segment that is stored in // the current TensorProto. message Segment { int64 begin = 1; int64 end = 2; } Segment segment = 3; // Tensor content must be organized in row-major order. // // Depending on the data_type field, exactly one of the fields below with // name ending in _data is used to store the elements of the tensor. // For float and complex64 values // Complex64 tensors are encoded as a single array of floats, // with the real components appearing in odd numbered positions, // and the corresponding imaginary component appearing in the // subsequent even numbered position. (e.g., [1.0 + 2.0i, 3.0 + 4.0i] // is encoded as [1.0, 2.0 ,3.0 ,4.0] // When this field is present, the data_type field MUST be FLOAT or COMPLEX64. repeated float float_data = 4 [packed = true]; // For int32, uint8, int8, uint16, int16, bool, float8, and float16 values // float16 and float8 values must be bit-wise converted to an uint16_t prior // to writing to the buffer. // When this field is present, the data_type field MUST be // INT32, INT16, INT8, UINT16, UINT8, BOOL, FLOAT16, BFLOAT16, FLOAT8E4M3FN, FLOAT8E4M3FNUZ, FLOAT8E5M2, FLOAT8E5M2FNUZ repeated int32 int32_data = 5 [packed = true]; // For strings. // Each element of string_data is a UTF-8 encoded Unicode // string. No trailing null, no leading BOM. The protobuf "string" // scalar type is not used to match ML community conventions. // When this field is present, the data_type field MUST be STRING repeated bytes string_data = 6; // For int64. // When this field is present, the data_type field MUST be INT64 repeated int64 int64_data = 7 [packed = true]; // Optionally, a name for the tensor. string name = 8; // namespace Value // A human-readable documentation for this tensor. Markdown is allowed. string doc_string = 12; // Serializations can either use one of the fields above, or use this // raw bytes field. The only exception is the string case, where one is // required to store the content in the repeated bytes string_data field. // // When this raw_data field is used to store tensor value, elements MUST // be stored in as fixed-width, little-endian order. // Floating-point data types MUST be stored in IEEE 754 format. // Complex64 elements must be written as two consecutive FLOAT values, real component first. // Complex128 elements must be written as two consecutive DOUBLE values, real component first. // Boolean type MUST be written one byte per tensor element (00000001 for true, 00000000 for false). // // Note: the advantage of specific field rather than the raw_data field is // that in some cases (e.g. int data), protobuf does a better packing via // variable length storage, and may lead to smaller binary footprint. // When this field is present, the data_type field MUST NOT be STRING or UNDEFINED bytes raw_data = 9; // Data can be stored inside the protobuf file using type-specific fields or raw_data. // Alternatively, raw bytes data can be stored in an external file, using the external_data field. // external_data stores key-value pairs describing data location. Recognized keys are: // - "location" (required) - POSIX filesystem path relative to the directory where the ONNX // protobuf model was stored // - "offset" (optional) - position of byte at which stored data begins. Integer stored as string. // Offset values SHOULD be multiples 4096 (page size) to enable mmap support. // - "length" (optional) - number of bytes containing data. Integer stored as string. // - "checksum" (optional) - SHA1 digest of file specified in under 'location' key. repeated StringStringEntryProto external_data = 13; // Location of the data for this tensor. MUST be one of: // - DEFAULT - data stored inside the protobuf message. Data is stored in raw_data (if set) otherwise in type-specified field. // - EXTERNAL - data stored in an external location as described by external_data field. enum DataLocation { DEFAULT = 0; EXTERNAL = 1; } // If value not set, data is stored in raw_data (if set) otherwise in type-specified field. DataLocation data_location = 14; // For double // Complex128 tensors are encoded as a single array of doubles, // with the real components appearing in odd numbered positions, // and the corresponding imaginary component appearing in the // subsequent even numbered position. (e.g., [1.0 + 2.0i, 3.0 + 4.0i] // is encoded as [1.0, 2.0 ,3.0 ,4.0] // When this field is present, the data_type field MUST be DOUBLE or COMPLEX128 repeated double double_data = 10 [packed = true]; // For uint64 and uint32 values // When this field is present, the data_type field MUST be // UINT32 or UINT64 repeated uint64 uint64_data = 11 [packed = true]; } // A serialized sparse-tensor value message SparseTensorProto { // The sequence of non-default values are encoded as a tensor of shape [NNZ]. // The default-value is zero for numeric tensors, and empty-string for string tensors. // values must have a non-empty name present which serves as a name for SparseTensorProto // when used in sparse_initializer list. TensorProto values = 1; // The indices of the non-default values, which may be stored in one of two formats. // (a) Indices can be a tensor of shape [NNZ, rank] with the [i,j]-th value // corresponding to the j-th index of the i-th value (in the values tensor). // (b) Indices can be a tensor of shape [NNZ], in which case the i-th value // must be the linearized-index of the i-th value (in the values tensor). // The linearized-index can be converted into an index tuple (k_1,...,k_rank) // using the shape provided below. // The indices must appear in ascending order without duplication. // In the first format, the ordering is lexicographic-ordering: // e.g., index-value [1,4] must appear before [2,1] TensorProto indices = 2; // The shape of the underlying dense-tensor: [dim_1, dim_2, ... dim_rank] repeated int64 dims = 3; } // Defines a tensor shape. A dimension can be either an integer value // or a symbolic variable. A symbolic variable represents an unknown // dimension. message TensorShapeProto { message Dimension { oneof value { int64 dim_value = 1; string dim_param = 2; // namespace Shape }; // Standard denotation can optionally be used to denote tensor // dimensions with standard semantic descriptions to ensure // that operations are applied to the correct axis of a tensor. // Refer to https://github.com/onnx/onnx/blob/main/docs/DimensionDenotation.md#denotation-definition // for pre-defined dimension denotations. string denotation = 3; }; repeated Dimension dim = 1; } // Types // // The standard ONNX data types. message TypeProto { message Tensor { // This field MUST NOT have the value of UNDEFINED // This field MUST have a valid TensorProto.DataType value // This field MUST be present for this version of the IR. int32 elem_type = 1; TensorShapeProto shape = 2; } // repeated T message Sequence { // The type and optional shape of each element of the sequence. // This field MUST be present for this version of the IR. TypeProto elem_type = 1; }; // map<K,V> message Map { // This field MUST have a valid TensorProto.DataType value // This field MUST be present for this version of the IR. // This field MUST refer to an integral type ([U]INT{8|16|32|64}) or STRING int32 key_type = 1; // This field MUST be present for this version of the IR. TypeProto value_type = 2; }; // wrapper for Tensor, Sequence, or Map message Optional { // The type and optional shape of the element wrapped. // This field MUST be present for this version of the IR. // Possible values correspond to OptionalProto.DataType enum TypeProto elem_type = 1; }; message SparseTensor { // This field MUST NOT have the value of UNDEFINED // This field MUST have a valid TensorProto.DataType value // This field MUST be present for this version of the IR. int32 elem_type = 1; TensorShapeProto shape = 2; } oneof value { // The type of a tensor. Tensor tensor_type = 1; // NOTE: DNN-only implementations of ONNX MAY elect to not support non-tensor values // as input and output to graphs and nodes. These types are needed to naturally // support classical ML operators. DNN operators SHOULD restrict their input // and output types to tensors. // The type of a sequence. Sequence sequence_type = 4; // The type of a map. Map map_type = 5; // The type of an optional. Optional optional_type = 9; // Type of the sparse tensor SparseTensor sparse_tensor_type = 8; } // An optional denotation can be used to denote the whole // type with a standard semantic description as to what is // stored inside. Refer to https://github.com/onnx/onnx/blob/main/docs/TypeDenotation.md#type-denotation-definition // for pre-defined type denotations. string denotation = 6; } // Operator Sets // // OperatorSets are uniquely identified by a (domain, opset_version) pair. message OperatorSetIdProto { // The domain of the operator set being identified. // The empty string ("") or absence of this field implies the operator // set that is defined as part of the ONNX specification. // This field MUST be present in this version of the IR when referring to any other operator set. string domain = 1; // The version of the operator set being identified. // This field MUST be present in this version of the IR. int64 version = 2; } // Operator/function status. enum OperatorStatus { EXPERIMENTAL = 0; STABLE = 1; } message FunctionProto { // The name of the function, similar usage of op_type in OperatorProto. // Combined with FunctionProto.domain, this forms the unique identity of // the FunctionProto. string name = 1; // Deprecated since IR Version 8 // optional int64 since_version = 2; reserved 2; reserved "since_version"; // Deprecated since IR Version 8 // optional OperatorStatus status = 3; reserved 3; reserved "status"; // The inputs and outputs of the function. repeated string input = 4; repeated string output = 5; // The attribute parameters of the function. // It is for function parameters without default values. repeated string attribute = 6; // The attribute protos of the function. // It is for function attributes with default values. // A function attribute shall be represented either as // a string attribute or an AttributeProto, not both. repeated AttributeProto attribute_proto = 11; // The nodes in the function. repeated NodeProto node = 7; // A human-readable documentation for this function. Markdown is allowed. string doc_string = 8; // The OperatorSets this function body (graph) relies on. // // All nodes in the function body (graph) will bind against the operator // with the same-domain/same-op_type operator with the HIGHEST version // in the referenced operator sets. This means at most one version can be relied // for one domain. // // The operator sets imported by FunctionProto should be compatible with the ones // imported by ModelProto. Example, if same operator set say 'A' is imported by FunctionProto // and ModelProto then versions for the operator set may be different but, // the operator schema returned for op_type, domain, version combination // for both the versions should be same. repeated OperatorSetIdProto opset_import = 9; // The domain which this function belongs to. Combined with FunctionProto.name, this forms the unique identity of // the FunctionProto. string domain = 10; } // For using protobuf-lite option optimize_for = LITE_RUNTIME;
candle/candle-onnx/src/onnx.proto3/0
{ "file_path": "candle/candle-onnx/src/onnx.proto3", "repo_id": "candle", "token_count": 10183 }
51
# Generated content DO NOT EDIT from typing import Any, Callable, Dict, List, Optional, Tuple, Union, Sequence from os import PathLike from candle.typing import _ArrayLike, Device, Scalar, Index, Shape from candle import Tensor, DType, QTensor @staticmethod def silu(tensor: Tensor) -> Tensor: """ Applies the Sigmoid Linear Unit (SiLU) function to a given tensor. """ pass @staticmethod def softmax(tensor: Tensor, dim: int) -> Tensor: """ Applies the Softmax function to a given tensor.# """ pass
candle/candle-pyo3/py_src/candle/nn/__init__.pyi/0
{ "file_path": "candle/candle-pyo3/py_src/candle/nn/__init__.pyi", "repo_id": "candle", "token_count": 181 }
52
use ::candle::Tensor; use pyo3::prelude::*; #[derive(Clone, Debug)] /// Represents an absolute shape e.g. (1, 2, 3) pub struct PyShape(Vec<usize>); impl<'source> pyo3::FromPyObject<'source> for PyShape { fn extract_bound(ob: &Bound<'source, PyAny>) -> PyResult<Self> { if ob.is_none() { return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>( "Shape cannot be None", )); } let tuple = ob.downcast::<pyo3::types::PyTuple>()?; if tuple.len() == 1 { let first_element = tuple.get_item(0)?; let dims: Vec<usize> = pyo3::FromPyObject::extract_bound(&first_element)?; Ok(PyShape(dims)) } else { let dims: Vec<usize> = pyo3::FromPyObject::extract_bound(tuple)?; Ok(PyShape(dims)) } } } impl From<PyShape> for ::candle::Shape { fn from(val: PyShape) -> Self { val.0.into() } } #[derive(Clone, Debug)] /// Represents a shape with a hole in it e.g. (1, -1, 3) pub struct PyShapeWithHole(Vec<isize>); impl<'source> pyo3::FromPyObject<'source> for PyShapeWithHole { fn extract_bound(ob: &Bound<'source, PyAny>) -> PyResult<Self> { if ob.is_none() { return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>( "Shape cannot be None", )); } let tuple = ob.downcast::<pyo3::types::PyTuple>()?; let dims: Vec<isize> = if tuple.len() == 1 { let first_element = tuple.get_item(0)?; pyo3::FromPyObject::extract_bound(&first_element)? } else { pyo3::FromPyObject::extract_bound(tuple)? }; // Ensure we have only positive numbers and at most one "hole" (-1) let negative_ones = dims.iter().filter(|&&x| x == -1).count(); let any_invalid_dimensions = dims.iter().any(|&x| x < -1 || x == 0); if negative_ones > 1 || any_invalid_dimensions { return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!( "Invalid dimension in shape: {dims:?}" ))); } Ok(PyShapeWithHole(dims)) } } impl PyShapeWithHole { /// Returns `true` if the shape is absolute e.g. (1, 2, 3) pub fn is_absolute(&self) -> bool { self.0.iter().all(|x| *x > 0) } /// Convert a relative shape to an absolute shape e.g. (1, -1) -> (1, 12) pub fn to_absolute(&self, t: &Tensor) -> PyResult<PyShape> { if self.is_absolute() { return Ok(PyShape( self.0.iter().map(|x| *x as usize).collect::<Vec<usize>>(), )); } let mut elements = t.elem_count(); let mut new_dims: Vec<usize> = vec![]; for dim in self.0.iter() { if *dim > 0 { new_dims.push(*dim as usize); elements /= *dim as usize; } else if *dim == -1 { new_dims.push(elements); } else { return Err(PyErr::new::<pyo3::exceptions::PyValueError, _>(format!( "Invalid dimension in shape: {dim}" ))); } } Ok(PyShape(new_dims)) } }
candle/candle-pyo3/src/shape.rs/0
{ "file_path": "candle/candle-pyo3/src/shape.rs", "repo_id": "candle", "token_count": 1628 }
53
//! Based from the Stanford Hazy Research group. //! //! See "Simple linear attention language models balance the recall-throughput tradeoff", Arora et al. 2024 //! - Simple linear attention language models balance the recall-throughput tradeoff. [Arxiv](https://arxiv.org/abs/2402.18668) //! - [Github Rep](https://github.com/HazyResearch/based) //! - [Blogpost](https://hazyresearch.stanford.edu/blog/2024-03-03-based) use candle::{DType, Device, IndexOp, Module, Result, Tensor, D}; use candle_nn::{ conv1d_no_bias, linear, linear_no_bias, ops::softmax_last_dim, rms_norm, Conv1d, Conv1dConfig, Func, Linear, RmsNorm, VarBuilder, }; use std::sync::Arc; #[derive(Debug, Clone, serde::Deserialize)] pub struct LinearAttentionFeatureMapConfig { input_dim: usize, } #[derive(Debug, Clone, serde::Deserialize)] pub struct LinearAttentionConfig { num_heads: usize, feature_dim: usize, feature_map: LinearAttentionFeatureMapConfig, } #[derive(Debug, Clone, serde::Deserialize)] pub struct SlidingWindowAttentionConfig { num_heads: usize, window_size: usize, } #[derive(Debug, Clone, serde::Deserialize)] pub struct Config { vocab_size: usize, #[serde(rename = "n_embd")] hidden_size: usize, #[serde(rename = "n_inner")] intermediate_size: usize, #[serde(rename = "n_layer")] num_hidden_layers: usize, #[serde(rename = "n_head")] num_attention_heads: usize, layer_norm_epsilon: f64, #[serde(default = "default_rope", rename = "rotary_emb_base")] rope_theta: f64, alt_mixer_layers: Vec<usize>, alt_mixer_2_layers: Vec<usize>, #[serde(rename = "alt_mixer")] la: LinearAttentionConfig, #[serde(rename = "alt_mixer_2")] swa: SlidingWindowAttentionConfig, } fn default_rope() -> f64 { 10_000.0 } #[derive(Debug, Clone)] #[allow(clippy::upper_case_acronyms)] struct MLP { fc1: Linear, fc2: Linear, } impl MLP { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let fc1 = linear_no_bias(cfg.hidden_size, cfg.hidden_size * 4, vb.pp("fc1"))?; let fc2 = linear_no_bias(cfg.intermediate_size, cfg.hidden_size, vb.pp("fc2"))?; Ok(Self { fc1, fc2 }) } } // Swiglu implementation. // Not using Activation::Swiglu because this has the gate and y arguments switched compared to the version in candle-nn/src/ops.rs fn swiglu(xs: &Tensor) -> Result<Tensor> { let xs = xs.chunk(2, D::Minus1)?; &xs[1].silu()? * &xs[0] } impl Module for MLP { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let xs = xs.apply(&self.fc1)?; let xs = swiglu(&xs)?; let xs = xs.apply(&self.fc2)?; Ok(xs) } } // A gated convolutional block. #[derive(Debug, Clone)] struct BasedConv { in_proj: Linear, out_proj: Linear, conv: Conv1d, state: Tensor, } impl BasedConv { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let dim = cfg.hidden_size * 2; let conv1d_cfg = Conv1dConfig { groups: dim, padding: 2, ..Default::default() }; let in_proj = linear(cfg.hidden_size, cfg.hidden_size * 4, vb.pp("in_proj"))?; let out_proj = linear(dim, cfg.hidden_size, vb.pp("out_proj"))?; let conv = conv1d_no_bias(dim, dim, 3, conv1d_cfg, vb.pp("conv.conv"))?; let state = Tensor::zeros((1, dim, 3), vb.dtype(), vb.device())?; Ok(Self { in_proj, out_proj, conv, state, }) } fn step(&mut self, xs: &Tensor) -> Result<Tensor> { self.state = self.state.roll(-1, D::Minus1)?; let (_, _, l) = self.state.dims3()?; self.state = self.state.narrow(D::Minus1, 0, l - 1)?; self.state = Tensor::cat(&[&self.state, &xs.transpose(1, 2)?], 2)?; let xs = (&self.state * self.conv.weight().permute((1, 0, 2))?)? .sum_keepdim(0)? .sum(D::Minus1)?; let xs = xs.unsqueeze(1)?; Ok(xs) } fn forward(&mut self, xs: &Tensor, seqlen_offset: usize) -> Result<Tensor> { let xs = xs.apply(&self.in_proj)?; let us = xs.chunk(2, D::Minus1)?; let (_b, l, _d) = us[0].dims3()?; let u_conv = if seqlen_offset > 0 { self.step(&us[0])? } else { let k = std::cmp::min(3, l); self.state = self.state.narrow(D::Minus1, 0, 3 - k)?; let xs = us[0].narrow(1, l - k, k)?.transpose(1, 2)?; self.state = Tensor::cat(&[&self.state, &xs], 2)?; us[0] .transpose(1, 2)? .apply(&self.conv)? .narrow(D::Minus1, 0, l)? .transpose(1, 2)? }; let u_conv = u_conv.silu()?; let v = u_conv.broadcast_mul(&us[1])?; let xs = v.apply(&self.out_proj)?; Ok(xs) } } // Linear attention approximating softmax using second order Taylor polynomials. #[derive(Debug, Clone)] struct LinearAttention { proj_q: Linear, proj_k: Linear, proj_v: Linear, out_proj: Linear, feature_dim: usize, num_heads: usize, input_dim: usize, k_state: Tensor, kv_state: Tensor, } impl LinearAttention { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let input_dim = cfg.la.feature_map.input_dim; let out_proj = linear_no_bias(cfg.hidden_size, cfg.hidden_size, vb.pp("out_proj"))?; let proj_k = linear_no_bias( cfg.hidden_size, cfg.la.num_heads * cfg.la.feature_dim, vb.pp("proj_k"), )?; let proj_q = linear_no_bias( cfg.hidden_size, cfg.la.num_heads * cfg.la.feature_dim, vb.pp("proj_q"), )?; let proj_v = linear_no_bias(cfg.hidden_size, cfg.hidden_size, vb.pp("proj_v"))?; let expanded_size = cfg.la.feature_dim.pow(2) + cfg.la.feature_dim + 1; let k_state = Tensor::zeros( (1, cfg.la.num_heads, 1, 1, expanded_size), vb.dtype(), vb.device(), )?; let kv_state = Tensor::zeros( (1, cfg.la.num_heads, cfg.la.feature_dim, expanded_size), vb.dtype(), vb.device(), )?; Ok(Self { proj_q, proj_k, proj_v, out_proj, feature_dim: cfg.la.feature_dim, num_heads: cfg.la.num_heads, input_dim, k_state, kv_state, }) } fn taylor_expansion(&self) -> Result<Func<'static>> { let r2 = std::f64::consts::SQRT_2; let rd = (self.input_dim as f64).sqrt(); let rrd = rd.sqrt(); Ok(Func::new(move |xs| { let dims = xs.dims(); let mut d = dims.to_vec(); if let Some(last) = d.last_mut() { *last = 1; }; let x = xs .unsqueeze(D::Minus1)? .broadcast_mul(&xs.unsqueeze(D::Minus2)?)?; let x = (x.flatten_from(D::Minus2)? / r2)?; let o = Tensor::ones(d, xs.dtype(), xs.device())?; let x = Tensor::cat(&[o, (xs / rrd)?, (&x / rd)?], D::Minus1)?; Ok(x) })) } fn forward(&mut self, xs: &Tensor, seqlen_offset: usize) -> Result<Tensor> { let eps = 1e-12; let feature_map = self.taylor_expansion()?; let (b, l, d) = xs.dims3()?; let q = xs.apply(&self.proj_q)?; let k = xs.apply(&self.proj_k)?; let v = xs.apply(&self.proj_v)?; let q = q .reshape((b, l, self.num_heads, self.feature_dim))? .transpose(1, 2)? .contiguous()?; let k = k .reshape((b, l, self.num_heads, self.feature_dim))? .transpose(1, 2)? .contiguous()?; let v = v .reshape((b, l, self.num_heads, d / self.num_heads))? .transpose(1, 2)? .contiguous()?; let q = feature_map.forward(&q)?; let k = feature_map.forward(&k)?; let y = if seqlen_offset > 0 { let (_b, _h, l, _d) = k.dims4()?; let q = q.unsqueeze(D::Minus2)?; let k = k.unsqueeze(D::Minus2)?; let v = v.unsqueeze(D::Minus1)?; let kn = k.narrow(D::Minus1, l - 1, 1)?; let vn = v.narrow(D::Minus1, l - 1, 1)?; self.k_state = self.k_state.broadcast_add(&kn)?; self.kv_state = self.kv_state.broadcast_add(&kn.broadcast_mul(&vn)?)?; let num = q.broadcast_mul(&self.kv_state)?.sum(D::Minus1)?; let den = (q.broadcast_mul(&self.k_state)?.sum(D::Minus1)? + eps)?; num.broadcast_div(&den)? } else { self.k_state = k.sum(2)?.unsqueeze(2)?.unsqueeze(3)?; self.kv_state = k .transpose(2, 3)? .matmul(&v)? .transpose(2, 3)? .unsqueeze(2)?; let aqk = q.matmul(&k.transpose(D::Minus1, D::Minus2)?)?; let tril = Tensor::tril2(l, aqk.dtype(), aqk.device())?; let aqk = aqk.broadcast_mul(&tril)?.matmul(&v)?; let z = (1f64 / (q.mul(&k.cumsum(2)?)?.sum(D::Minus1)? + eps)?)?; aqk.broadcast_mul(&z.unsqueeze(D::Minus1)?)? }; let (b, h, l, d) = y.dims4()?; let y = y.permute((0, 2, 1, 3))?.reshape((b, l, h * d))?; let y = self.out_proj.forward(&y)?; Ok(y) } } // Rotary embeddings used in local attention. #[derive(Debug, Clone)] struct RotaryEmbedding { sin: Tensor, cos: Tensor, } impl RotaryEmbedding { fn new(dtype: DType, cfg: &Config, dev: &Device) -> Result<Self> { let dim = cfg.hidden_size / cfg.num_attention_heads; let max_seq_len = 2048; // Hardcoded, missing from config. 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)) } } // Local attention using a small sliding window. #[derive(Debug, Clone)] struct SlidingWindowAttention { wqkv: Linear, out_proj: Linear, num_heads: usize, head_dim: usize, hidden_size: usize, rotary_emb: Arc<RotaryEmbedding>, kv_cache: Option<(Tensor, Tensor)>, } impl SlidingWindowAttention { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let hidden_size = cfg.hidden_size; let num_heads = cfg.swa.num_heads; let head_dim = hidden_size / num_heads; let out_proj = linear_no_bias(hidden_size, hidden_size, vb.pp("out_proj"))?; let wqkv = linear_no_bias(hidden_size, hidden_size * 3, vb.pp("Wqkv"))?; let rotary_emb = Arc::new(RotaryEmbedding::new(vb.dtype(), cfg, vb.device())?); Ok(Self { wqkv, out_proj, hidden_size, num_heads, head_dim, rotary_emb, kv_cache: None, }) } fn forward( &mut self, xs: &Tensor, attention_mask: Option<&Tensor>, seqlen_offset: usize, ) -> Result<Tensor> { let (b_sz, q_len, _) = xs.dims3()?; let qkv = xs.apply(&self.wqkv)?; let qkv = qkv.reshape((b_sz, q_len, 3, (), self.head_dim))?; let q = qkv.i((.., .., 0))?; let k = qkv.i((.., .., 1))?; let v = qkv.i((.., .., 2))?; let q = q .reshape((b_sz, q_len, self.num_heads, self.head_dim))? .transpose(1, 2)?; let k = k .reshape((b_sz, q_len, self.num_heads, self.head_dim))? .transpose(1, 2)?; let v = v .reshape((b_sz, q_len, self.num_heads, self.head_dim))? .transpose(1, 2)?; let (q, k) = self .rotary_emb .apply_rotary_emb_qkv(&q, &k, seqlen_offset)?; let (k, v) = match &self.kv_cache { None => (k, v), Some((prev_k, prev_v)) => { let k = Tensor::cat(&[prev_k, &k], 2)?; let v = Tensor::cat(&[prev_v, &v], 2)?; (k, v) } }; self.kv_cache = Some((k.clone(), v.clone())); let scale = 1f64 / f64::sqrt(self.head_dim as f64); let attn_weights = (q.matmul(&k.transpose(2, 3)?)? * scale)?; let attn_weights = match attention_mask { None => attn_weights, Some(mask) => attn_weights.broadcast_add(mask)?, }; let attn_weights = softmax_last_dim(&attn_weights)?; let attn_output = attn_weights.matmul(&v)?; let out = attn_output .transpose(1, 2)? .reshape((b_sz, q_len, self.hidden_size))? .apply(&self.out_proj)?; Ok(out) } } // The model layers use three types of mixers. #[derive(Debug, Clone)] enum SequenceMixer { Based(BasedConv), Linear(LinearAttention), Sliding(SlidingWindowAttention), } impl SequenceMixer { fn forward( &mut self, xs: &Tensor, attention_mask: Option<&Tensor>, pos: usize, ) -> Result<Tensor> { match self { Self::Based(b) => b.forward(xs, pos), Self::Linear(b) => b.forward(xs, pos), Self::Sliding(b) => b.forward(xs, attention_mask, pos), } } } #[derive(Debug, Clone)] struct DecoderLayer { mlp: MLP, norm1: RmsNorm, norm2: RmsNorm, mixer: SequenceMixer, } impl DecoderLayer { fn new(layer_idx: usize, cfg: &Config, vb: VarBuilder) -> Result<Self> { let mlp = MLP::new(cfg, vb.pp("mlp"))?; let norm1 = rms_norm(cfg.hidden_size, cfg.layer_norm_epsilon, vb.pp("norm1"))?; let norm2 = rms_norm(cfg.hidden_size, cfg.layer_norm_epsilon, vb.pp("norm2"))?; let l_attn = cfg.alt_mixer_layers.contains(&layer_idx); let sw_attn = cfg.alt_mixer_2_layers.contains(&layer_idx); let mixer = if l_attn { SequenceMixer::Linear(LinearAttention::new(cfg, vb.pp("mixer"))?) } else if sw_attn { SequenceMixer::Sliding(SlidingWindowAttention::new(cfg, vb.pp("mixer"))?) } else { SequenceMixer::Based(BasedConv::new(cfg, vb.pp("mixer"))?) }; Ok(Self { mlp, norm1, norm2, mixer, }) } fn forward( &mut self, xs: &Tensor, attention_mask: Option<&Tensor>, seqlen_offset: usize, ) -> Result<Tensor> { let residual = xs; let xs = self.norm1.forward(xs)?; let xs = self.mixer.forward(&xs, attention_mask, seqlen_offset)?; let xs = (xs + residual)?; let residual = &xs; let xs = xs.apply(&self.norm2)?.apply(&self.mlp)?; residual + xs } } #[derive(Debug, Clone)] pub struct Model { embed_tokens: super::with_tracing::Embedding, layers: Vec<DecoderLayer>, norm: RmsNorm, lm_head: Linear, sliding_window: usize, device: Device, dtype: DType, } impl Model { pub fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let vocab_size = cfg.vocab_size + (8 - cfg.vocab_size % 8) % 8; let lm_head = linear_no_bias(cfg.hidden_size, vocab_size, vb.pp("lm_head"))?; let embed_tokens = super::with_tracing::Embedding::from_weights(lm_head.weight().clone())?; let vb_m = vb.pp("transformer"); 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(layer_idx, cfg, vb_l.pp(layer_idx))?; layers.push(layer) } let norm = rms_norm(cfg.hidden_size, cfg.layer_norm_epsilon, vb_m.pp("ln_f"))?; Ok(Self { embed_tokens, layers, norm, lm_head, sliding_window: cfg.swa.window_size, device: vb.device().clone(), dtype: vb.dtype(), }) } fn prepare_decoder_attention_mask( &self, b_size: usize, tgt_len: usize, seqlen_offset: usize, ) -> Result<Tensor> { let sliding_window = self.sliding_window / 2; let mask: Vec<_> = (0..tgt_len) .flat_map(|i| { (0..tgt_len).map(move |j| { if i < j || j + sliding_window < i { 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), self.dtype, &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 mut xs = self.embed_tokens.forward(input_ids)?; 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) } }
candle/candle-transformers/src/models/based.rs/0
{ "file_path": "candle/candle-transformers/src/models/based.rs", "repo_id": "candle", "token_count": 9967 }
54
//! ConvNeXt implementation. //! //! This candle implementation uses a pre-trained ConvNeXt network for inference. The //! classification head has been trained on the ImageNet dataset and returns the //! probabilities for the top-5 classes. //! //! Original code: //! - 💻 [ConvNeXt](https://github.com/facebookresearch/ConvNeXt/) //! - 💻 [ConvNeXt-V2](https://github.com/facebookresearch/ConvNeXt-V2/) //! - 💻 [timm](https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/convnext.py) //! - 📝 [Paper](https://arxiv.org/abs/2201.03545) A ConvNet for the 2020s //! - 📝 [Paper](https://arxiv.org/abs/2301.00808) ConvNeXt V2: Co-designing and Scaling ConvNets with Masked Autoencoders //! use candle::shape::ShapeWithOneHole; use candle::{Result, D}; use candle_nn::{conv2d, layer_norm, linear, Conv2dConfig, Func, VarBuilder}; #[derive(Clone)] pub struct Config { blocks: [usize; 4], channels: [usize; 4], use_conv_mlp: bool, } impl Config { pub fn atto() -> Self { Self { blocks: [2, 2, 6, 2], channels: [40, 80, 160, 320], use_conv_mlp: true, } } pub fn femto() -> Self { Self { blocks: [2, 2, 6, 2], channels: [48, 96, 192, 384], use_conv_mlp: true, } } pub fn pico() -> Self { Self { blocks: [2, 2, 6, 2], channels: [64, 128, 256, 512], use_conv_mlp: true, } } pub fn nano() -> Self { Self { blocks: [2, 2, 8, 2], channels: [80, 160, 320, 640], use_conv_mlp: true, } } pub fn tiny() -> Self { Self { blocks: [3, 3, 9, 3], channels: [96, 192, 384, 768], use_conv_mlp: false, } } pub fn small() -> Self { Self { blocks: [3, 3, 27, 3], channels: [96, 192, 384, 768], use_conv_mlp: false, } } pub fn base() -> Self { Self { blocks: [3, 3, 27, 3], channels: [128, 256, 512, 1024], use_conv_mlp: false, } } pub fn large() -> Self { Self { blocks: [3, 3, 27, 3], channels: [192, 384, 768, 1536], use_conv_mlp: false, } } pub fn xlarge() -> Self { Self { blocks: [3, 3, 27, 3], channels: [256, 512, 1024, 2048], use_conv_mlp: false, } } pub fn huge() -> Self { Self { blocks: [3, 3, 27, 3], channels: [352, 704, 1408, 2816], use_conv_mlp: false, } } } // Layer norm for data in channels-last format. fn layer_norm_cl(dim: usize, vb: VarBuilder) -> Result<Func<'static>> { let norm = layer_norm(dim, 1e-6, vb)?; Ok(Func::new(move |xs| xs.apply(&norm))) } // Layer norm for data in channels-first format. fn layer_norm_cf(dim: usize, vb: VarBuilder) -> Result<Func<'static>> { let norm = layer_norm(dim, 1e-6, vb)?; Ok(Func::new(move |xs| { let xs = xs .permute((0, 2, 3, 1))? .apply(&norm)? .permute((0, 3, 1, 2))?; Ok(xs) })) } // Global response normalization layer // Based on https://github.com/huggingface/pytorch-image-models/blob/main/timm/layers/grn.py fn convnext2_grn(dim: usize, channels_last: bool, vb: VarBuilder) -> Result<Func<'static>> { let (shape, spatial_dim, channel_dim) = if channels_last { ((1, 1, 1, ()).into_shape(dim)?, [1, 2], 3) } else { ((1, (), 1, 1).into_shape(dim)?, [2, 3], 1) }; let gamma = vb.get(dim, "weight")?.reshape(&shape)?; let beta = vb.get(dim, "bias")?.reshape(&shape)?; Ok(Func::new(move |xs| { let residual = xs; let gx = xs .sqr()? .sum_keepdim(spatial_dim)? .mean_keepdim(spatial_dim)? .sqrt()?; let gxmean = gx.mean_keepdim(channel_dim)?; let nx = gx.broadcast_div(&(gxmean + 1e-6)?)?; let xs = xs .broadcast_mul(&nx)? .broadcast_mul(&gamma)? .broadcast_add(&beta)?; xs + residual })) } // Initial downsampling via a patchify layer. fn convnext_stem(out_channels: usize, vb: VarBuilder) -> Result<Func<'static>> { let conv2d_cfg = Conv2dConfig { stride: 4, ..Default::default() }; let patchify = conv2d(3, out_channels, 4, conv2d_cfg, vb.pp(0))?; let norm = layer_norm_cf(out_channels, vb.pp(1))?; Ok(Func::new(move |xs| xs.apply(&patchify)?.apply(&norm))) } // Downsampling applied after the stages. fn convnext_downsample(dim: usize, vb: VarBuilder) -> Result<Func<'static>> { let conv2d_cfg = Conv2dConfig { stride: 2, ..Default::default() }; let norm = layer_norm_cf(dim / 2, vb.pp(0))?; let conv = conv2d(dim / 2, dim, 2, conv2d_cfg, vb.pp(1))?; Ok(Func::new(move |xs| xs.apply(&norm)?.apply(&conv))) } // MLP block from the original paper with optional GRN layer (v2 models). fn convnext_mlp(dim: usize, vb: VarBuilder) -> Result<Func<'static>> { let fc1 = linear(dim, 4 * dim, vb.pp("fc1"))?; let fc2 = linear(4 * dim, dim, vb.pp("fc2"))?; let grn = convnext2_grn(4 * dim, true, vb.pp("grn")); Ok(Func::new(move |xs| { let mut xs = xs.apply(&fc1)?.gelu_erf()?; if let Ok(g) = &grn { xs = xs.apply(g)?; } xs = xs.apply(&fc2)?; Ok(xs) })) } // MLP block using pointwise convolutions, with optional GRN layer (v2 models). fn convnext_conv_mlp(dim: usize, vb: VarBuilder) -> Result<Func<'static>> { let conv2d_cfg = Conv2dConfig { ..Default::default() }; let fc1 = conv2d(dim, 4 * dim, 1, conv2d_cfg, vb.pp("fc1"))?; let fc2 = conv2d(4 * dim, dim, 1, conv2d_cfg, vb.pp("fc2"))?; let grn = convnext2_grn(4 * dim, false, vb.pp("grn")); Ok(Func::new(move |xs| { let mut xs = xs.apply(&fc1)?.gelu_erf()?; if let Ok(g) = &grn { xs = xs.apply(g)?; } xs = xs.apply(&fc2)?; Ok(xs) })) } // A block consisting of a depthwise convolution, a MLP and layer scaling (v1 models only). fn convnext_block(dim: usize, use_conv_mlp: bool, vb: VarBuilder) -> Result<Func<'static>> { let conv2d_cfg = Conv2dConfig { groups: dim, padding: 3, ..Default::default() }; let conv_dw = conv2d(dim, dim, 7, conv2d_cfg, vb.pp("conv_dw"))?; let gamma = vb.get(dim, "gamma"); let (mlp, norm) = if use_conv_mlp { ( convnext_conv_mlp(dim, vb.pp("mlp"))?, layer_norm_cf(dim, vb.pp("norm"))?, ) } else { ( convnext_mlp(dim, vb.pp("mlp"))?, layer_norm_cl(dim, vb.pp("norm"))?, ) }; Ok(Func::new(move |xs| { let residual = xs; let mut xs = xs.apply(&conv_dw)?; xs = if use_conv_mlp { xs.apply(&norm)?.apply(&mlp)? } else { xs.permute((0, 2, 3, 1))? .apply(&norm)? .apply(&mlp)? .permute((0, 3, 1, 2))? }; if let Ok(g) = &gamma { xs = xs.broadcast_mul(&g.reshape((1, (), 1, 1))?)?; }; xs + residual })) } // Each stage contains blocks and a downsampling layer for the previous stage. fn convnext_stage(cfg: &Config, stage_idx: usize, vb: VarBuilder) -> Result<Func<'static>> { let nblocks = cfg.blocks[stage_idx]; let mut blocks = Vec::with_capacity(nblocks); let dim = cfg.channels[stage_idx]; if stage_idx > 0 { blocks.push(convnext_downsample(dim, vb.pp("downsample"))?); } for block_idx in 0..nblocks { blocks.push(convnext_block( dim, cfg.use_conv_mlp, vb.pp(format!("blocks.{block_idx}")), )?); } Ok(Func::new(move |xs| { let mut xs = xs.clone(); for block in blocks.iter() { xs = xs.apply(block)? } Ok(xs) })) } // Classification head. fn convnext_head(outputs: usize, nclasses: usize, vb: VarBuilder) -> Result<Func<'static>> { let norm = layer_norm_cl(outputs, vb.pp("norm"))?; let linear = linear(outputs, nclasses, vb.pp("fc"))?; Ok(Func::new(move |xs| xs.apply(&norm)?.apply(&linear))) } // Build a convnext model for a given configuration. fn convnext_model( config: &Config, nclasses: Option<usize>, vb: VarBuilder, ) -> Result<Func<'static>> { let head = match nclasses { None => None, Some(nclasses) => { let head = convnext_head(config.channels[3], nclasses, vb.pp("head"))?; Some(head) } }; let stem = convnext_stem(config.channels[0], vb.pp("stem"))?; let vb = vb.pp("stages"); let stage1 = convnext_stage(config, 0, vb.pp(0))?; let stage2 = convnext_stage(config, 1, vb.pp(1))?; let stage3 = convnext_stage(config, 2, vb.pp(2))?; let stage4 = convnext_stage(config, 3, vb.pp(3))?; Ok(Func::new(move |xs| { let xs = xs .apply(&stem)? .apply(&stage1)? .apply(&stage2)? .apply(&stage3)? .apply(&stage4)? .mean(D::Minus2)? .mean(D::Minus1)?; match &head { None => Ok(xs), Some(head) => xs.apply(head), } })) } pub fn convnext(cfg: &Config, nclasses: usize, vb: VarBuilder) -> Result<Func<'static>> { convnext_model(cfg, Some(nclasses), vb) } pub fn convnext_no_final_layer(cfg: &Config, vb: VarBuilder) -> Result<Func<'static>> { convnext_model(cfg, None, vb) }
candle/candle-transformers/src/models/convnext.rs/0
{ "file_path": "candle/candle-transformers/src/models/convnext.rs", "repo_id": "candle", "token_count": 4949 }
55
//! Flux Model //! //! Flux is a 12B rectified flow transformer capable of generating images from text descriptions. //! //! - 🤗 [Hugging Face Model](https://huggingface.co/black-forest-labs/FLUX.1-schnell) //! - 💻 [GitHub Repository](https://github.com/black-forest-labs/flux) //! - 📝 [Blog Post](https://blackforestlabs.ai/announcing-black-forest-labs/) //! //! # Usage //! //! ```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" //! ``` //! //! <div align=center> //! <img src="https://github.com/huggingface/candle/raw/main/candle-examples/examples/flux/assets/flux-robot.jpg" alt="" width=320> //! </div> //! use candle::{Result, Tensor}; pub trait WithForward { #[allow(clippy::too_many_arguments)] fn forward( &self, img: &Tensor, img_ids: &Tensor, txt: &Tensor, txt_ids: &Tensor, timesteps: &Tensor, y: &Tensor, guidance: Option<&Tensor>, ) -> Result<Tensor>; } pub mod autoencoder; pub mod model; pub mod quantized_model; pub mod sampling;
candle/candle-transformers/src/models/flux/mod.rs/0
{ "file_path": "candle/candle-transformers/src/models/flux/mod.rs", "repo_id": "candle", "token_count": 530 }
56
use std::collections::HashMap; use crate::models::{ clip::{text_model::Activation, vision_model::ClipVisionConfig}, llama::{Config, LlamaEosToks}, }; use serde::{Deserialize, Serialize}; // original config from liuhaotian/llava #[derive(Serialize, Deserialize, Debug, Clone)] pub struct LLaVAConfig { pub architectures: Vec<String>, pub bos_token_id: usize, pub eos_token_id: usize, pub hidden_size: usize, #[serde(default = "default_image_aspect_ratio")] pub image_aspect_ratio: String, pub image_crop_resolution: usize, pub image_grid_pinpoints: Vec<(u32, u32)>, pub image_split_resolution: usize, pub intermediate_size: usize, pub max_position_embeddings: usize, pub mm_hidden_size: usize, #[serde(default = "default_mm_patch_merge_type")] pub mm_patch_merge_type: String, pub mm_projector_type: String, pub mm_use_im_start_end: bool, pub mm_vision_select_feature: String, pub mm_vision_select_layer: isize, pub mm_vision_tower: Option<String>, pub model_type: String, pub num_attention_heads: usize, pub num_hidden_layers: usize, pub num_key_value_heads: usize, pub pad_token_id: usize, pub rms_norm_eps: f32, pub rope_theta: f32, pub tokenizer_model_max_length: Option<usize>, pub torch_dtype: String, pub use_cache: bool, pub vocab_size: usize, #[serde(default = "default_image_token_index")] pub image_token_index: isize, #[serde(default = "default_hf")] pub hf: bool, pub tie_word_embeddings: Option<bool>, } fn default_hf() -> bool { false } fn default_image_token_index() -> isize { -200 } fn default_mm_patch_merge_type() -> String { "flat".to_string() } fn default_image_aspect_ratio() -> String { "square".to_string() } impl LLaVAConfig { pub fn to_llama_config(&self) -> Config { Config { hidden_size: self.hidden_size, intermediate_size: self.intermediate_size, vocab_size: self.vocab_size, num_hidden_layers: self.num_hidden_layers, num_attention_heads: self.num_attention_heads, num_key_value_heads: self.num_key_value_heads, rms_norm_eps: self.rms_norm_eps as f64, rope_theta: self.rope_theta, bos_token_id: Some(self.bos_token_id as u32), eos_token_id: Some(LlamaEosToks::Single(self.eos_token_id as u32)), use_flash_attn: false, rope_scaling: None, // Assume we don't have LLaVA for Llama 3.1 max_position_embeddings: self.max_position_embeddings, tie_word_embeddings: self.tie_word_embeddings.unwrap_or(false), } } } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct HFLLaVATextConfig { pub architectures: Vec<String>, #[serde(default = "default_hidden_size")] pub hidden_size: usize, #[serde(default = "default_intermediate_size")] pub intermediate_size: usize, #[serde(default = "default_max_length")] pub max_length: usize, pub max_position_embeddings: usize, pub model_type: String, #[serde(default = "default_num_attention_heads")] pub num_attention_heads: usize, #[serde(default = "default_num_hidden_layers")] pub num_hidden_layers: usize, #[serde(default = "default_num_key_value_heads")] pub num_key_value_heads: usize, pub pad_token_id: usize, pub rms_norm_eps: f32, #[serde(default = "default_rope_theta")] pub rope_theta: f32, pub torch_dtype: String, #[serde(default = "default_use_cache")] pub use_cache: bool, pub vocab_size: usize, } fn default_num_hidden_layers() -> usize { 32 } fn default_use_cache() -> bool { true } fn default_hidden_size() -> usize { 4096 } fn default_intermediate_size() -> usize { 11008 } fn default_max_length() -> usize { 4096 } fn default_num_attention_heads() -> usize { 32 } fn default_num_key_value_heads() -> usize { 32 } fn default_rope_theta() -> f32 { 10000.0 } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct HFLLaVAVisionConfig { pub hidden_size: usize, pub image_size: usize, pub intermediate_size: usize, pub model_type: String, pub num_attention_heads: usize, pub num_hidden_layers: usize, pub patch_size: usize, pub projection_dim: usize, pub vocab_size: usize, } // config from llava-v1.6-vicuna-7b-hf #[derive(Serialize, Deserialize, Debug, Clone)] pub struct HFLLaVAConfig { pub architectures: Vec<String>, pub ignore_index: isize, pub image_grid_pinpoints: Vec<(u32, u32)>, pub image_token_index: isize, pub model_type: String, pub projector_hidden_act: String, pub text_config: HFLLaVATextConfig, pub torch_dtype: String, pub use_image_newline_parameter: bool, pub vision_config: HFLLaVAVisionConfig, pub vision_feature_layer: isize, pub vision_feature_select_strategy: String, pub vocab_size: usize, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct HFGenerationConfig { pub bos_token_id: usize, pub eos_token_id: usize, #[serde(default = "default_max_length")] pub max_length: usize, pub pad_token_id: usize, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct HFPreProcessorConfig { pub aspect_ratio_setting: String, pub crop_size: HashMap<String, usize>, pub do_center_crop: bool, pub do_convert_rgb: bool, pub do_normalize: bool, pub do_rescale: bool, pub do_resize: bool, pub image_mean: Vec<f32>, pub image_std: Vec<f32>, pub resample: u32, pub rescale_factor: f32, pub size: HashMap<String, f32>, } impl HFLLaVAConfig { pub fn to_clip_vision_config(&self) -> ClipVisionConfig { ClipVisionConfig { embed_dim: self.vision_config.hidden_size, activation: Activation::QuickGelu, intermediate_size: self.vision_config.intermediate_size, num_hidden_layers: self.vision_config.num_hidden_layers, num_attention_heads: self.vision_config.num_attention_heads, projection_dim: self.vision_config.projection_dim, num_channels: 3, image_size: self.vision_config.image_size, patch_size: self.vision_config.patch_size, } } fn map_projector_type(s: &str) -> String { if s == "gelu" { "mlp2x_gelu".to_string() } else { s.to_string() } } fn map_select_feature(s: &str) -> String { if s == "default" { "patch".to_string() } else { "cls_patch".to_string() } } pub fn to_llava_config( &self, generation_config: &HFGenerationConfig, preprocessor_config: &HFPreProcessorConfig, ) -> LLaVAConfig { LLaVAConfig { hf: true, architectures: self.architectures.clone(), bos_token_id: generation_config.bos_token_id, eos_token_id: generation_config.eos_token_id, hidden_size: self.text_config.hidden_size, image_aspect_ratio: preprocessor_config.aspect_ratio_setting.clone(), image_crop_resolution: 224, image_grid_pinpoints: self.image_grid_pinpoints.clone(), image_split_resolution: 224, intermediate_size: self.text_config.intermediate_size, max_position_embeddings: self.text_config.max_position_embeddings, mm_hidden_size: 1024, mm_patch_merge_type: "spatial_unpad".to_string(), mm_projector_type: Self::map_projector_type(&self.projector_hidden_act), mm_use_im_start_end: false, mm_vision_select_feature: Self::map_select_feature( &self.vision_feature_select_strategy, ), mm_vision_select_layer: self.vision_feature_layer, mm_vision_tower: None, model_type: self.model_type.clone(), num_attention_heads: self.text_config.num_attention_heads, num_hidden_layers: self.text_config.num_hidden_layers, num_key_value_heads: self.text_config.num_key_value_heads, pad_token_id: self.text_config.pad_token_id, rms_norm_eps: self.text_config.rms_norm_eps, rope_theta: self.text_config.rope_theta, tokenizer_model_max_length: Some(4096), torch_dtype: self.torch_dtype.clone(), use_cache: self.text_config.use_cache, vocab_size: self.vocab_size, image_token_index: self.image_token_index, tie_word_embeddings: None, } } }
candle/candle-transformers/src/models/llava/config.rs/0
{ "file_path": "candle/candle-transformers/src/models/llava/config.rs", "repo_id": "candle", "token_count": 3948 }
57
use candle::{bail, DType, Module, Result, Tensor}; use candle_nn as nn; pub struct PatchEmbedder { proj: nn::Conv2d, } impl PatchEmbedder { pub fn new( patch_size: usize, in_channels: usize, embed_dim: usize, vb: nn::VarBuilder, ) -> Result<Self> { let proj = nn::conv2d( in_channels, embed_dim, patch_size, nn::Conv2dConfig { stride: patch_size, ..Default::default() }, vb.pp("proj"), )?; Ok(Self { proj }) } } impl Module for PatchEmbedder { fn forward(&self, x: &Tensor) -> Result<Tensor> { let x = self.proj.forward(x)?; // flatten spatial dim and transpose to channels last let (b, c, h, w) = x.dims4()?; x.reshape((b, c, h * w))?.transpose(1, 2) } } pub struct Unpatchifier { patch_size: usize, out_channels: usize, } impl Unpatchifier { pub fn new(patch_size: usize, out_channels: usize) -> Result<Self> { Ok(Self { patch_size, out_channels, }) } pub fn unpatchify(&self, x: &Tensor, h: usize, w: usize) -> Result<Tensor> { let h = (h + 1) / self.patch_size; let w = (w + 1) / self.patch_size; let x = x.reshape(( x.dim(0)?, h, w, self.patch_size, self.patch_size, self.out_channels, ))?; let x = x.permute((0, 5, 1, 3, 2, 4))?; // "nhwpqc->nchpwq" x.reshape(( x.dim(0)?, self.out_channels, self.patch_size * h, self.patch_size * w, )) } } pub struct PositionEmbedder { pos_embed: Tensor, patch_size: usize, pos_embed_max_size: usize, } impl PositionEmbedder { pub fn new( hidden_size: usize, patch_size: usize, pos_embed_max_size: usize, vb: nn::VarBuilder, ) -> Result<Self> { let pos_embed = vb.get( (1, pos_embed_max_size * pos_embed_max_size, hidden_size), "pos_embed", )?; Ok(Self { pos_embed, patch_size, pos_embed_max_size, }) } pub fn get_cropped_pos_embed(&self, h: usize, w: usize) -> Result<Tensor> { let h = (h + 1) / self.patch_size; let w = (w + 1) / self.patch_size; if h > self.pos_embed_max_size || w > self.pos_embed_max_size { bail!("Input size is too large for the position embedding") } let top = (self.pos_embed_max_size - h) / 2; let left = (self.pos_embed_max_size - w) / 2; let pos_embed = self.pos_embed .reshape((1, self.pos_embed_max_size, self.pos_embed_max_size, ()))?; let pos_embed = pos_embed.narrow(1, top, h)?.narrow(2, left, w)?; pos_embed.reshape((1, h * w, ())) } } pub struct TimestepEmbedder { mlp: nn::Sequential, frequency_embedding_size: usize, } impl TimestepEmbedder { pub fn new( hidden_size: usize, frequency_embedding_size: usize, vb: nn::VarBuilder, ) -> Result<Self> { let mlp = nn::seq() .add(nn::linear( frequency_embedding_size, hidden_size, vb.pp("mlp.0"), )?) .add(nn::Activation::Silu) .add(nn::linear(hidden_size, hidden_size, vb.pp("mlp.2"))?); Ok(Self { mlp, frequency_embedding_size, }) } fn timestep_embedding(t: &Tensor, dim: usize, max_period: f64) -> Result<Tensor> { if dim % 2 != 0 { bail!("Embedding dimension must be even") } if t.dtype() != DType::F32 && t.dtype() != DType::F64 { bail!("Input tensor must be floating point") } let half = dim / 2; let freqs = Tensor::arange(0f32, half as f32, t.device())? .to_dtype(candle::DType::F32)? .mul(&Tensor::full( (-f64::ln(max_period) / half as f64) as f32, half, t.device(), )?)? .exp()?; let args = t .unsqueeze(1)? .to_dtype(candle::DType::F32)? .matmul(&freqs.unsqueeze(0)?)?; let embedding = Tensor::cat(&[args.cos()?, args.sin()?], 1)?; embedding.to_dtype(candle::DType::F16) } } impl Module for TimestepEmbedder { fn forward(&self, t: &Tensor) -> Result<Tensor> { let t_freq = Self::timestep_embedding(t, self.frequency_embedding_size, 10000.0)?; self.mlp.forward(&t_freq) } } pub struct VectorEmbedder { mlp: nn::Sequential, } impl VectorEmbedder { pub fn new(input_dim: usize, hidden_size: usize, vb: nn::VarBuilder) -> Result<Self> { let mlp = nn::seq() .add(nn::linear(input_dim, hidden_size, vb.pp("mlp.0"))?) .add(nn::Activation::Silu) .add(nn::linear(hidden_size, hidden_size, vb.pp("mlp.2"))?); Ok(Self { mlp }) } } impl Module for VectorEmbedder { fn forward(&self, x: &Tensor) -> Result<Tensor> { self.mlp.forward(x) } }
candle/candle-transformers/src/models/mmdit/embedding.rs/0
{ "file_path": "candle/candle-transformers/src/models/mmdit/embedding.rs", "repo_id": "candle", "token_count": 2837 }
58
//! Open Contrastive Language-Image Pre-Training //! //! Open Contrastive Language-Image Pre-Training (OpenCLIP) is an architecture trained on //! pairs of images with related texts. //! //! - 💻 [GH Link](https://github.com/mlfoundations/open_clip) //! - 📝 [Paper](https://arxiv.org/abs/2212.07143) //! //! ## Overview //! //! ![](https://raw.githubusercontent.com/mlfoundations/open_clip/main/docs/CLIP.png) pub mod text_model;
candle/candle-transformers/src/models/openclip/mod.rs/0
{ "file_path": "candle/candle-transformers/src/models/openclip/mod.rs", "repo_id": "candle", "token_count": 154 }
59
//! Mistral model implementation with quantization support. //! //! Mistral is a large language model optimized for efficiency. //! This implementation provides quantization for reduced memory and compute. //! //! Key characteristics: //! - Sliding window attention mechanism //! - Grouped query attention (GQA) //! - RMSNorm for layer normalization //! - Rotary positional embeddings (RoPE) //! - Support for 8-bit quantization //! //! References: //! - [Mistral Paper](https://arxiv.org/abs/2310.06825) //! - [Model Card](https://huggingface.co/mistralai/Mistral-7B-v0.1) //! use crate::quantized_nn::{linear_no_bias, Embedding, Linear, RmsNorm}; pub use crate::quantized_var_builder::VarBuilder; use candle::{DType, Device, Module, Result, Tensor, D}; use candle_nn::Activation; use std::sync::Arc; pub use crate::models::mistral::Config; #[derive(Debug, Clone)] struct RotaryEmbedding { sin: Tensor, cos: Tensor, } impl RotaryEmbedding { fn new(cfg: &Config, dev: &Device) -> Result<Self> { let rope_theta = cfg.rope_theta as f32; let dim = cfg.hidden_size / cfg.num_attention_heads; let max_seq_len = cfg.max_position_embeddings; let inv_freq: Vec<_> = (0..dim) .step_by(2) .map(|i| 1f32 / 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)?; 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, &cos, &sin)?; let k_embed = candle_nn::rotary_emb::rope(k, &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: 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_no_bias(hidden_sz, intermediate_sz, vb.pp("gate_proj"))?; let up_proj = linear_no_bias(hidden_sz, intermediate_sz, vb.pp("up_proj"))?; let down_proj = linear_no_bias(intermediate_sz, hidden_sz, 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, hidden_size: usize, rotary_emb: Arc<RotaryEmbedding>, kv_cache: Option<(Tensor, Tensor)>, } impl Attention { fn new(rotary_emb: Arc<RotaryEmbedding>, 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 = hidden_sz / num_heads; let q_proj = linear_no_bias(hidden_sz, num_heads * head_dim, vb.pp("q_proj"))?; let k_proj = linear_no_bias(hidden_sz, num_kv_heads * head_dim, vb.pp("k_proj"))?; let v_proj = linear_no_bias(hidden_sz, num_kv_heads * head_dim, vb.pp("v_proj"))?; let o_proj = linear_no_bias(num_heads * head_dim, hidden_sz, vb.pp("o_proj"))?; Ok(Self { q_proj, k_proj, v_proj, o_proj, num_heads, num_kv_heads, num_kv_groups, head_dim, hidden_size: hidden_sz, rotary_emb, kv_cache: None, }) } 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)? .contiguous()?; let key_states = key_states .reshape((b_sz, q_len, self.num_kv_heads, self.head_dim))? .transpose(1, 2)? .contiguous()?; 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)?; let value_states = crate::utils::repeat_kv(value_states, self.num_kv_groups)?; let attn_output = { 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, self.hidden_size))? .apply(&self.o_proj) } fn clear_kv_cache(&mut self) { self.kv_cache = None } } #[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>, cfg: &Config, vb: VarBuilder) -> Result<Self> { let self_attn = Attention::new(rotary_emb, 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: Embedding, layers: Vec<DecoderLayer>, norm: RmsNorm, lm_head: Linear, sliding_window: Option<usize>, device: Device, } impl Model { pub fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let vb_m = vb.pp("model"); let embed_tokens = Embedding::new(cfg.vocab_size, cfg.hidden_size, vb_m.pp("embed_tokens"))?; let rotary_emb = Arc::new(RotaryEmbedding::new(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(), 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_no_bias(cfg.hidden_size, cfg.vocab_size, vb.pp("lm_head"))?; Ok(Self { embed_tokens, layers, norm, lm_head, sliding_window: cfg.sliding_window, device: vb.device().clone(), }) } fn prepare_decoder_attention_mask( &self, tgt_len: usize, seqlen_offset: usize, ) -> Result<Tensor> { let sliding_window = self.sliding_window.unwrap_or(tgt_len + 1); let mask: Vec<_> = (0..tgt_len) .flat_map(|i| { (0..tgt_len).map(move |j| { if i < j || j + sliding_window < i { 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((1, 1, tgt_len, tgt_len + seqlen_offset))? .to_dtype(DType::F32) } 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(seq_len, seqlen_offset)?; Some(mask) }; let mut xs = self.embed_tokens.forward(input_ids)?; for layer in self.layers.iter_mut() { xs = layer.forward(&xs, attention_mask.as_ref(), seqlen_offset)? } xs.narrow(1, seq_len - 1, 1)? .contiguous()? .apply(&self.norm)? .apply(&self.lm_head) } pub fn clear_kv_cache(&mut self) { for layer in self.layers.iter_mut() { layer.clear_kv_cache() } } }
candle/candle-transformers/src/models/quantized_mistral.rs/0
{ "file_path": "candle/candle-transformers/src/models/quantized_mistral.rs", "repo_id": "candle", "token_count": 5831 }
60
use crate::models::{ qwen3::{Config as Qwen3Config, Qwen3Attention, Qwen3MLP, Qwen3RotaryEmbedding}, with_tracing::{linear_no_bias, Linear, RmsNorm}, }; use candle::{DType, Device, Module, Result, Tensor, D}; use candle_nn::{Activation, VarBuilder}; use std::sync::Arc; #[derive(Debug, Clone, PartialEq, serde::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 head_dim: usize, pub attention_bias: bool, pub num_key_value_heads: usize, pub max_position_embeddings: usize, pub sliding_window: Option<usize>, pub max_window_layers: usize, pub tie_word_embeddings: bool, pub rope_theta: f64, pub rms_norm_eps: f64, pub use_sliding_window: bool, pub hidden_act: Activation, // MoE specific configuration pub decoder_sparse_step: usize, pub moe_intermediate_size: usize, pub num_experts_per_tok: usize, pub num_experts: usize, pub norm_topk_prob: bool, } impl From<&Config> for Qwen3Config { fn from(val: &Config) -> Self { Qwen3Config { vocab_size: val.vocab_size, hidden_size: val.hidden_size, intermediate_size: val.intermediate_size, num_hidden_layers: val.num_hidden_layers, num_attention_heads: val.num_attention_heads, head_dim: val.head_dim, attention_bias: val.attention_bias, num_key_value_heads: val.num_key_value_heads, max_position_embeddings: val.max_position_embeddings, sliding_window: val.sliding_window, max_window_layers: val.max_window_layers, tie_word_embeddings: val.tie_word_embeddings, rope_theta: val.rope_theta, rms_norm_eps: val.rms_norm_eps, use_sliding_window: val.use_sliding_window, hidden_act: val.hidden_act, } } } #[derive(Debug, Clone)] struct Qwen3MLPExpert { gate_proj: Linear, up_proj: Linear, down_proj: Linear, act_fn: Activation, } impl Qwen3MLPExpert { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { Ok(Self { gate_proj: linear_no_bias( cfg.hidden_size, cfg.moe_intermediate_size, vb.pp("gate_proj"), )?, up_proj: linear_no_bias(cfg.hidden_size, cfg.moe_intermediate_size, vb.pp("up_proj"))?, down_proj: linear_no_bias( cfg.moe_intermediate_size, cfg.hidden_size, vb.pp("down_proj"), )?, act_fn: cfg.hidden_act, }) } } impl Module for Qwen3MLPExpert { fn forward(&self, x: &Tensor) -> Result<Tensor> { let lhs = x.apply(&self.gate_proj)?.apply(&self.act_fn)?; let rhs = x.apply(&self.up_proj)?; (lhs * rhs)?.apply(&self.down_proj) } } // Qwen3 Sparse MoE Block implementation #[derive(Debug, Clone)] struct Qwen3SparseMoeBlock { gate: Linear, experts: Vec<Qwen3MLPExpert>, norm_topk_prob: bool, num_experts_per_tok: usize, } impl Qwen3SparseMoeBlock { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let gate = linear_no_bias(cfg.hidden_size, cfg.num_experts, vb.pp("gate"))?; let mut experts = Vec::with_capacity(cfg.num_experts); let vb_e = vb.pp("experts"); for idx in 0..cfg.num_experts { let expert = Qwen3MLPExpert::new(cfg, vb_e.pp(idx))?; experts.push(expert) } Ok(Self { gate, experts, norm_topk_prob: cfg.norm_topk_prob, num_experts_per_tok: cfg.num_experts_per_tok, }) } } impl Module for Qwen3SparseMoeBlock { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let (b_size, seq_len, hidden_dim) = xs.dims3()?; let xs = xs.reshape(((), hidden_dim))?; let router_logits = xs.apply(&self.gate)?; let routing_weights = candle_nn::ops::softmax_last_dim(&router_logits)?; // Extract topk experts per token let experts_per_tok = routing_weights .arg_sort_last_dim(false)? .narrow(D::Minus1, 0, self.num_experts_per_tok)? .contiguous()?; let routing_weights = routing_weights.gather(&experts_per_tok, D::Minus1)?; // Extract needed data let routing_weights = routing_weights.to_dtype(DType::F32)?.to_vec2::<f32>()?; let experts_per_tok = experts_per_tok.to_vec2::<u32>()?; let mut top_x = vec![vec![]; self.experts.len()]; let mut selected_experts = vec![vec![]; self.experts.len()]; for (row_idx, (rw, expert_idxs)) in routing_weights .iter() .zip(experts_per_tok.iter()) .enumerate() { let sum_rw = rw.iter().sum::<f32>(); for (&rw, &expert_idx) in rw.iter().zip(expert_idxs.iter()) { top_x[expert_idx as usize].push(row_idx as u32); let rw = if self.norm_topk_prob { rw / sum_rw } else { rw }; selected_experts[expert_idx as usize].push(rw) } } // Process through experts let mut ys = xs.zeros_like()?; for (expert_idx, expert_layer) in self.experts.iter().enumerate() { let top_x = &top_x[expert_idx]; if top_x.is_empty() { continue; } let top_x = Tensor::new(top_x.as_slice(), xs.device())?; let selected_experts = Tensor::new(selected_experts[expert_idx].as_slice(), xs.device())? .reshape(((), 1))? .to_dtype(xs.dtype())?; let current_state = xs.index_select(&top_x, 0)?.reshape(((), hidden_dim))?; let current_hidden_states = expert_layer.forward(&current_state)?; let current_hidden_states = current_hidden_states.broadcast_mul(&selected_experts)?; ys = ys.index_add(&top_x, &current_hidden_states, 0)?; } ys.reshape((b_size, seq_len, hidden_dim)) } } // MLP or MoE decision enum #[derive(Debug, Clone)] enum Qwen3FeedForward { Mlp(Qwen3MLP), MoE(Qwen3SparseMoeBlock), } impl Module for Qwen3FeedForward { fn forward(&self, xs: &Tensor) -> Result<Tensor> { match self { Self::Mlp(m) => m.forward(xs), Self::MoE(m) => m.forward(xs), } } } #[derive(Debug, Clone)] struct DecoderLayer { self_attn: Qwen3Attention, feed_forward: Qwen3FeedForward, ln1: RmsNorm, ln2: RmsNorm, } impl DecoderLayer { fn new( layer_idx: usize, cfg: &Config, rotary: Arc<Qwen3RotaryEmbedding>, vb: VarBuilder, ) -> Result<Self> { let self_attn = Qwen3Attention::new(&cfg.into(), rotary, vb.pp("self_attn"))?; // Decide whether to use MoE or regular MLP based on layer_idx and decoder_sparse_step let feed_forward = if cfg.num_experts > 0 && (layer_idx + 1) % cfg.decoder_sparse_step == 0 { Qwen3FeedForward::MoE(Qwen3SparseMoeBlock::new(cfg, vb.pp("mlp"))?) } else { Qwen3FeedForward::Mlp(Qwen3MLP::new(&cfg.into(), vb.pp("mlp"))?) }; let ln1 = RmsNorm::new(cfg.hidden_size, cfg.rms_norm_eps, vb.pp("input_layernorm"))?; let ln2 = RmsNorm::new( cfg.hidden_size, cfg.rms_norm_eps, vb.pp("post_attention_layernorm"), )?; Ok(Self { self_attn, feed_forward, ln1, ln2, }) } fn forward(&mut self, x: &Tensor, mask: Option<&Tensor>, offset: usize) -> Result<Tensor> { let h = self.ln1.forward(x)?; let h = self.self_attn.forward(&h, mask, offset)?; let x = (x + h)?; let h2 = self.ln2.forward(&x)?; let h2 = h2.apply(&self.feed_forward)?; x + h2 } 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, device: Device, dtype: DType, } impl Model { pub fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let embed_tokens = candle_nn::embedding(cfg.vocab_size, cfg.hidden_size, vb.pp("model.embed_tokens"))?; let rotary = Arc::new(Qwen3RotaryEmbedding::new( vb.dtype(), &cfg.into(), vb.device(), )?); let mut layers = Vec::with_capacity(cfg.num_hidden_layers); let vb_l = vb.pp("model.layers"); for i in 0..cfg.num_hidden_layers { layers.push(DecoderLayer::new(i, cfg, rotary.clone(), vb_l.pp(i))?); } Ok(Self { embed_tokens, layers, norm: RmsNorm::new(cfg.hidden_size, cfg.rms_norm_eps, vb.pp("model.norm"))?, device: vb.device().clone(), dtype: vb.dtype(), }) } fn clear_kv_cache(&mut self) { for l in &mut self.layers { l.clear_kv_cache(); } } fn causal_mask( &self, b: usize, tgt: usize, offset: usize, sw: Option<usize>, ) -> Result<Tensor> { let minf = f32::NEG_INFINITY; let mask: Vec<_> = (0..tgt) .flat_map(|i| { (0..(tgt + offset)).map(move |j| { let past_ok = j <= i + offset; let sw_ok = match sw { Some(w) => (i + offset) as i64 - j as i64 <= w as i64, None => true, }; if past_ok && sw_ok { 0. } else { minf } }) }) .collect(); Tensor::from_slice(&mask, (b, 1, tgt, tgt + offset), &self.device)?.to_dtype(self.dtype) } pub fn forward(&mut self, input: &Tensor, offset: usize) -> Result<Tensor> { let (b, l) = input.dims2()?; let mut h = self.embed_tokens.forward(input)?; let causal = if l == 1 { None } else { Some(self.causal_mask(b, l, offset, None)?) }; for layer in &mut self.layers { h = layer.forward(&h, causal.as_ref(), offset)?; } self.norm.forward(&h) } } #[derive(Debug, Clone)] pub struct ModelForCausalLM { base: Model, lm_head: Linear, } impl ModelForCausalLM { pub fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let base = Model::new(cfg, vb.clone())?; let lm_head = if cfg.tie_word_embeddings { Linear::from_weights(base.embed_tokens.embeddings().clone(), None) } else { linear_no_bias(cfg.hidden_size, cfg.vocab_size, vb.pp("lm_head"))? }; Ok(Self { base, lm_head }) } pub fn forward(&mut self, input: &Tensor, offset: usize) -> Result<Tensor> { let (_, l) = input.dims2()?; self.base .forward(input, offset)? .narrow(1, l - 1, 1)? .apply(&self.lm_head) } pub fn clear_kv_cache(&mut self) { self.base.clear_kv_cache(); } }
candle/candle-transformers/src/models/qwen3_moe.rs/0
{ "file_path": "candle/candle-transformers/src/models/qwen3_moe.rs", "repo_id": "candle", "token_count": 5966 }
61
//! Attention Based Building Blocks use candle::{DType, IndexOp, Result, Tensor, D}; use candle_nn as nn; use candle_nn::Module; #[derive(Debug)] struct GeGlu { proj: nn::Linear, span: tracing::Span, } impl GeGlu { fn new(vs: nn::VarBuilder, dim_in: usize, dim_out: usize) -> Result<Self> { let proj = nn::linear(dim_in, dim_out * 2, vs.pp("proj"))?; let span = tracing::span!(tracing::Level::TRACE, "geglu"); Ok(Self { proj, span }) } } impl Module for GeGlu { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let hidden_states_and_gate = self.proj.forward(xs)?.chunk(2, D::Minus1)?; &hidden_states_and_gate[0] * hidden_states_and_gate[1].gelu()? } } /// A feed-forward layer. #[derive(Debug)] struct FeedForward { project_in: GeGlu, linear: nn::Linear, span: tracing::Span, } impl FeedForward { // The glu parameter in the python code is unused? // https://github.com/huggingface/diffusers/blob/d3d22ce5a894becb951eec03e663951b28d45135/src/diffusers/models/attention.py#L347 /// Creates a new feed-forward layer based on some given input dimension, some /// output dimension, and a multiplier to be used for the intermediary layer. fn new(vs: nn::VarBuilder, dim: usize, dim_out: Option<usize>, mult: usize) -> Result<Self> { let inner_dim = dim * mult; let dim_out = dim_out.unwrap_or(dim); let vs = vs.pp("net"); let project_in = GeGlu::new(vs.pp("0"), dim, inner_dim)?; let linear = nn::linear(inner_dim, dim_out, vs.pp("2"))?; let span = tracing::span!(tracing::Level::TRACE, "ff"); Ok(Self { project_in, linear, span, }) } } impl Module for FeedForward { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let xs = self.project_in.forward(xs)?; self.linear.forward(&xs) } } #[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)] pub struct CrossAttention { to_q: nn::Linear, to_k: nn::Linear, to_v: nn::Linear, to_out: nn::Linear, heads: usize, scale: f64, slice_size: Option<usize>, span: tracing::Span, span_attn: tracing::Span, span_softmax: tracing::Span, use_flash_attn: bool, } impl CrossAttention { // Defaults should be heads = 8, dim_head = 64, context_dim = None pub fn new( vs: nn::VarBuilder, query_dim: usize, context_dim: Option<usize>, heads: usize, dim_head: usize, slice_size: Option<usize>, use_flash_attn: bool, ) -> Result<Self> { let inner_dim = dim_head * heads; let context_dim = context_dim.unwrap_or(query_dim); let scale = 1.0 / f64::sqrt(dim_head as f64); let to_q = nn::linear_no_bias(query_dim, inner_dim, vs.pp("to_q"))?; let to_k = nn::linear_no_bias(context_dim, inner_dim, vs.pp("to_k"))?; let to_v = nn::linear_no_bias(context_dim, inner_dim, vs.pp("to_v"))?; let to_out = nn::linear(inner_dim, query_dim, vs.pp("to_out.0"))?; let span = tracing::span!(tracing::Level::TRACE, "xa"); let span_attn = tracing::span!(tracing::Level::TRACE, "xa-attn"); let span_softmax = tracing::span!(tracing::Level::TRACE, "xa-softmax"); Ok(Self { to_q, to_k, to_v, to_out, heads, scale, slice_size, span, span_attn, span_softmax, use_flash_attn, }) } fn reshape_heads_to_batch_dim(&self, xs: &Tensor) -> Result<Tensor> { let (batch_size, seq_len, dim) = xs.dims3()?; xs.reshape((batch_size, seq_len, self.heads, dim / self.heads))? .transpose(1, 2)? .reshape((batch_size * self.heads, seq_len, dim / self.heads)) } fn reshape_batch_dim_to_heads(&self, xs: &Tensor) -> Result<Tensor> { let (batch_size, seq_len, dim) = xs.dims3()?; xs.reshape((batch_size / self.heads, self.heads, seq_len, dim))? .transpose(1, 2)? .reshape((batch_size / self.heads, seq_len, dim * self.heads)) } fn sliced_attention( &self, query: &Tensor, key: &Tensor, value: &Tensor, slice_size: usize, ) -> Result<Tensor> { let batch_size_attention = query.dim(0)?; let mut hidden_states = Vec::with_capacity(batch_size_attention / slice_size); let in_dtype = query.dtype(); let query = query.to_dtype(DType::F32)?; let key = key.to_dtype(DType::F32)?; let value = value.to_dtype(DType::F32)?; for i in 0..batch_size_attention / slice_size { let start_idx = i * slice_size; let end_idx = (i + 1) * slice_size; let xs = query .i(start_idx..end_idx)? .matmul(&(key.i(start_idx..end_idx)?.t()? * self.scale)?)?; let xs = nn::ops::softmax(&xs, D::Minus1)?.matmul(&value.i(start_idx..end_idx)?)?; hidden_states.push(xs) } let hidden_states = Tensor::stack(&hidden_states, 0)?.to_dtype(in_dtype)?; self.reshape_batch_dim_to_heads(&hidden_states) } fn attention(&self, query: &Tensor, key: &Tensor, value: &Tensor) -> Result<Tensor> { let _enter = self.span_attn.enter(); let xs = if self.use_flash_attn { let init_dtype = query.dtype(); let q = query .to_dtype(candle::DType::F16)? .unsqueeze(0)? .transpose(1, 2)?; let k = key .to_dtype(candle::DType::F16)? .unsqueeze(0)? .transpose(1, 2)?; let v = value .to_dtype(candle::DType::F16)? .unsqueeze(0)? .transpose(1, 2)?; flash_attn(&q, &k, &v, self.scale as f32, false)? .transpose(1, 2)? .squeeze(0)? .to_dtype(init_dtype)? } else { let in_dtype = query.dtype(); let query = query.to_dtype(DType::F32)?; let key = key.to_dtype(DType::F32)?; let value = value.to_dtype(DType::F32)?; let xs = query.matmul(&(key.t()? * self.scale)?)?; let xs = { let _enter = self.span_softmax.enter(); nn::ops::softmax_last_dim(&xs)? }; xs.matmul(&value)?.to_dtype(in_dtype)? }; self.reshape_batch_dim_to_heads(&xs) } pub fn forward(&self, xs: &Tensor, context: Option<&Tensor>) -> Result<Tensor> { let _enter = self.span.enter(); let query = self.to_q.forward(xs)?; let context = context.unwrap_or(xs).contiguous()?; let key = self.to_k.forward(&context)?; let value = self.to_v.forward(&context)?; let query = self.reshape_heads_to_batch_dim(&query)?; let key = self.reshape_heads_to_batch_dim(&key)?; let value = self.reshape_heads_to_batch_dim(&value)?; let dim0 = query.dim(0)?; let slice_size = self.slice_size.and_then(|slice_size| { if dim0 < slice_size { None } else { Some(slice_size) } }); let xs = match slice_size { None => self.attention(&query, &key, &value)?, Some(slice_size) => self.sliced_attention(&query, &key, &value, slice_size)?, }; self.to_out.forward(&xs) } } /// A basic Transformer block. #[derive(Debug)] struct BasicTransformerBlock { attn1: CrossAttention, ff: FeedForward, attn2: CrossAttention, norm1: nn::LayerNorm, norm2: nn::LayerNorm, norm3: nn::LayerNorm, span: tracing::Span, } impl BasicTransformerBlock { fn new( vs: nn::VarBuilder, dim: usize, n_heads: usize, d_head: usize, context_dim: Option<usize>, sliced_attention_size: Option<usize>, use_flash_attn: bool, ) -> Result<Self> { let attn1 = CrossAttention::new( vs.pp("attn1"), dim, None, n_heads, d_head, sliced_attention_size, use_flash_attn, )?; let ff = FeedForward::new(vs.pp("ff"), dim, None, 4)?; let attn2 = CrossAttention::new( vs.pp("attn2"), dim, context_dim, n_heads, d_head, sliced_attention_size, use_flash_attn, )?; let norm1 = nn::layer_norm(dim, 1e-5, vs.pp("norm1"))?; let norm2 = nn::layer_norm(dim, 1e-5, vs.pp("norm2"))?; let norm3 = nn::layer_norm(dim, 1e-5, vs.pp("norm3"))?; let span = tracing::span!(tracing::Level::TRACE, "basic-transformer"); Ok(Self { attn1, ff, attn2, norm1, norm2, norm3, span, }) } fn forward(&self, xs: &Tensor, context: Option<&Tensor>) -> Result<Tensor> { let _enter = self.span.enter(); let xs = (self.attn1.forward(&self.norm1.forward(xs)?, None)? + xs)?; let xs = (self.attn2.forward(&self.norm2.forward(&xs)?, context)? + xs)?; self.ff.forward(&self.norm3.forward(&xs)?)? + xs } } #[derive(Debug, Clone, Copy)] pub struct SpatialTransformerConfig { pub depth: usize, pub num_groups: usize, pub context_dim: Option<usize>, pub sliced_attention_size: Option<usize>, pub use_linear_projection: bool, } impl Default for SpatialTransformerConfig { fn default() -> Self { Self { depth: 1, num_groups: 32, context_dim: None, sliced_attention_size: None, use_linear_projection: false, } } } #[derive(Debug)] enum Proj { Conv2d(nn::Conv2d), Linear(nn::Linear), } // Aka Transformer2DModel #[derive(Debug)] pub struct SpatialTransformer { norm: nn::GroupNorm, proj_in: Proj, transformer_blocks: Vec<BasicTransformerBlock>, proj_out: Proj, span: tracing::Span, pub config: SpatialTransformerConfig, } impl SpatialTransformer { pub fn new( vs: nn::VarBuilder, in_channels: usize, n_heads: usize, d_head: usize, use_flash_attn: bool, config: SpatialTransformerConfig, ) -> Result<Self> { let inner_dim = n_heads * d_head; let norm = nn::group_norm(config.num_groups, in_channels, 1e-6, vs.pp("norm"))?; let proj_in = if config.use_linear_projection { Proj::Linear(nn::linear(in_channels, inner_dim, vs.pp("proj_in"))?) } else { Proj::Conv2d(nn::conv2d( in_channels, inner_dim, 1, Default::default(), vs.pp("proj_in"), )?) }; let mut transformer_blocks = vec![]; let vs_tb = vs.pp("transformer_blocks"); for index in 0..config.depth { let tb = BasicTransformerBlock::new( vs_tb.pp(index.to_string()), inner_dim, n_heads, d_head, config.context_dim, config.sliced_attention_size, use_flash_attn, )?; transformer_blocks.push(tb) } let proj_out = if config.use_linear_projection { Proj::Linear(nn::linear(in_channels, inner_dim, vs.pp("proj_out"))?) } else { Proj::Conv2d(nn::conv2d( inner_dim, in_channels, 1, Default::default(), vs.pp("proj_out"), )?) }; let span = tracing::span!(tracing::Level::TRACE, "spatial-transformer"); Ok(Self { norm, proj_in, transformer_blocks, proj_out, span, config, }) } pub fn forward(&self, xs: &Tensor, context: Option<&Tensor>) -> Result<Tensor> { let _enter = self.span.enter(); let (batch, _channel, height, weight) = xs.dims4()?; let residual = xs; let xs = self.norm.forward(xs)?; let (inner_dim, xs) = match &self.proj_in { Proj::Conv2d(p) => { let xs = p.forward(&xs)?; let inner_dim = xs.dim(1)?; let xs = xs .transpose(1, 2)? .t()? .reshape((batch, height * weight, inner_dim))?; (inner_dim, xs) } Proj::Linear(p) => { let inner_dim = xs.dim(1)?; let xs = xs .transpose(1, 2)? .t()? .reshape((batch, height * weight, inner_dim))?; (inner_dim, p.forward(&xs)?) } }; let mut xs = xs; for block in self.transformer_blocks.iter() { xs = block.forward(&xs, context)? } let xs = match &self.proj_out { Proj::Conv2d(p) => p.forward( &xs.reshape((batch, height, weight, inner_dim))? .t()? .transpose(1, 2)?, )?, Proj::Linear(p) => p .forward(&xs)? .reshape((batch, height, weight, inner_dim))? .t()? .transpose(1, 2)?, }; xs + residual } } /// Configuration for an attention block. #[derive(Debug, Clone, Copy)] pub struct AttentionBlockConfig { pub num_head_channels: Option<usize>, pub num_groups: usize, pub rescale_output_factor: f64, pub eps: f64, } impl Default for AttentionBlockConfig { fn default() -> Self { Self { num_head_channels: None, num_groups: 32, rescale_output_factor: 1., eps: 1e-5, } } } #[derive(Debug)] pub struct AttentionBlock { group_norm: nn::GroupNorm, query: nn::Linear, key: nn::Linear, value: nn::Linear, proj_attn: nn::Linear, channels: usize, num_heads: usize, span: tracing::Span, config: AttentionBlockConfig, } // In the .safetensor weights of official Stable Diffusion 3 Medium Huggingface repo // https://huggingface.co/stabilityai/stable-diffusion-3-medium // Linear layer may use a different dimension for the weight in the linear, which is // incompatible with the current implementation of the nn::linear constructor. // This is a workaround to handle the different dimensions. fn get_qkv_linear(channels: usize, vs: nn::VarBuilder) -> Result<nn::Linear> { match vs.get((channels, channels), "weight") { Ok(_) => nn::linear(channels, channels, vs), Err(_) => { let weight = vs .get((channels, channels, 1, 1), "weight")? .reshape((channels, channels))?; let bias = vs.get((channels,), "bias")?; Ok(nn::Linear::new(weight, Some(bias))) } } } impl AttentionBlock { pub fn new(vs: nn::VarBuilder, channels: usize, config: AttentionBlockConfig) -> Result<Self> { let num_head_channels = config.num_head_channels.unwrap_or(channels); let num_heads = channels / num_head_channels; let group_norm = nn::group_norm(config.num_groups, channels, config.eps, vs.pp("group_norm"))?; let (q_path, k_path, v_path, out_path) = if vs.contains_tensor("to_q.weight") { ("to_q", "to_k", "to_v", "to_out.0") } else { ("query", "key", "value", "proj_attn") }; let query = get_qkv_linear(channels, vs.pp(q_path))?; let key = get_qkv_linear(channels, vs.pp(k_path))?; let value = get_qkv_linear(channels, vs.pp(v_path))?; let proj_attn = get_qkv_linear(channels, vs.pp(out_path))?; let span = tracing::span!(tracing::Level::TRACE, "attn-block"); Ok(Self { group_norm, query, key, value, proj_attn, channels, num_heads, span, config, }) } fn transpose_for_scores(&self, xs: Tensor) -> Result<Tensor> { let (batch, t, h_times_d) = xs.dims3()?; xs.reshape((batch, t, self.num_heads, h_times_d / self.num_heads))? .transpose(1, 2) } } impl Module for AttentionBlock { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let in_dtype = xs.dtype(); let residual = xs; let (batch, channel, height, width) = xs.dims4()?; let xs = self .group_norm .forward(xs)? .reshape((batch, channel, height * width))? .transpose(1, 2)?; let query_proj = self.query.forward(&xs)?; let key_proj = self.key.forward(&xs)?; let value_proj = self.value.forward(&xs)?; let query_states = self .transpose_for_scores(query_proj)? .to_dtype(DType::F32)?; let key_states = self.transpose_for_scores(key_proj)?.to_dtype(DType::F32)?; let value_states = self .transpose_for_scores(value_proj)? .to_dtype(DType::F32)?; // scale is applied twice, hence the -0.25 here rather than -0.5. // https://github.com/huggingface/diffusers/blob/d3d22ce5a894becb951eec03e663951b28d45135/src/diffusers/models/attention.py#L87 let scale = f64::powf(self.channels as f64 / self.num_heads as f64, -0.25); let attention_scores = (query_states * scale)?.matmul(&(key_states.t()? * scale)?)?; let attention_probs = nn::ops::softmax(&attention_scores, D::Minus1)?; // TODO: revert the call to force_contiguous once the three matmul kernels have been // adapted to handle layout with some dims set to 1. let xs = attention_probs.matmul(&value_states)?; let xs = xs.to_dtype(in_dtype)?; let xs = xs.transpose(1, 2)?.contiguous()?; let xs = xs.flatten_from(D::Minus2)?; let xs = self .proj_attn .forward(&xs)? .t()? .reshape((batch, channel, height, width))?; (xs + residual)? / self.config.rescale_output_factor } }
candle/candle-transformers/src/models/stable_diffusion/attention.rs/0
{ "file_path": "candle/candle-transformers/src/models/stable_diffusion/attention.rs", "repo_id": "candle", "token_count": 9788 }
62
//! Stella v5 model implementation. //! //! Stella is a dense text embedding model optimized for retrieval and similarity tasks. //! This implementation provides support for multiple embedding dimensions. //! //! Key characteristics: //! - Dense text embeddings optimized for similarity search //! - Multiple output dimension support (256 to 8192) //! - Grouped query attention (GQA) //! - RMSNorm for layer normalization //! - Rotary positional embeddings (RoPE) //! //! References: //! - [MRL Framework](https://arxiv.org/abs/2205.13147) //! - [Model Card](https://huggingface.co/dunzhang/stella_en_1.5B_v5) //! use crate::models::with_tracing::{linear, linear_no_bias, Linear, RmsNorm}; use candle::{DType, Device, Error, IndexOp, Module, Result, Tensor, D}; use candle_nn::{layer_norm, Activation, LayerNorm, VarBuilder}; use std::sync::Arc; // internal representation for identifying which model is being used #[derive(Debug, Copy, Clone, PartialEq, serde::Deserialize)] pub enum ModelVariant { Large, // 1.5B Small, // 400M } impl Default for ModelVariant { fn default() -> Self { Self::Large } } // Same as `qwen2` family of models with the exception being the `embed_head` // The final `output` causal modelling head is swapped with a learned `dense` layer, `embed_head` #[derive(Debug, Default, Clone, PartialEq, serde::Deserialize)] pub struct Config { pub variant: ModelVariant, pub vocab_size: usize, pub hidden_size: usize, pub intermediate_size: usize, pub num_hidden_layers: usize, pub num_attention_heads: usize, pub max_position_embeddings: usize, pub rope_theta: f64, pub embed_head: EmbedHead, pub norm_eps: f64, // RMSNorm for 1.5B || LayerNorm for 400M pub activation_fn: Activation, // Silu for 1.5B || Gelu for 400M // Unique to 1.5B pub num_key_value_heads: usize, // Unique to 400M pub type_vocab_size: usize, pub scaling_factor: f64, } // Excerpt from `stella` model card: // `Stella_en_1.5B_v5` models have been trained on [MRL](https://arxiv.org/abs/2205.13147) enabling multiple output dimensions // Embed head represents the config for various embedding dims supported #[derive(Debug, Default, Clone, PartialEq, serde::Deserialize)] pub struct EmbedHead { pub in_features: usize, pub out_features: usize, } /// An enum variant representing the Embedding head dimensions `stella` is trained on /// As the [model-card](https://huggingface.co/dunzhang/stella_en_1.5B_v5#introduction) suggests, D1024 is good enough for most cases #[derive(Debug, Clone, Copy)] pub enum EmbedDim { Dim256, Dim768, Dim1024, Dim2048, Dim4096, Dim6144, Dim8192, } impl Default for EmbedDim { fn default() -> Self { Self::Dim1024 } } impl EmbedDim { pub fn config(&self, in_features: usize) -> EmbedHead { EmbedHead { in_features, out_features: match &self { Self::Dim256 => 256, Self::Dim768 => 768, Self::Dim1024 => 1024, Self::Dim2048 => 2048, Self::Dim4096 => 4096, Self::Dim6144 => 6144, Self::Dim8192 => 8192, }, } } } // Initialize a new `stella_en` model - with 400M variant or 1.5B variant impl Config { /// Initialize a new `stella_en_1.5B_v5`` model with given embedding dim pub fn new_1_5_b_v5(embed_dim: EmbedDim) -> Self { // Representing config.json at https://huggingface.co/dunzhang/stella_en_1.5B_v5/blob/main/config.json // Removed `sliding_window` related config which is basically being carried forward from `qwen2` but not used here Self { variant: ModelVariant::Large, activation_fn: candle_nn::Activation::Silu, vocab_size: 151646, hidden_size: 1536, intermediate_size: 8960, num_hidden_layers: 28, num_attention_heads: 12, num_key_value_heads: 2, max_position_embeddings: 131072, rope_theta: 1000000., norm_eps: 1e-06, embed_head: embed_dim.config(1536), ..Default::default() } } /// Initialize new `stella_en_400M_v5` pub fn new_400_m_v5(embed_dim: EmbedDim) -> Self { Self { variant: ModelVariant::Small, vocab_size: 30528, hidden_size: 1024, intermediate_size: 4096, num_hidden_layers: 24, num_attention_heads: 16, max_position_embeddings: 8192, type_vocab_size: 2, norm_eps: 1e-12, scaling_factor: 2.0, rope_theta: 160000.0, activation_fn: Activation::Gelu, embed_head: embed_dim.config(1024), ..Default::default() } } } #[derive(Debug, Clone)] struct RotaryEmbedding { sin: Tensor, cos: Tensor, } impl RotaryEmbedding { fn new(dtype: DType, cfg: &Config, dev: &Device) -> Result<Self> { let dim = cfg.hidden_size / cfg.num_attention_heads; // Factoring in `scaling factor` for `400M` variant let max_seq_len = if cfg.scaling_factor == 0. { cfg.max_position_embeddings } else { ((cfg.max_position_embeddings as f64) * cfg.scaling_factor) as usize }; // let rot_dim = if cfg.variant == ModelVariant::Small { dim / 2 } else { dim }; let inv_freq: Vec<_> = (0..dim) .step_by(2) .map(|i| { // Scaled rope_theta for 400M variant let rope_theta = if cfg.scaling_factor == 0. { cfg.rope_theta } else { cfg.rope_theta * cfg.scaling_factor }; let mut freq = 1. / rope_theta.powf(i as f64 / dim as f64); if cfg.scaling_factor != 0. { freq /= cfg.scaling_factor.powf(2.0 / (dim as f64)) } freq 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)?; // Calculate position embeddings with scaled sequence length 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)?; // if cfg.variant == ModelVariant::Small { // freqs = Tensor::cat(&[&freqs, &freqs], 1)? // } Ok(Self { sin: freqs.sin()?, cos: freqs.cos()?, }) } // TODO: re-visit this fn apply_rotary_emb_qkv(&self, q: &Tensor, k: &Tensor) -> Result<(Tensor, Tensor)> { let (_b_sz, _h, seq_len, _n_embd) = q.dims4()?; let cos = self.cos.narrow(0, 0, seq_len)?; let sin = self.sin.narrow(0, 0, 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 { variant: ModelVariant, gate_proj: Linear, up_proj: Option<Linear>, // `up_proj` only for 1.5B variant down_proj: Linear, act_fn: 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, up_proj, down_proj) = match cfg.variant { ModelVariant::Large => ( linear_no_bias(hidden_sz, intermediate_sz, vb.pp("gate_proj"))?, Some(linear_no_bias( hidden_sz, intermediate_sz, vb.pp("up_proj"), )?), linear_no_bias(intermediate_sz, hidden_sz, vb.pp("down_proj"))?, ), ModelVariant::Small => ( linear_no_bias(hidden_sz, intermediate_sz * 2, vb.pp("up_gate_proj"))?, None, linear(intermediate_sz, hidden_sz, vb.pp("down_proj"))?, ), }; Ok(Self { variant: cfg.variant, gate_proj, up_proj, down_proj, act_fn: cfg.activation_fn, }) } } impl Module for MLP { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let up = self.gate_proj.forward(xs)?; let (lhs, rhs) = match self.variant { ModelVariant::Large => { let lhs = up.apply(&self.act_fn)?; let rhs = xs.apply(self.up_proj.as_ref().unwrap())?; (lhs, rhs) } ModelVariant::Small => { // Get the dimensions let (_batch_size, _seq_len, hidden_dim) = up.dims3()?; let split_size = hidden_dim / 2; // Split along the last dimension (hidden_dim) let up_states = up.narrow(2, 0, split_size)?; let gate = up.narrow(2, split_size, split_size)?.apply(&self.act_fn)?; (up_states, gate) } }; (lhs * rhs)?.apply(&self.down_proj) } } #[derive(Debug, Clone)] struct Attention { qkv_proj: Linear, o_proj: Linear, num_heads: usize, num_kv_heads: usize, num_kv_groups: usize, head_dim: usize, hidden_size: usize, rotary_emb: Arc<RotaryEmbedding>, variant: ModelVariant, } impl Attention { fn new(rotary_emb: Arc<RotaryEmbedding>, 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 = if num_kv_heads > 0 { num_heads / num_kv_heads } else { 0 }; let head_dim = hidden_sz / num_heads; let (qkv_proj, o_proj) = match cfg.variant { ModelVariant::Large => { // The 1.5B variant comes with separate `q, k, v` layers, let's merge it and standardize // Weights let q_w = vb .pp("q_proj") .get((num_heads * head_dim, hidden_sz), "weight")?; let k_w = vb .pp("k_proj") .get((num_kv_heads * head_dim, hidden_sz), "weight")?; let v_w = vb .pp("v_proj") .get((num_kv_heads * head_dim, hidden_sz), "weight")?; // Biases let q_b = vb.pp("q_proj").get(num_heads * head_dim, "bias")?; let k_b = vb.pp("k_proj").get(num_kv_heads * head_dim, "bias")?; let v_b = vb.pp("v_proj").get(num_kv_heads * head_dim, "bias")?; let qkv_w = Tensor::cat(&[&q_w, &k_w, &v_w], 0)?; let qkv_b = Tensor::cat(&[&q_b, &k_b, &v_b], 0)?; ( Linear::from_weights(qkv_w, Some(qkv_b)), linear_no_bias(num_heads * head_dim, hidden_sz, vb.pp("o_proj"))?, ) } ModelVariant::Small => ( linear(hidden_sz, 3 * num_heads * head_dim, vb.pp("qkv_proj"))?, linear(num_heads * head_dim, hidden_sz, vb.pp("o_proj"))?, ), }; Ok(Self { qkv_proj, o_proj, num_heads, num_kv_heads, num_kv_groups, head_dim, hidden_size: hidden_sz, rotary_emb, variant: cfg.variant, }) } fn forward(&mut self, xs: &Tensor, attention_mask: Option<&Tensor>) -> Result<Tensor> { let (b_sz, q_len, _) = xs.dims3()?; let qkv = self.qkv_proj.forward(xs)?; let n_kv_heads = match self.variant { ModelVariant::Large => self.num_kv_heads, ModelVariant::Small => self.num_heads, }; let (query_states, key_states, value_states) = match self.variant { ModelVariant::Large => { let q_sz = self.num_heads * self.head_dim; let kv_sz = n_kv_heads * self.head_dim; let q = qkv.narrow(D::Minus1, 0, q_sz)?.reshape(( b_sz, q_len, self.num_heads, self.head_dim, ))?; let k = qkv.narrow(D::Minus1, q_sz, kv_sz)?.reshape(( b_sz, q_len, n_kv_heads, self.head_dim, ))?; let v = qkv.narrow(D::Minus1, q_sz + kv_sz, kv_sz)?.reshape(( b_sz, q_len, n_kv_heads, self.head_dim, ))?; (q, k, v) } ModelVariant::Small => { // Split into Q, K, V and reshape to match PyTorch shapes let qkv = qkv.reshape((b_sz, q_len, 3, self.num_heads, self.head_dim))?; ( qkv.i((.., .., 0, .., ..))?, qkv.i((.., .., 1, .., ..))?, qkv.i((.., .., 2, .., ..))?, ) } }; let query_states = query_states.transpose(1, 2)?.contiguous()?; let key_states = key_states.transpose(1, 2)?.contiguous()?; let value_states = value_states.transpose(1, 2)?.contiguous()?; let (query_states, key_states) = self .rotary_emb .apply_rotary_emb_qkv(&query_states, &key_states)?; // The 1.5B is expected to have grouped query attention let (key_states, value_states) = if self.variant == ModelVariant::Large { ( crate::utils::repeat_kv(key_states, self.num_kv_groups)?.contiguous()?, crate::utils::repeat_kv(value_states, self.num_kv_groups)?.contiguous()?, ) } else { (key_states, value_states) }; let attn_output = { let scale = 1f64 / f64::sqrt(self.head_dim as f64); let attn_weights = query_states.matmul(&key_states.transpose(2, 3)?)?; let attn_weights = (attn_weights * 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, self.hidden_size))? .apply(&self.o_proj) } } #[derive(Debug, Clone)] enum NormType { Layer(LayerNorm), Rms(RmsNorm), } #[derive(Debug, Clone)] struct Layer { variant: ModelVariant, attention: Attention, mlp: MLP, // For 1.5B: this is `input_layernorm` // For 400M: this is `output_layernorm` layernorm: NormType, post_attention_layernorm: NormType, } impl Layer { fn new(rotary_emb: Arc<RotaryEmbedding>, cfg: &Config, vb: VarBuilder) -> Result<Self> { let attention = Attention::new( rotary_emb, cfg, vb.pp(if cfg.variant == ModelVariant::Large { "self_attn" } else { "attention" }), )?; let mlp = MLP::new(cfg, vb.pp("mlp"))?; let (layernorm, post_attention_layernorm) = match cfg.variant { ModelVariant::Large => ( NormType::Rms(RmsNorm::new( cfg.hidden_size, cfg.norm_eps, vb.pp("input_layernorm"), )?), NormType::Rms(RmsNorm::new( cfg.hidden_size, cfg.norm_eps, vb.pp("post_attention_layernorm"), )?), ), ModelVariant::Small => ( NormType::Layer(layer_norm( cfg.hidden_size, candle_nn::LayerNormConfig { eps: cfg.norm_eps, ..Default::default() }, vb.pp("mlp_ln"), )?), NormType::Layer(layer_norm( cfg.hidden_size, candle_nn::LayerNormConfig { eps: cfg.norm_eps, ..Default::default() }, vb.pp("attn_ln"), )?), ), }; Ok(Self { variant: cfg.variant, attention, mlp, layernorm, post_attention_layernorm, }) } fn forward(&mut self, xs: &Tensor, attention_mask: Option<&Tensor>) -> Result<Tensor> { // Here, the application of normalizations and activation calculations differ // For Large [1.5B]: // residual = x // state = other_layernorm(xs) // state = attention(state) // state += residual // residual = state // state = mlp(attention_layernorm(state)) // -> residual + state // For Small [400M]: // residual = x; // state = attention(x) // state += residual // state = attention_layernorm(state) // residual = state // state = mlp(state) // state += residual // -> other_layernorm(state) let residual = xs; match self.variant { ModelVariant::Large => { let (attn_ln, input_ln) = if let (NormType::Rms(attn_ln), NormType::Rms(input_ln)) = (&self.post_attention_layernorm, &self.layernorm) { (attn_ln, input_ln) } else { return Err(candle::error::Error::Msg( "Stella 1.5B expects RMSNorm".to_string(), )); }; let xs = input_ln.forward(xs)?; let xs = (self.attention.forward(&xs, attention_mask)? + residual)?; let residual = &xs; let xs = xs.apply(attn_ln)?.apply(&self.mlp)?; residual + xs } ModelVariant::Small => { let (attn_ln, output_ln) = if let (NormType::Layer(attn_ln), NormType::Layer(input_ln)) = (&self.post_attention_layernorm, &self.layernorm) { (attn_ln, input_ln) } else { return Err(candle::error::Error::Msg( "Stella 400M expects RMSNorm".to_string(), )); }; let xs = (self.attention.forward(xs, attention_mask)? + residual)?; let xs = attn_ln.forward(&xs)?; let residual = &xs; let xs = (self.mlp.forward(&xs)? + residual)?; output_ln.forward(&xs) } } } } #[derive(Debug, Clone)] pub struct Embeddings { variant: ModelVariant, // For 1.5B: this is the `embed_tokens` // For 400M: this is the `word_embeddings` embeddings: candle_nn::Embedding, // folloing are specifically for 400M token_type_embeddings: Option<candle_nn::Embedding>, layer_norm: Option<LayerNorm>, position_ids: Option<Tensor>, } impl Embeddings { pub fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let (embeddings, token_type_embeddings, layer_norm, position_ids) = match cfg.variant { ModelVariant::Large => ( candle_nn::embedding(cfg.vocab_size, cfg.hidden_size, vb.pp("embed_tokens"))?, None, None, None, ), ModelVariant::Small => { let vb = vb.pp("embeddings"); let weight = vb.pp("LayerNorm").get_with_hints( cfg.hidden_size, "weight", candle_nn::Init::Const(1.0), )?; let bias = vb.pp("LayerNorm").get_with_hints( cfg.hidden_size, "bias", candle_nn::Init::Const(0.0), )?; let dev = bias.device().clone(); let layer_norm = candle_nn::LayerNorm::new(weight, bias, cfg.norm_eps); ( candle_nn::embedding( cfg.vocab_size, cfg.hidden_size, vb.pp("word_embeddings"), )?, Some(candle_nn::embedding( cfg.type_vocab_size, cfg.hidden_size, vb.pp("token_type_embeddings"), )?), Some(layer_norm), Some(Tensor::arange( 0u32, cfg.max_position_embeddings as u32, &dev, )?), ) } }; Ok(Self { variant: cfg.variant, embeddings, token_type_embeddings, layer_norm, position_ids, }) } } impl Module for Embeddings { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let embd = self.embeddings.forward(xs)?; // For 1.5B just forward the embeddings if self.variant == ModelVariant::Large { return Ok(embd); } let (token_type_embed, layer_norm, pos_ids) = if let (Some(token_type_embd), Some(layer_norm), Some(position_ids)) = ( &self.token_type_embeddings, &self.layer_norm, &self.position_ids, ) { (token_type_embd, layer_norm, position_ids) } else { return Err(Error::Msg( "Stella 400M requires `token_type_embeddings`, `layer_norm` and `position_ids`" .to_string(), )); }; let (batch_size, seq_length) = xs.dims2()?; let pos_ids = pos_ids .as_ref() .narrow(0, 0, seq_length)? .expand((batch_size, seq_length))?; layer_norm.forward(&embd.add(&token_type_embed.forward(&pos_ids.zeros_like()?)?)?) } } #[derive(Debug, Clone)] pub struct Model { embeddings: Embeddings, layers: Vec<Layer>, norm: Option<RmsNorm>, device: Device, dtype: DType, } impl Model { pub fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let vb_m = match cfg.variant { ModelVariant::Large => vb.pp("model"), ModelVariant::Small => vb.pp("new"), }; // let embed_tokens = // candle_nn::embedding(cfg.vocab_size, cfg.hidden_size, vb_m.pp("embed_tokens"))?; let embeddings = Embeddings::new(cfg, vb_m.clone())?; 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 = match cfg.variant { ModelVariant::Large => vb_m.pp("layers"), ModelVariant::Small => vb_m.pp("encoder").pp("layer"), }; for layer_idx in 0..cfg.num_hidden_layers { let layer = Layer::new(rotary_emb.clone(), cfg, vb_l.pp(layer_idx))?; layers.push(layer) } let norm = match cfg.variant { ModelVariant::Large => Some(RmsNorm::new( cfg.hidden_size, cfg.norm_eps, vb_m.pp("norm"), )?), ModelVariant::Small => None, }; Ok(Self { embeddings, layers, norm, device: vb.device().clone(), dtype: vb.dtype(), }) } fn prepare_attention_mask(&self, attn_mask: &Tensor) -> Result<Tensor> { let (b_sz, sql_len) = attn_mask.dims2()?; let mut mask: Vec<Tensor> = vec![]; for b in 0..b_sz { mask.push(attn_mask.i((b, ..))?.expand((1, 1, sql_len, sql_len))?); } let mask = Tensor::cat(&mask, 0)?; let on_true = mask.zeros_like()?.to_dtype(self.dtype)?; let on_false = Tensor::new(f32::NEG_INFINITY, &self.device)? .broadcast_as(mask.shape())? .to_dtype(self.dtype)?; mask.where_cond(&on_true, &on_false) } pub fn forward(&mut self, input_ids: &Tensor, mask: &Tensor) -> Result<Tensor> { let (_, seq_len) = input_ids.dims2()?; let attention_mask = if seq_len <= 1 { None } else { // This is not a `causal language modelling` task, we'll need to prepare a `non-causal` attention Some(self.prepare_attention_mask(mask)?) }; let mut xs = self.embeddings.forward(input_ids)?; for layer in self.layers.iter_mut() { xs = layer.forward(&xs, attention_mask.as_ref())? } if let Some(n) = &self.norm { xs.apply(n) } else { Ok(xs) } } } #[derive(Debug)] pub struct EmbeddingModel { base_model: Model, lm_head: Linear, } impl EmbeddingModel { pub fn new(cfg: &Config, base_vb: VarBuilder, embed_vb: VarBuilder) -> Result<Self> { let base_model = Model::new(cfg, base_vb.clone())?; let lm_head = linear( cfg.embed_head.in_features, cfg.embed_head.out_features, embed_vb.pp("linear"), )?; Ok(Self { base_model, lm_head, }) } pub fn forward(&mut self, input_ids: &Tensor, mask: &Tensor) -> Result<Tensor> { let x = self.base_model.forward(input_ids, mask)?; let x = self.pool(&x, mask)?; // No matter what keeping the final activations as F32 helps with the accuracy self.lm_head.forward(&x.to_dtype(DType::F32)?) // [B_sz, dim_size] } /// Same as forward pass but normalizes the output pub fn forward_norm(&mut self, input_ids: &Tensor, mask: &Tensor) -> Result<Tensor> { let x = self.forward(input_ids, mask)?; // Normalize x.broadcast_div(&x.sqr()?.sum_keepdim(1)?.sqrt()?) } fn pool(&self, x: &Tensor, mask: &Tensor) -> Result<Tensor> { let mask = mask.to_dtype(x.dtype())?; // [B_Sz, Seq_len] let (batch_size, seq_len, hidden_dim) = x.dims3()?; // expanding the shape of the mask from [B_Sz, Seq_len] -> [B_Sz, Seq_len, Hidden_size] let mask_expanded = mask .unsqueeze(2)? .broadcast_as((batch_size, seq_len, hidden_dim))?; // [B_Sz, Seq_len, Hidden_dim] let x = (x * &mask_expanded)?; // Sum let sum_mask = mask .sum(1)? .unsqueeze(1)? .expand((batch_size, hidden_dim))?; x.sum(1)? / sum_mask } }
candle/candle-transformers/src/models/stella_en_v5.rs/0
{ "file_path": "candle/candle-transformers/src/models/stella_en_v5.rs", "repo_id": "candle", "token_count": 14806 }
63
use candle::{Result, Tensor}; #[derive(Debug, Clone)] pub struct DDPMWSchedulerConfig { scaler: f64, s: f64, } impl Default for DDPMWSchedulerConfig { fn default() -> Self { Self { scaler: 1f64, s: 0.008f64, } } } pub struct DDPMWScheduler { init_alpha_cumprod: f64, init_noise_sigma: f64, timesteps: Vec<f64>, pub config: DDPMWSchedulerConfig, } impl DDPMWScheduler { pub fn new(inference_steps: usize, config: DDPMWSchedulerConfig) -> Result<Self> { let init_alpha_cumprod = (config.s / (1. + config.s) * std::f64::consts::PI) .cos() .powi(2); let timesteps = (0..=inference_steps) .map(|i| 1. - i as f64 / inference_steps as f64) .collect::<Vec<_>>(); Ok(Self { init_alpha_cumprod, init_noise_sigma: 1.0, timesteps, config, }) } pub fn timesteps(&self) -> &[f64] { &self.timesteps } fn alpha_cumprod(&self, t: f64) -> f64 { let scaler = self.config.scaler; let s = self.config.s; let t = if scaler > 1. { 1. - (1. - t).powf(scaler) } else if scaler < 1. { t.powf(scaler) } else { t }; let alpha_cumprod = ((t + s) / (1. + s) * std::f64::consts::PI * 0.5) .cos() .powi(2) / self.init_alpha_cumprod; alpha_cumprod.clamp(0.0001, 0.9999) } fn previous_timestep(&self, ts: f64) -> f64 { let index = self .timesteps .iter() .enumerate() .map(|(idx, v)| (idx, (v - ts).abs())) .min_by(|x, y| x.1.total_cmp(&y.1)) .unwrap() .0; self.timesteps[index + 1] } /// Ensures interchangeability with schedulers that need to scale the denoising model input /// depending on the current timestep. pub fn scale_model_input(&self, sample: Tensor, _timestep: usize) -> Tensor { sample } pub fn step(&self, model_output: &Tensor, ts: f64, sample: &Tensor) -> Result<Tensor> { let prev_t = self.previous_timestep(ts); let alpha_cumprod = self.alpha_cumprod(ts); let alpha_cumprod_prev = self.alpha_cumprod(prev_t); let alpha = alpha_cumprod / alpha_cumprod_prev; let mu = (sample - model_output * ((1. - alpha) / (1. - alpha_cumprod).sqrt()))?; let mu = (mu * (1. / alpha).sqrt())?; let std_noise = mu.randn_like(0., 1.)?; let std = std_noise * ((1. - alpha) * (1. - alpha_cumprod_prev) / (1. - alpha_cumprod)).sqrt(); if prev_t == 0. { Ok(mu) } else { mu + std } } pub fn init_noise_sigma(&self) -> f64 { self.init_noise_sigma } }
candle/candle-transformers/src/models/wuerstchen/ddpm.rs/0
{ "file_path": "candle/candle-transformers/src/models/wuerstchen/ddpm.rs", "repo_id": "candle", "token_count": 1537 }
64
## Running [llama2.c](https://github.com/karpathy/llama2.c) Examples Here, we provide two examples of how to run [llama2.c](https://github.com/karpathy/llama2.c) written in Rust using a Candle-compiled WASM binary and runtimes. ### Pure Rust UI To build and test the UI made in Rust you will need [Trunk](https://trunkrs.dev/#install) From the `candle-wasm-examples/llama2-c` directory run: Download assets: ```bash # Model and tokenizer wget -c https://huggingface.co/spaces/lmz/candle-llama2/resolve/main/model.bin wget -c https://huggingface.co/spaces/lmz/candle-llama2/resolve/main/tokenizer.json ``` Run hot reload server: ```bash trunk serve --release --public-url / --port 8080 ``` ### Vanilla JS and WebWorkers To build and test the UI made in Vanilla JS and WebWorkers, first we need to build the WASM library: ```bash sh build-lib.sh ``` This will bundle the library under `./build` and we can import it inside our WebWorker like a normal JS module: ```js import init, { Model } from "./build/m.js"; ``` The full example can be found under `./lib-example.html`. All needed assets are fetched from the web, so no need to download anything. Finally, you can preview the example by running a local HTTP server. For example: ```bash python -m http.server ``` Then open `http://localhost:8000/lib-example.html` in your browser.
candle/candle-wasm-examples/llama2-c/README.md/0
{ "file_path": "candle/candle-wasm-examples/llama2-c/README.md", "repo_id": "candle", "token_count": 449 }
65
<html> <head> <meta content="text/html;charset=utf-8" http-equiv="Content-Type" /> <title>Candle Moondream Rust/WASM</title> </head> <body></body> </html> <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@11.8.0/build/styles/default.min.css" /> <style> @import url("https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght@200;300;400&family=Source+Sans+3:wght@100;200;300;400;500;600;700;800;900&display=swap"); html, body { font-family: "Source Sans 3", sans-serif; } code, output, select, pre { font-family: "Source Code Pro", monospace; } </style> <style type="text/tailwindcss"> .link { @apply underline hover:text-blue-500 hover:no-underline; } </style> <script src="https://cdn.tailwindcss.com/3.4.3"></script> <script type="module" src="./code.js"></script> </head> <body class="container max-w-4xl mx-auto p-4 text-gray-800"> <main class="grid grid-cols-1 gap-8 relative"> <span class="absolute text-5xl -ml-[1em]"> 🕯️ </span> <div> <h1 class="text-5xl font-bold">Candle Moondream 2</h1> <h2 class="text-2xl font-bold">Rust/WASM Demo</h2> <p class="max-w-lg"> <a href="https://huggingface.co/vikhyatk/moondream2" class="link" target="_blank" >Moondream 2</a > by <a href=" https://huggingface.co/vikhyatk" class="link" target="_blank" >Vik</a > and model implementation on Candle by <a href="https://huggingface.co/santiagomed" class="link" target="_blank" >Santiago Medina </a> </p> </div> <div> <p class="text-xs italic max-w-lg"> <b>Note:</b> When first run, the app will download and cache the model, which could take a few minutes. Then, the embeddings and generation will take a few minutes to start 😔. </p> </div> <div> <label for="model" class="font-medium">Models Options: </label> <select id="model" class="border-2 border-gray-500 rounded-md font-light" ></select> </div> <form id="form" class="flex text-normal px-1 py-1 border border-gray-700 rounded-md items-center" > <input type="submit" hidden /> <input type="text" id="prompt" class="font-light text-lg w-full px-3 py-2 mx-1 resize-none outline-none" placeholder="Add your prompt here..." /> <button id="run" class="bg-gray-700 hover:bg-gray-800 text-white font-normal py-2 w-16 rounded disabled:bg-gray-300 disabled:cursor-not-allowed" > Run </button> </form> <details> <summary class="font-medium cursor-pointer">Advanced Options</summary> <div class="grid grid-cols-3 max-w-md items-center gap-3 py-3"> <label class="text-sm font-medium" for="max-seq" >Maximum length </label> <input type="range" id="max-seq" name="max-seq" min="1" max="2048" step="1" value="500" oninput="this.nextElementSibling.value = Number(this.value)" /> <output class="text-xs w-[50px] text-center font-light px-1 py-1 border border-gray-700 rounded-md" > 500</output > <label class="text-sm font-medium" for="temperature" >Temperature</label > <input type="range" id="temperature" name="temperature" min="0" max="2" step="0.01" value="0.00" oninput="this.nextElementSibling.value = Number(this.value).toFixed(2)" /> <output class="text-xs w-[50px] text-center font-light px-1 py-1 border border-gray-700 rounded-md" > 0.00</output > <label class="text-sm font-medium" for="top-p">Top-p</label> <input type="range" id="top-p" name="top-p" min="0" max="1" step="0.01" value="1.00" oninput="this.nextElementSibling.value = Number(this.value).toFixed(2)" /> <output class="text-xs w-[50px] text-center font-light px-1 py-1 border border-gray-700 rounded-md" > 1.00</output > <label class="text-sm font-medium" for="repeat_penalty" >Repeat Penalty</label > <input type="range" id="repeat_penalty" name="repeat_penalty" min="1" max="2" step="0.01" value="1.10" oninput="this.nextElementSibling.value = Number(this.value).toFixed(2)" /> <output class="text-xs w-[50px] text-center font-light px-1 py-1 border border-gray-700 rounded-md" >1.10</output > <label class="text-sm font-medium" for="seed">Seed</label> <input type="number" id="seed" name="seed" value="299792458" class="font-light border border-gray-700 text-right rounded-md p-2" /> <button id="run" onclick="document.querySelector('#seed').value = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)" class="bg-gray-700 hover:bg-gray-800 text-white font-normal py-1 w-[50px] rounded disabled:bg-gray-300 disabled:cursor-not-allowed text-sm" > Rand </button> </div> </details> <div class="grid md:grid-cols-2 gap-4 items-start"> <div> <div class="relative md:mt-6"> <div class="absolute w-full bottom-full flex justify-between items-center" > <div class="flex gap-2 w-full"> <button id="clear-img-btn" disabled title="Clear Image" class="ml-auto text-xs py-1 bg-white rounded-md disabled:opacity-20 flex gap-1 items-center" > <svg class="" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 12" height="1em" > <path d="M1.6.7 12 11.1M12 .7 1.6 11.1" stroke="#2E3036" stroke-width="2" /> </svg> </button> </div> </div> <div id="drop-area" class="min-h-[250px] flex flex-col items-center justify-center border-2 border-gray-300 border-dashed rounded-xl relative w-full overflow-hidden" > <div class="absolute flex flex-col items-center justify-center space-y-1 text-center" > <svg width="25" height="25" viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg" > <path d="M3.5 24.3a3 3 0 0 1-1.9-.8c-.5-.5-.8-1.2-.8-1.9V2.9c0-.7.3-1.3.8-1.9.6-.5 1.2-.7 2-.7h18.6c.7 0 1.3.2 1.9.7.5.6.7 1.2.7 2v18.6c0 .7-.2 1.4-.7 1.9a3 3 0 0 1-2 .8H3.6Zm0-2.7h18.7V2.9H3.5v18.7Zm2.7-2.7h13.3c.3 0 .5 0 .6-.3v-.7l-3.7-5a.6.6 0 0 0-.6-.2c-.2 0-.4 0-.5.3l-3.5 4.6-2.4-3.3a.6.6 0 0 0-.6-.3c-.2 0-.4.1-.5.3l-2.7 3.6c-.1.2-.2.4 0 .7.1.2.3.3.6.3Z" fill="#000" /> </svg> <div class="flex text-sm text-gray-600"> <label for="file-upload" class="relative cursor-pointer bg-white rounded-md font-medium text-blue-950 hover:text-blue-700" > <span>Drag and drop the image here</span> <span class="block text-xs">or</span> <span class="block text-xs">Click to upload</span> </label> </div> <input id="file-upload" name="file-upload" type="file" accept="image/*" class="sr-only" /> </div> <canvas id="canvas" class="z-10 pointer-events-none w-full" ></canvas> </div> </div> </div> <div> <h3 class="font-medium">Generation:</h3> <div class="min-h-[250px] bg-slate-100 text-gray-500 p-4 rounded-md flex flex-col gap-2" > <div id="output-counter" hidden class="ml-auto font-semibold grid-rows-1" ></div> <p hidden id="output-generation" class="grid-rows-2 text-lg"></p> <span id="output-status" class="m-auto font-light" >No output yet</span > </div> </div> </div> <div> <div class="flex gap-3 items-center overflow-x-scroll" id="image-select" > <h3 class="font-medium">Examples:</h3> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/candle/examples/sf.jpg" class="cursor-pointer w-24 h-24 object-cover" /> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/candle/examples/bike.jpeg" class="cursor-pointer w-24 h-24 object-cover" /> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/candle/examples/000000000077.jpg" class="cursor-pointer w-24 h-24 object-cover" /> <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/candle/examples/demo-1.jpg" class="cursor-pointer w-24 h-24 object-cover" /> </div> </div> </main> </body> </html>
candle/candle-wasm-examples/moondream/index.html/0
{ "file_path": "candle/candle-wasm-examples/moondream/index.html", "repo_id": "candle", "token_count": 6120 }
66
use candle::{DType, Device, Tensor}; use candle_nn::VarBuilder; use candle_wasm_example_sam as sam; use wasm_bindgen::prelude::*; struct Embeddings { original_width: u32, original_height: u32, width: u32, height: u32, data: Tensor, } #[wasm_bindgen] pub struct Model { sam: sam::Sam, embeddings: Option<Embeddings>, } #[wasm_bindgen] impl Model { #[wasm_bindgen(constructor)] pub fn new(weights: Vec<u8>, use_tiny: bool) -> Result<Model, JsError> { console_error_panic_hook::set_once(); let dev = &Device::Cpu; let vb = VarBuilder::from_buffered_safetensors(weights, DType::F32, dev)?; let sam = if use_tiny { sam::Sam::new_tiny(vb)? // tiny vit_t } else { sam::Sam::new(768, 12, 12, &[2, 5, 8, 11], vb)? // sam_vit_b }; Ok(Self { sam, embeddings: None, }) } pub fn set_image_embeddings(&mut self, image_data: Vec<u8>) -> Result<(), JsError> { sam::console_log!("image data: {}", image_data.len()); let image_data = std::io::Cursor::new(image_data); let image = image::ImageReader::new(image_data) .with_guessed_format()? .decode() .map_err(candle::Error::wrap)?; let (original_height, original_width) = (image.height(), image.width()); let (height, width) = (original_height, original_width); let resize_longest = sam::IMAGE_SIZE as u32; let (height, width) = if height < width { let h = (resize_longest * height) / width; (h, resize_longest) } else { let w = (resize_longest * width) / height; (resize_longest, w) }; let image_t = { let img = image.resize_exact(width, height, image::imageops::FilterType::CatmullRom); let data = img.to_rgb8().into_raw(); Tensor::from_vec( data, (img.height() as usize, img.width() as usize, 3), &Device::Cpu, )? .permute((2, 0, 1))? }; let data = self.sam.embeddings(&image_t)?; self.embeddings = Some(Embeddings { original_width, original_height, width, height, data, }); Ok(()) } pub fn mask_for_point(&self, input: JsValue) -> Result<JsValue, JsError> { let input: PointsInput = serde_wasm_bindgen::from_value(input).map_err(|m| JsError::new(&m.to_string()))?; let transformed_points = input.points; for &(x, y, _bool) in &transformed_points { if !(0.0..=1.0).contains(&x) { return Err(JsError::new(&format!( "x has to be between 0 and 1, got {x}" ))); } if !(0.0..=1.0).contains(&y) { return Err(JsError::new(&format!( "y has to be between 0 and 1, got {y}" ))); } } let embeddings = match &self.embeddings { None => Err(JsError::new("image embeddings have not been set"))?, Some(embeddings) => embeddings, }; let (mask, iou_predictions) = self.sam.forward_for_embeddings( &embeddings.data, embeddings.height as usize, embeddings.width as usize, &transformed_points, false, )?; let iou = iou_predictions.flatten(0, 1)?.to_vec1::<f32>()?[0]; let mask_shape = mask.dims().to_vec(); let mask_data = mask.ge(0f32)?.flatten_all()?.to_vec1::<u8>()?; let mask = Mask { iou, mask_shape, mask_data, }; let image = Image { original_width: embeddings.original_width, original_height: embeddings.original_height, width: embeddings.width, height: embeddings.height, }; Ok(serde_wasm_bindgen::to_value(&MaskImage { mask, image })?) } } #[derive(serde::Serialize, serde::Deserialize)] struct Mask { iou: f32, mask_shape: Vec<usize>, mask_data: Vec<u8>, } #[derive(serde::Serialize, serde::Deserialize)] struct Image { original_width: u32, original_height: u32, width: u32, height: u32, } #[derive(serde::Serialize, serde::Deserialize)] struct MaskImage { mask: Mask, image: Image, } #[derive(serde::Serialize, serde::Deserialize)] struct PointsInput { points: Vec<(f64, f64, bool)>, } fn main() { console_error_panic_hook::set_once(); }
candle/candle-wasm-examples/segment-anything/src/bin/m.rs/0
{ "file_path": "candle/candle-wasm-examples/segment-anything/src/bin/m.rs", "repo_id": "candle", "token_count": 2359 }
67
<html> <head> <meta content="text/html;charset=utf-8" http-equiv="Content-Type" /> <title>Candle Whisper Rust/WASM</title> </head> <body></body> </html> <!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <style> @import url("https://fonts.googleapis.com/css2?family=Source+Code+Pro:wght@200;300;400&family=Source+Sans+3:wght@100;200;300;400;500;600;700;800;900&display=swap"); html, body { font-family: "Source Sans 3", sans-serif; } </style> <script src="https://cdn.tailwindcss.com"></script> <script type="module"> // base url for audio examples const AUDIO_BASE_URL = "https://huggingface.co/datasets/Narsil/candle-examples/resolve/main/"; // models base url const MODELS = { tiny_multilingual: { base_url: "https://huggingface.co/openai/whisper-tiny/resolve/main/", model: "model.safetensors", tokenizer: "tokenizer.json", config: "config.json", size: "151 MB", }, tiny_en: { base_url: "https://huggingface.co/openai/whisper-tiny.en/resolve/main/", model: "model.safetensors", tokenizer: "tokenizer.json", config: "config.json", size: "151 MB", }, tiny_quantized_multilingual_q80: { base_url: "https://huggingface.co/lmz/candle-whisper/resolve/main/", model: "model-tiny-q80.gguf", tokenizer: "tokenizer-tiny.json", config: "config-tiny.json", size: "41.5 MB", }, tiny_en_quantized_q80: { base_url: "https://huggingface.co/lmz/candle-whisper/resolve/main/", model: "model-tiny-q80.gguf", tokenizer: "tokenizer-tiny-en.json", config: "config-tiny-en.json", size: "41.8 MB", }, distil_medium_en: { base_url: "https://huggingface.co/distil-whisper/distil-medium.en/resolve/main/", model: "model.safetensors", tokenizer: "tokenizer.json", config: "config.json", size: "789 MB", }, }; const modelEl = document.querySelector("#model"); Object.keys(MODELS).forEach((modelID) => { const model = MODELS[modelID]; const option = document.createElement("option"); option.value = modelID; option.textContent = `${modelID} (${model.size})`; modelEl.appendChild(option); }); const whisperWorker = new Worker("./whisperWorker.js", { type: "module", }); async function classifyAudio( weightsURL, // URL to the weights file modelID, // model ID tokenizerURL, // URL to the tokenizer file configURL, // model config URL mel_filtersURL, // URL to the mel filters file audioURL, // URL to the audio file updateStatus // function to update the status ) { return new Promise((resolve, reject) => { whisperWorker.postMessage({ weightsURL, modelID, tokenizerURL, configURL, mel_filtersURL, audioURL, }); function messageHandler(event) { console.log(event.data); if ("status" in event.data) { updateStatus(event.data); } if ("error" in event.data) { whisperWorker.removeEventListener("message", messageHandler); reject(new Error(event.data.error)); } if (event.data.status === "complete") { whisperWorker.removeEventListener("message", messageHandler); resolve(event.data); } } whisperWorker.addEventListener("message", messageHandler); }); } // keep track of the audio URL let audioURL = null; function setAudio(src) { const audio = document.querySelector("#audio"); audio.src = src; audio.controls = true; audio.hidden = false; document.querySelector("#detect").disabled = false; audioURL = src; } // add event listener to audio buttons document.querySelectorAll("#audios-select > button").forEach((target) => { target.addEventListener("click", (e) => { const value = target.dataset.value; const href = AUDIO_BASE_URL + value; setAudio(href); }); }); //add event listener to file input document.querySelector("#file-upload").addEventListener("change", (e) => { const target = e.target; if (target.files.length > 0) { const href = URL.createObjectURL(target.files[0]); setAudio(href); } }); // add event listener to drop-area const dropArea = document.querySelector("#drop-area"); dropArea.addEventListener("dragenter", (e) => { e.preventDefault(); dropArea.classList.add("border-blue-700"); }); dropArea.addEventListener("dragleave", (e) => { e.preventDefault(); dropArea.classList.remove("border-blue-700"); }); dropArea.addEventListener("dragover", (e) => { e.preventDefault(); dropArea.classList.add("border-blue-700"); }); dropArea.addEventListener("drop", (e) => { e.preventDefault(); dropArea.classList.remove("border-blue-700"); const url = e.dataTransfer.getData("text/uri-list"); const files = e.dataTransfer.files; if (files.length > 0) { const href = URL.createObjectURL(files[0]); setAudio(href); } else if (url) { setAudio(url); } }); // add event listener to detect button document.querySelector("#detect").addEventListener("click", async () => { if (audioURL === null) { return; } const modelID = modelEl.value; const model = MODELS[modelID]; const modelURL = model.base_url + model.model; const tokenizerURL = model.base_url + model.tokenizer; const configURL = model.base_url + model.config; classifyAudio( modelURL, modelID, tokenizerURL, configURL, "mel_filters.safetensors", audioURL, updateStatus ) .then((result) => { console.log("RESULT", result); const { output } = result; const text = output.map((segment) => segment.dr.text).join(" "); console.log(text); document.querySelector("#output-status").hidden = true; document.querySelector("#output-generation").hidden = false; document.querySelector("#output-generation").textContent = text; }) .catch((error) => { console.error(error); }); }); function updateStatus(data) { const { status, message } = data; const button = document.querySelector("#detect"); if (status === "decoding" || status === "loading") { button.disabled = true; button.textContent = message; } else if (status === "complete") { button.disabled = false; button.textContent = "Transcribe Audio"; } } </script> </head> <body class="container max-w-4xl mx-auto p-4"> <main class="grid grid-cols-1 gap-8 relative"> <span class="absolute text-5xl -ml-[1em]"> 🕯️ </span> <div> <h1 class="text-5xl font-bold">Candle Whisper</h1> <h2 class="text-2xl font-bold">Rust/WASM Demo</h2> <p class="max-w-lg"> Transcribe audio in the browser using rust/wasm with an audio file. This demo uses the <a href="https://huggingface.co/openai/" target="_blank" class="underline hover:text-blue-500 hover:no-underline"> OpenAI Whisper models </a> and WASM runtime built with <a href="https://github.com/huggingface/candle/" target="_blank" class="underline hover:text-blue-500 hover:no-underline" >Candle </a> </p> </div> <div> <label for="model" class="font-medium">Models Options: </label> <select id="model" class="border-2 border-gray-500 rounded-md font-light"> </select> </div> <!-- drag and drop area --> <div class="relative"> <div id="drop-area" class="flex flex-col items-center justify-center border-2 border-gray-300 border-dashed rounded-xl relative h-48 w-full overflow-hidden"> <div class="flex flex-col items-center justify-center space-y-1 text-center"> <svg width="25" height="25" viewBox="0 0 25 25" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M3.5 24.3a3 3 0 0 1-1.9-.8c-.5-.5-.8-1.2-.8-1.9V2.9c0-.7.3-1.3.8-1.9.6-.5 1.2-.7 2-.7h18.6c.7 0 1.3.2 1.9.7.5.6.7 1.2.7 2v18.6c0 .7-.2 1.4-.7 1.9a3 3 0 0 1-2 .8H3.6Zm0-2.7h18.7V2.9H3.5v18.7Zm2.7-2.7h13.3c.3 0 .5 0 .6-.3v-.7l-3.7-5a.6.6 0 0 0-.6-.2c-.2 0-.4 0-.5.3l-3.5 4.6-2.4-3.3a.6.6 0 0 0-.6-.3c-.2 0-.4.1-.5.3l-2.7 3.6c-.1.2-.2.4 0 .7.1.2.3.3.6.3Z" fill="#000" /> </svg> <div class="flex text-sm text-gray-600"> <label for="file-upload" class="relative cursor-pointer bg-white rounded-md font-medium text-blue-950 hover:text-blue-700"> <span>Drag and drop your audio here</span> <span class="block text-xs">or</span> <span class="block text-xs">Click to upload</span> </label> </div> <input id="file-upload" name="file-upload" type="file" accept="audio/*" class="sr-only" /> </div> <audio id="audio" hidden controls class="w-full p-2 select-none"></audio> </div> </div> <div> <div class="flex flex-wrap gap-3 items-center" id="audios-select"> <h3 class="font-medium">Examples:</h3> <button data-value="samples_jfk.wav" class="text-gray-500 border border-gray-500 rounded-md p-2 underline hover:no-underline"> <span>jfk.wav</span> <span class="text-xs block"> (352 kB)</span> </button> <button data-value="samples_a13.wav" class="text-gray-500 border border-gray-500 rounded-md p-2 underline hover:no-underline"> <span>a13.wav</span> <span class="text-xs block"> (960 kB)</span> </button> <button data-value="samples_mm0.wav" class="text-gray-500 border border-gray-500 rounded-md p-2 underline hover:no-underline"> <span>mm0.wav</span> <span class="text-xs block new"> (957 kB)</span> </button> <button data-value="samples_gb0.wav" class="text-gray-500 border border-gray-500 rounded-md p-2 underline hover:no-underline"> <span>gb0.wav </span> <span class="text-xs block">(4.08 MB)</span> </button> <button data-value="samples_gb1.wav" class="text-gray-500 border border-gray-500 rounded-md p-2 underline hover:no-underline"> <span>gb1.wav </span> <span class="text-xs block">(6.36 MB)</span> </button> <button data-value="samples_hp0.wav" class="text-gray-500 border border-gray-500 rounded-md p-2 underline hover:no-underline"> <span>hp0.wav </span> <span class="text-xs block">(8.75 MB)</span> </button> </div> </div> <div> <button id="detect" disabled class="bg-gray-700 hover:bg-gray-800 text-white font-normal py-2 px-4 rounded disabled:bg-gray-300 disabled:cursor-not-allowed"> Transcribe Audio </button> </div> <div> <h3 class="font-medium">Transcription:</h3> <div class="min-h-[250px] bg-slate-100 text-gray-500 p-4 rounded-md flex flex-col gap-2"> <p hidden id="output-generation" class="grid-rows-2"></p> <span id="output-status" class="m-auto font-light" >No transcription results yet</span > </div> </div> </main> </body> </html>
candle/candle-wasm-examples/whisper/lib-example.html/0
{ "file_path": "candle/candle-wasm-examples/whisper/lib-example.html", "repo_id": "candle", "token_count": 6488 }
68
use crate::console_log; use crate::worker::{ModelData, RunData, Worker, WorkerInput, WorkerOutput}; use wasm_bindgen::prelude::*; use wasm_bindgen_futures::JsFuture; use yew::{html, Component, Context, Html}; use yew_agent::{Bridge, Bridged}; async fn fetch_url(url: &str) -> Result<Vec<u8>, JsValue> { use web_sys::{Request, RequestCache, RequestInit, RequestMode, Response}; let window = web_sys::window().ok_or("window")?; let opts = RequestInit::new(); opts.set_method("GET"); opts.set_mode(RequestMode::Cors); opts.set_cache(RequestCache::NoCache); let request = Request::new_with_str_and_init(url, &opts)?; let resp_value = JsFuture::from(window.fetch_with_request(&request)).await?; // `resp_value` is a `Response` object. assert!(resp_value.is_instance_of::<Response>()); let resp: Response = resp_value.dyn_into()?; let data = JsFuture::from(resp.blob()?).await?; let blob = web_sys::Blob::from(data); let array_buffer = JsFuture::from(blob.array_buffer()).await?; let data = js_sys::Uint8Array::new(&array_buffer).to_vec(); Ok(data) } pub enum Msg { Refresh, Run, UpdateStatus(String), SetModel(ModelData), WorkerIn(WorkerInput), WorkerOut(Result<WorkerOutput, String>), } pub struct CurrentDecode { start_time: Option<f64>, } pub struct App { status: String, loaded: bool, generated: String, current_decode: Option<CurrentDecode>, worker: Box<dyn Bridge<Worker>>, } async fn model_data_load() -> Result<ModelData, JsValue> { let weights = fetch_url("yolov8s.safetensors").await?; let model_size = "s".to_string(); console_log!("loaded weights {}", weights.len()); Ok(ModelData { weights, model_size, }) } fn performance_now() -> Option<f64> { let window = web_sys::window()?; let performance = window.performance()?; Some(performance.now() / 1000.) } fn draw_bboxes(bboxes: Vec<Vec<crate::model::Bbox>>) -> Result<(), JsValue> { let document = web_sys::window().unwrap().document().unwrap(); let canvas = match document.get_element_by_id("canvas") { Some(canvas) => canvas, None => return Err("no canvas".into()), }; let canvas: web_sys::HtmlCanvasElement = canvas.dyn_into::<web_sys::HtmlCanvasElement>()?; let context = canvas .get_context("2d")? .ok_or("no 2d")? .dyn_into::<web_sys::CanvasRenderingContext2d>()?; let image_html_element = document.get_element_by_id("bike-img"); let image_html_element = match image_html_element { Some(data) => data, None => return Err("no bike-img".into()), }; let image_html_element = image_html_element.dyn_into::<web_sys::HtmlImageElement>()?; canvas.set_width(image_html_element.natural_width()); canvas.set_height(image_html_element.natural_height()); context.draw_image_with_html_image_element(&image_html_element, 0., 0.)?; context.set_stroke_style(&JsValue::from("#0dff9a")); for (class_index, bboxes_for_class) in bboxes.iter().enumerate() { for b in bboxes_for_class.iter() { let name = crate::coco_classes::NAMES[class_index]; context.stroke_rect( b.xmin as f64, b.ymin as f64, (b.xmax - b.xmin) as f64, (b.ymax - b.ymin) as f64, ); if let Ok(metrics) = context.measure_text(name) { let width = metrics.width(); context.set_fill_style(&"#3c8566".into()); context.fill_rect(b.xmin as f64 - 2., b.ymin as f64 - 12., width + 4., 14.); context.set_fill_style(&"#e3fff3".into()); context.fill_text(name, b.xmin as f64, b.ymin as f64 - 2.)? } } } Ok(()) } impl Component for App { type Message = Msg; type Properties = (); fn create(ctx: &Context<Self>) -> Self { let status = "loading weights".to_string(); let cb = { let link = ctx.link().clone(); move |e| link.send_message(Self::Message::WorkerOut(e)) }; let worker = Worker::bridge(std::rc::Rc::new(cb)); Self { status, generated: String::new(), current_decode: None, worker, loaded: false, } } fn rendered(&mut self, ctx: &Context<Self>, first_render: bool) { if first_render { ctx.link().send_future(async { match model_data_load().await { Err(err) => { let status = format!("{err:?}"); Msg::UpdateStatus(status) } Ok(model_data) => Msg::SetModel(model_data), } }); } } fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool { match msg { Msg::SetModel(md) => { self.status = "weights loaded successfully!".to_string(); self.loaded = true; console_log!("loaded weights"); self.worker.send(WorkerInput::ModelData(md)); true } Msg::Run => { if self.current_decode.is_some() { self.status = "already processing some image at the moment".to_string() } else { let start_time = performance_now(); self.current_decode = Some(CurrentDecode { start_time }); self.status = "processing...".to_string(); self.generated.clear(); ctx.link().send_future(async { match fetch_url("bike.jpeg").await { Err(err) => { let status = format!("{err:?}"); Msg::UpdateStatus(status) } Ok(image_data) => Msg::WorkerIn(WorkerInput::RunData(RunData { image_data, conf_threshold: 0.5, iou_threshold: 0.5, })), } }); } true } Msg::WorkerOut(output) => { match output { Ok(WorkerOutput::WeightsLoaded) => self.status = "weights loaded!".to_string(), Ok(WorkerOutput::ProcessingDone(Err(err))) => { self.status = format!("error in worker process: {err}"); self.current_decode = None } Ok(WorkerOutput::ProcessingDone(Ok(bboxes))) => { let mut content = Vec::new(); for (class_index, bboxes_for_class) in bboxes.iter().enumerate() { for b in bboxes_for_class.iter() { content.push(format!( "bbox {}: xs {:.0}-{:.0} ys {:.0}-{:.0}", crate::coco_classes::NAMES[class_index], b.xmin, b.xmax, b.ymin, b.ymax )) } } self.generated = content.join("\n"); let dt = self.current_decode.as_ref().and_then(|current_decode| { current_decode.start_time.and_then(|start_time| { performance_now().map(|stop_time| stop_time - start_time) }) }); self.status = match dt { None => "processing succeeded!".to_string(), Some(dt) => format!("processing succeeded in {dt:.2}s",), }; self.current_decode = None; if let Err(err) = draw_bboxes(bboxes) { self.status = format!("{err:?}") } } Err(err) => { self.status = format!("error in worker {err:?}"); } } true } Msg::WorkerIn(inp) => { self.worker.send(inp); true } Msg::UpdateStatus(status) => { self.status = status; true } Msg::Refresh => true, } } fn view(&self, ctx: &Context<Self>) -> Html { html! { <div style="margin: 2%;"> <div><p>{"Running an object detection model in the browser using rust/wasm with "} <a href="https://github.com/huggingface/candle" target="_blank">{"candle!"}</a> </p> <p>{"Once the weights have loaded, click on the run button to process an image."}</p> <p><img id="bike-img" src="bike.jpeg"/></p> <p>{"Source: "}<a href="https://commons.wikimedia.org/wiki/File:V%C3%A9lo_parade_-_V%C3%A9lorution_-_bike_critical_mass.JPG">{"wikimedia"}</a></p> </div> { if self.loaded{ html!(<button class="button" onclick={ctx.link().callback(move |_| Msg::Run)}> { "run" }</button>) }else{ html! { <progress id="progress-bar" aria-label="Loading weights..."></progress> } } } <br/ > <h3> {&self.status} </h3> { if self.current_decode.is_some() { html! { <progress id="progress-bar" aria-label="generating…"></progress> } } else { html! {} } } <div> <canvas id="canvas" height="150" width="150"></canvas> </div> <blockquote> <p> { self.generated.chars().map(|c| if c == '\r' || c == '\n' { html! { <br/> } } else { html! { {c} } }).collect::<Html>() } </p> </blockquote> </div> } } }
candle/candle-wasm-examples/yolo/src/app.rs/0
{ "file_path": "candle/candle-wasm-examples/yolo/src/app.rs", "repo_id": "candle", "token_count": 5960 }
69
 backend-test:J  xytest"Relu SingleReluZ x   b y   B
candle/test.onnx/0
{ "file_path": "candle/test.onnx", "repo_id": "candle", "token_count": 76 }
70
set -e npx lint-staged --config ./.husky/lint-stage-config.js
chat-ui/.husky/pre-commit/0
{ "file_path": "chat-ui/.husky/pre-commit", "repo_id": "chat-ui", "token_count": 27 }
71
{{- if $.Values.autoscaling.enabled }} apiVersion: autoscaling/v2 kind: HorizontalPodAutoscaler metadata: labels: {{ include "labels.standard" . | nindent 4 }} name: {{ include "name" . }} namespace: {{ .Release.Namespace }} spec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: {{ include "name" . }} minReplicas: {{ $.Values.autoscaling.minReplicas }} maxReplicas: {{ $.Values.autoscaling.maxReplicas }} metrics: {{- if ne "" $.Values.autoscaling.targetMemoryUtilizationPercentage }} - type: Resource resource: name: memory target: type: Utilization averageUtilization: {{ $.Values.autoscaling.targetMemoryUtilizationPercentage | int }} {{- end }} {{- if ne "" $.Values.autoscaling.targetCPUUtilizationPercentage }} - type: Resource resource: name: cpu target: type: Utilization averageUtilization: {{ $.Values.autoscaling.targetCPUUtilizationPercentage | int }} {{- end }} behavior: scaleDown: stabilizationWindowSeconds: 600 policies: - type: Percent value: 10 periodSeconds: 60 scaleUp: stabilizationWindowSeconds: 0 policies: - type: Pods value: 1 periodSeconds: 30 {{- end }}
chat-ui/chart/templates/hpa.yaml/0
{ "file_path": "chat-ui/chart/templates/hpa.yaml", "repo_id": "chat-ui", "token_count": 543 }
72