text
stringlengths
5
631k
id
stringlengths
14
178
metadata
dict
__index_level_0__
int64
0
647
# coding=utf-8 # Copyright 2024 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 numpy as np from transformers.image_utils import PILImageResampling from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_torch_available, is_torchvision_available, is_vision_available from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs if is_vision_available(): from PIL import Image from transformers import PerceiverImageProcessor if is_torchvision_available(): from transformers import PerceiverImageProcessorFast if is_torch_available(): import torch class PerceiverImageProcessingTester: def __init__( self, parent, batch_size=7, num_channels=3, num_images=1, image_size=18, min_resolution=30, max_resolution=40, do_center_crop=True, crop_size=None, do_resize=True, size=None, do_rescale=True, rescale_factor=1 / 255, do_normalize=True, image_mean=[0.5, 0.5, 0.5], image_std=[0.5, 0.5, 0.5], resample=PILImageResampling.BICUBIC, ): self.crop_size = crop_size if crop_size is not None else {"height": 256, "width": 256} self.size = size if size is not None else {"height": 224, "width": 224} self.parent = parent self.batch_size = batch_size self.num_channels = num_channels self.num_images = num_images self.image_size = image_size self.min_resolution = min_resolution self.max_resolution = max_resolution self.do_center_crop = do_center_crop self.do_resize = do_resize self.resample = resample self.do_rescale = do_rescale self.rescale_factor = rescale_factor self.do_normalize = do_normalize self.image_mean = image_mean self.image_std = image_std def prepare_image_processor_dict(self): return { "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_resize": self.do_resize, "size": self.size, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "resample": self.resample, } def expected_output_image_shape(self, images): return self.num_channels, self.size["height"], self.size["width"] def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False): return prepare_image_inputs( batch_size=self.batch_size, num_channels=self.num_channels, min_resolution=self.min_resolution, max_resolution=self.max_resolution, equal_resolution=equal_resolution, numpify=numpify, torchify=torchify, ) @require_torch @require_vision class PerceiverImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase): image_processing_class = PerceiverImageProcessor if is_vision_available() else None fast_image_processing_class = PerceiverImageProcessorFast if is_torchvision_available() else None def setUp(self): super().setUp() self.image_processor_tester = PerceiverImageProcessingTester(self) @property def image_processor_dict(self): return self.image_processor_tester.prepare_image_processor_dict() def test_image_processor_properties(self): for image_processing_class in self.image_processor_list: image_processing = image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(image_processing, "do_center_crop")) self.assertTrue(hasattr(image_processing, "crop_size")) self.assertTrue(hasattr(image_processing, "do_resize")) self.assertTrue(hasattr(image_processing, "size")) self.assertTrue(hasattr(image_processing, "resample")) self.assertTrue(hasattr(image_processing, "do_rescale")) self.assertTrue(hasattr(image_processing, "rescale_factor")) self.assertTrue(hasattr(image_processing, "do_normalize")) self.assertTrue(hasattr(image_processing, "image_mean")) self.assertTrue(hasattr(image_processing, "image_std")) def test_call_numpy(self): for image_processing_class in self.image_processor_list: # Initialize image_processing image_processing = image_processing_class(**self.image_processor_dict) # create random numpy tensors image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True) for sample_images in image_inputs: for image in sample_images: self.assertIsInstance(image, np.ndarray) # Test not batched input encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]]) self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape)) # Test batched encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs) self.assertEqual( tuple(encoded_images.shape), (self.image_processor_tester.batch_size, *expected_output_image_shape) ) def test_call_numpy_4_channels(self): # Idefics3 always processes images as RGB, so it always returns images with 3 channels for image_processing_class in self.image_processor_list: # Initialize image_processing image_processor_dict = self.image_processor_dict image_processing = image_processing_class(**image_processor_dict) # create random numpy tensors image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True) for sample_images in image_inputs: for image in sample_images: self.assertIsInstance(image, np.ndarray) # Test not batched input encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]]) self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape)) # Test batched encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs) self.assertEqual( tuple(encoded_images.shape), (self.image_processor_tester.batch_size, *expected_output_image_shape) ) def test_call_pil(self): for image_processing_class in self.image_processor_list: # Initialize image_processing image_processing = image_processing_class(**self.image_processor_dict) # create random PIL images image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False) for image in image_inputs: self.assertIsInstance(image, Image.Image) # Test not batched input encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]]) self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape)) # Test batched encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs) self.assertEqual( tuple(encoded_images.shape), (self.image_processor_tester.batch_size, *expected_output_image_shape) ) def test_call_pytorch(self): for image_processing_class in self.image_processor_list: # Initialize image_processing image_processing = image_processing_class(**self.image_processor_dict) # create random PyTorch tensors image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True) for images in image_inputs: for image in images: self.assertIsInstance(image, torch.Tensor) # Test not batched input encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]]) self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape)) # Test batched expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs) encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values self.assertEqual( tuple(encoded_images.shape), (self.image_processor_tester.batch_size, *expected_output_image_shape), )
transformers/tests/models/perceiver/test_image_processing_perceiver.py/0
{ "file_path": "transformers/tests/models/perceiver/test_image_processing_perceiver.py", "repo_id": "transformers", "token_count": 4235 }
537
# coding=utf-8 # Copyright 2021 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 inspect import math import unittest import warnings import numpy as np import pytest from packaging import version from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import is_torch_available, is_torchvision_available, is_vision_available from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image if is_torchvision_available(): from transformers import Phi4MultimodalImageProcessorFast class Phi4MultimodalImageProcessingTester: def __init__( self, parent, batch_size=7, num_channels=3, image_size=100, min_resolution=30, max_resolution=400, dynamic_hd=36, do_resize=True, size=None, patch_size=14, do_normalize=True, image_mean=[0.5, 0.5, 0.5], image_std=[0.5, 0.5, 0.5], do_convert_rgb=True, ): super().__init__() size = size if size is not None else {"height": 100, "width": 100} self.parent = parent self.batch_size = batch_size self.num_channels = num_channels self.image_size = image_size self.min_resolution = min_resolution self.max_resolution = max_resolution self.dynamic_hd = dynamic_hd self.do_resize = do_resize self.size = size self.patch_size = patch_size self.do_normalize = do_normalize self.image_mean = image_mean self.image_std = image_std self.do_convert_rgb = do_convert_rgb def prepare_image_processor_dict(self): return { "do_resize": self.do_resize, "size": self.size, "patch_size": self.patch_size, "dynamic_hd": self.dynamic_hd, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_convert_rgb": self.do_convert_rgb, } def expected_output_image_shape(self, images): max_num_patches = 0 for image in images: if isinstance(image, Image.Image): width, height = image.size elif isinstance(image, np.ndarray): height, width = image.shape[:2] elif isinstance(image, torch.Tensor): height, width = image.shape[-2:] w_crop_num = math.ceil(width / float(self.size["width"])) h_crop_num = math.ceil(height / float(self.size["height"])) num_patches = min(w_crop_num * h_crop_num + 1, self.dynamic_hd) max_num_patches = max(max_num_patches, num_patches) num_patches = max_num_patches return num_patches, self.num_channels, self.size["height"], self.size["width"] def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False): return prepare_image_inputs( batch_size=self.batch_size, num_channels=self.num_channels, min_resolution=self.min_resolution, max_resolution=self.max_resolution, equal_resolution=equal_resolution, numpify=numpify, torchify=torchify, ) @require_torch @require_vision class Phi4MultimodalImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase): fast_image_processing_class = Phi4MultimodalImageProcessorFast if is_torchvision_available() else None test_slow_image_processor = False def setUp(self): super().setUp() self.image_processor_tester = Phi4MultimodalImageProcessingTester(self) @property def image_processor_dict(self): return self.image_processor_tester.prepare_image_processor_dict() def test_image_processor_properties(self): for image_processing_class in self.image_processor_list: image_processing = image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(image_processing, "do_resize")) self.assertTrue(hasattr(image_processing, "size")) self.assertTrue(hasattr(image_processing, "do_center_crop")) self.assertTrue(hasattr(image_processing, "center_crop")) self.assertTrue(hasattr(image_processing, "do_normalize")) self.assertTrue(hasattr(image_processing, "image_mean")) self.assertTrue(hasattr(image_processing, "image_std")) self.assertTrue(hasattr(image_processing, "do_convert_rgb")) def test_image_processor_from_dict_with_kwargs(self): for image_processing_class in self.image_processor_list: image_processor = image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size, {"height": 100, "width": 100}) image_processor = image_processing_class.from_dict(self.image_processor_dict, size=42) self.assertEqual(image_processor.size, {"height": 42, "width": 42}) @unittest.skip(reason="Phi4MultimodalImageProcessorFast doesn't treat 4 channel PIL and numpy consistently yet") def test_call_numpy_4_channels(self): pass def test_cast_dtype_device(self): for image_processing_class in self.image_processor_list: if self.test_cast_dtype is not None: # Initialize image_processor image_processor = image_processing_class(**self.image_processor_dict) # create random PyTorch tensors image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True) encoding = image_processor(image_inputs, return_tensors="pt") # for layoutLM compatibility self.assertEqual(encoding.image_pixel_values.device, torch.device("cpu")) self.assertEqual(encoding.image_pixel_values.dtype, torch.float32) encoding = image_processor(image_inputs, return_tensors="pt").to(torch.float16) self.assertEqual(encoding.image_pixel_values.device, torch.device("cpu")) self.assertEqual(encoding.image_pixel_values.dtype, torch.float16) encoding = image_processor(image_inputs, return_tensors="pt").to("cpu", torch.bfloat16) self.assertEqual(encoding.image_pixel_values.device, torch.device("cpu")) self.assertEqual(encoding.image_pixel_values.dtype, torch.bfloat16) with self.assertRaises(TypeError): _ = image_processor(image_inputs, return_tensors="pt").to(torch.bfloat16, "cpu") # Try with text + image feature encoding = image_processor(image_inputs, return_tensors="pt") encoding.update({"input_ids": torch.LongTensor([[1, 2, 3], [4, 5, 6]])}) encoding = encoding.to(torch.float16) self.assertEqual(encoding.image_pixel_values.device, torch.device("cpu")) self.assertEqual(encoding.image_pixel_values.dtype, torch.float16) self.assertEqual(encoding.input_ids.dtype, torch.long) def test_call_pil(self): for image_processing_class in self.image_processor_list: # Initialize image_processing image_processing = image_processing_class(**self.image_processor_dict) # create random PIL images image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False) for image in image_inputs: self.assertIsInstance(image, Image.Image) # Test not batched input encoded_images = image_processing(image_inputs[0], return_tensors="pt").image_pixel_values expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]]) self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape)) # Test batched encoded_images = image_processing(image_inputs, return_tensors="pt").image_pixel_values expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs) self.assertEqual( tuple(encoded_images.shape), (self.image_processor_tester.batch_size, *expected_output_image_shape) ) def test_call_numpy(self): for image_processing_class in self.image_processor_list: # Initialize image_processing image_processing = image_processing_class(**self.image_processor_dict) # create random numpy tensors image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True) for image in image_inputs: self.assertIsInstance(image, np.ndarray) # Test not batched input encoded_images = image_processing(image_inputs[0], return_tensors="pt").image_pixel_values expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]]) self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape)) # Test batched encoded_images = image_processing(image_inputs, return_tensors="pt").image_pixel_values expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs) self.assertEqual( tuple(encoded_images.shape), (self.image_processor_tester.batch_size, *expected_output_image_shape) ) def test_call_pytorch(self): for image_processing_class in self.image_processor_list: # Initialize image_processing image_processing = image_processing_class(**self.image_processor_dict) # create random PyTorch tensors image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True) for image in image_inputs: self.assertIsInstance(image, torch.Tensor) # Test not batched input encoded_images = image_processing(image_inputs[0], return_tensors="pt").image_pixel_values expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]]) self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape)) # Test batched expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs) encoded_images = image_processing(image_inputs, return_tensors="pt").image_pixel_values self.assertEqual( tuple(encoded_images.shape), (self.image_processor_tester.batch_size, *expected_output_image_shape), ) def test_image_processor_preprocess_arguments(self): is_tested = False for image_processing_class in self.image_processor_list: image_processor = image_processing_class(**self.image_processor_dict) # validation done by _valid_processor_keys attribute if hasattr(image_processor, "_valid_processor_keys") and hasattr(image_processor, "preprocess"): preprocess_parameter_names = inspect.getfullargspec(image_processor.preprocess).args preprocess_parameter_names.remove("self") preprocess_parameter_names.sort() valid_processor_keys = image_processor._valid_processor_keys valid_processor_keys.sort() self.assertEqual(preprocess_parameter_names, valid_processor_keys) is_tested = True # validation done by @filter_out_non_signature_kwargs decorator if hasattr(image_processor.preprocess, "_filter_out_non_signature_kwargs"): if hasattr(self.image_processor_tester, "prepare_image_inputs"): inputs = self.image_processor_tester.prepare_image_inputs() elif hasattr(self.image_processor_tester, "prepare_video_inputs"): inputs = self.image_processor_tester.prepare_video_inputs() else: self.skipTest(reason="No valid input preparation method found") with warnings.catch_warnings(record=True) as raised_warnings: warnings.simplefilter("always") image_processor(inputs, extra_argument=True) messages = " ".join([str(w.message) for w in raised_warnings]) self.assertGreaterEqual(len(raised_warnings), 1) self.assertIn("extra_argument", messages) is_tested = True if not is_tested: self.skipTest(reason="No validation found for `preprocess` method") @slow @pytest.mark.torch_compile_test def test_can_compile_fast_image_processor(self): if self.fast_image_processing_class is None: self.skipTest("Skipping compilation test as fast image processor is not defined") if version.parse(torch.__version__) < version.parse("2.3"): self.skipTest(reason="This test requires torch >= 2.3 to run.") torch.compiler.reset() input_image = torch.randint(0, 255, (3, 224, 224), dtype=torch.uint8) image_processor = self.fast_image_processing_class(**self.image_processor_dict) output_eager = image_processor(input_image, device=torch_device, return_tensors="pt") image_processor = torch.compile(image_processor, mode="reduce-overhead") output_compiled = image_processor(input_image, device=torch_device, return_tensors="pt") torch.testing.assert_close( output_eager.image_pixel_values, output_compiled.image_pixel_values, rtol=1e-4, atol=1e-4 )
transformers/tests/models/phi4_multimodal/test_image_processing_phi4_multimodal.py/0
{ "file_path": "transformers/tests/models/phi4_multimodal/test_image_processing_phi4_multimodal.py", "repo_id": "transformers", "token_count": 6194 }
538
# Copyright 2022 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 tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, PLBartTokenizer, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin SAMPLE_VOCAB = get_tests_dir("fixtures/test_sentencepiece.model") if is_torch_available(): from transformers.models.plbart.modeling_plbart import shift_tokens_right EN_CODE = 50003 PYTHON_CODE = 50002 @require_sentencepiece @require_tokenizers class PLBartTokenizationTest(TokenizerTesterMixin, unittest.TestCase): from_pretrained_id = "uclanlp/plbart-base" tokenizer_class = PLBartTokenizer rust_tokenizer_class = None test_rust_tokenizer = False @classmethod def setUpClass(cls): super().setUpClass() # We have a SentencePiece fixture for testing tokenizer = PLBartTokenizer(SAMPLE_VOCAB, language_codes="base", keep_accents=True) tokenizer.save_pretrained(cls.tmpdirname) def test_full_base_tokenizer(self): tokenizer = PLBartTokenizer(SAMPLE_VOCAB, language_codes="base", keep_accents=True) tokens = tokenizer.tokenize("This is a test") self.assertListEqual(tokens, ["▁This", "▁is", "▁a", "▁t", "est"]) self.assertListEqual( tokenizer.convert_tokens_to_ids(tokens), [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]], ) tokens = tokenizer.tokenize("I was born in 92000, and this is falsé.") self.assertListEqual( tokens, [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ], ) ids = tokenizer.convert_tokens_to_ids(tokens) self.assertListEqual( ids, [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ], ) back_tokens = tokenizer.convert_ids_to_tokens(ids) self.assertListEqual( back_tokens, [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ], ) end = tokenizer.vocab_size language_tokens = [tokenizer.convert_ids_to_tokens(x) for x in range(end - 4, end)] self.assertListEqual(language_tokens, ["__java__", "__python__", "__en_XX__", "<mask>"]) code = "java.lang.Exception, python.lang.Exception, javascript, php, ruby, go" input_ids = tokenizer(code).input_ids self.assertEqual( tokenizer.decode(input_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False), code, ) def test_full_multi_tokenizer(self): tokenizer = PLBartTokenizer(SAMPLE_VOCAB, language_codes="multi", keep_accents=True) tokens = tokenizer.tokenize("This is a test") self.assertListEqual(tokens, ["▁This", "▁is", "▁a", "▁t", "est"]) self.assertListEqual( tokenizer.convert_tokens_to_ids(tokens), [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]], ) tokens = tokenizer.tokenize("I was born in 92000, and this is falsé.") self.assertListEqual( tokens, [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ], ) ids = tokenizer.convert_tokens_to_ids(tokens) self.assertListEqual( ids, [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4] ], ) back_tokens = tokenizer.convert_ids_to_tokens(ids) self.assertListEqual( back_tokens, [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ], ) end = tokenizer.vocab_size language_tokens = [tokenizer.convert_ids_to_tokens(x) for x in range(end - 7, end)] self.assertListEqual( language_tokens, ["__java__", "__python__", "__en_XX__", "__javascript__", "__php__", "__ruby__", "__go__"] ) code = "java.lang.Exception, python.lang.Exception, javascript, php, ruby, go" input_ids = tokenizer(code).input_ids self.assertEqual( tokenizer.decode(input_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False), code, ) @require_torch @require_sentencepiece @require_tokenizers class PLBartPythonEnIntegrationTest(unittest.TestCase): checkpoint_name = "uclanlp/plbart-python-en_XX" src_text = [ "def maximum(a,b,c):NEW_LINE_INDENTreturn max([a,b,c])", "def sum(a,b,c):NEW_LINE_INDENTreturn sum([a,b,c])", ] tgt_text = [ "Returns the maximum value of a b c.", "Sums the values of a b c.", ] expected_src_tokens = [ 134, 5452, 33460, 33441, 33463, 33465, 33463, 33449, 988, 20, 33456, 19, 33456, 771, 39, 4258, 889, 3318, 33441, 33463, 33465, 33463, 33449, 2471, 2, PYTHON_CODE, ] @classmethod def setUpClass(cls): cls.tokenizer: PLBartTokenizer = PLBartTokenizer.from_pretrained( cls.checkpoint_name, language_codes="base", src_lang="python", tgt_lang="en_XX" ) cls.pad_token_id = 1 return cls def check_language_codes(self): self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["__java__"], 50001) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["__python__"], 50002) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["__en_XX__"], 50003) def test_python_en_tokenizer_batch_encode_plus(self): ids = self.tokenizer.batch_encode_plus(self.src_text).input_ids[0] self.assertListEqual(self.expected_src_tokens, ids) def test_python_en_tokenizer_decode_ignores_language_codes(self): self.assertIn(PYTHON_CODE, self.tokenizer.all_special_ids) generated_ids = [EN_CODE, 9037, 33442, 57, 752, 153, 14, 56, 18, 9, 2] result = self.tokenizer.decode(generated_ids, skip_special_tokens=True) expected_english = self.tokenizer.decode(generated_ids[1:], skip_special_tokens=True) self.assertEqual(result, expected_english) self.assertNotIn(self.tokenizer.eos_token, result) def test_python_en_tokenizer_truncation(self): src_text = ["def sum(a,b,c):NEW_LINE_INDENTreturn sum([a,b,c])" * 20] self.assertIsInstance(src_text[0], str) desired_max_length = 10 ids = self.tokenizer(src_text, max_length=desired_max_length, truncation=True).input_ids[0] self.assertEqual(ids[-2], 2) self.assertEqual(ids[-1], PYTHON_CODE) self.assertEqual(len(ids), desired_max_length) def test_mask_token(self): self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["<mask>", "__java__"]), [50004, 50001]) def test_special_tokens_unaffacted_by_save_load(self): tmpdirname = tempfile.mkdtemp() original_special_tokens = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(tmpdirname) new_tok = PLBartTokenizer.from_pretrained(tmpdirname) self.assertDictEqual(new_tok.fairseq_tokens_to_ids, original_special_tokens) @require_torch def test_batch_fairseq_parity(self): batch = self.tokenizer(self.src_text, text_target=self.tgt_text, padding=True, return_tensors="pt") batch["decoder_input_ids"] = shift_tokens_right(batch["labels"], self.tokenizer.pad_token_id) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 self.assertEqual(batch.input_ids[1][-2:].tolist(), [2, PYTHON_CODE]) self.assertEqual(batch.decoder_input_ids[1][0], EN_CODE) self.assertEqual(batch.decoder_input_ids[1][-1], 2) self.assertEqual(batch.labels[1][-2:].tolist(), [2, EN_CODE]) @require_torch def test_python_en_tokenizer_prepare_batch(self): batch = self.tokenizer( self.src_text, text_target=self.tgt_text, padding=True, truncation=True, max_length=len(self.expected_src_tokens), return_tensors="pt", ) batch["decoder_input_ids"] = shift_tokens_right(batch["labels"], self.tokenizer.pad_token_id) self.assertIsInstance(batch, BatchEncoding) self.assertEqual((2, 26), batch.input_ids.shape) self.assertEqual((2, 26), batch.attention_mask.shape) result = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens, result) self.assertEqual(2, batch.decoder_input_ids[0, -1]) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens, []) self.assertEqual(self.tokenizer.suffix_tokens, [self.tokenizer.eos_token_id, PYTHON_CODE]) def test_seq2seq_max_length(self): batch = self.tokenizer(self.src_text, padding=True, truncation=True, max_length=3, return_tensors="pt") targets = self.tokenizer( text_target=self.tgt_text, padding=True, truncation=True, max_length=10, return_tensors="pt" ) labels = targets["input_ids"] batch["decoder_input_ids"] = shift_tokens_right(labels, self.tokenizer.pad_token_id) self.assertEqual(batch.input_ids.shape[1], 3) self.assertEqual(batch.decoder_input_ids.shape[1], 10) @require_torch def test_tokenizer_translation(self): inputs = self.tokenizer._build_translation_inputs( "A test", return_tensors="pt", src_lang="en_XX", tgt_lang="java" ) self.assertEqual( nested_simplify(inputs), { # A, test, EOS, en_XX "input_ids": [[150, 242, 2, 50003]], "attention_mask": [[1, 1, 1, 1]], # java "forced_bos_token_id": 50001, }, )
transformers/tests/models/plbart/test_tokenization_plbart.py/0
{ "file_path": "transformers/tests/models/plbart/test_tokenization_plbart.py", "repo_id": "transformers", "token_count": 6908 }
539
# Copyright 2022 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 ( SPIECE_UNDERLINE, AddedToken, BatchEncoding, PreTrainedTokenizerFast, SeamlessM4TTokenizer, SeamlessM4TTokenizerFast, is_torch_available, ) from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, ) from ...test_tokenization_common import TokenizerTesterMixin SAMPLE_VOCAB = get_tests_dir("fixtures/test_sentencepiece.model") if is_torch_available(): from transformers.models.m2m_100.modeling_m2m_100 import shift_tokens_right EN_CODE = 256047 RO_CODE = 256145 SMALL_TRAINING_CORPUS = [ ["This is the first sentence.", "This is the second one."], ["This sentence (contains #) over symbols and numbers 12 3.", "But not this one."], ] @require_sentencepiece @require_tokenizers class SeamlessM4TTokenizationTest(TokenizerTesterMixin, unittest.TestCase): from_pretrained_id = "facebook/hf-seamless-m4t-medium" tokenizer_class = SeamlessM4TTokenizer rust_tokenizer_class = SeamlessM4TTokenizerFast test_rust_tokenizer = True test_sentencepiece = True from_pretrained_kwargs = {} @classmethod def setUpClass(cls): super().setUpClass() # We have a SentencePiece fixture for testing tokenizer = SeamlessM4TTokenizer(SAMPLE_VOCAB, keep_accents=True) tokenizer.save_pretrained(cls.tmpdirname) def test_full_tokenizer(self): tokenizer = SeamlessM4TTokenizer(SAMPLE_VOCAB, keep_accents=True) tokens = tokenizer.tokenize("This is a test") self.assertListEqual(tokens, ["▁This", "▁is", "▁a", "▁t", "est"]) self.assertListEqual( tokenizer.convert_tokens_to_ids(tokens), [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]], ) tokens = tokenizer.tokenize("I was born in 92000, and this is falsé.") self.assertListEqual( tokens, [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ], ) ids = tokenizer.convert_tokens_to_ids(tokens) self.assertListEqual( ids, [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] ], ) back_tokens = tokenizer.convert_ids_to_tokens(ids) self.assertListEqual( back_tokens, [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "<unk>", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "<unk>", ".", ], ) @unittest.skip(reason="This fails currently and is a blocker. No idea why TODO @ylacombe") def test_maximum_encoding_length_single_input(self): tokenizers = self.get_tokenizers(do_lower_case=False, model_max_length=100) for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}"): seq_0, ids = self.get_clean_sequence(tokenizer, max_length=20) sequence = tokenizer.encode(seq_0, add_special_tokens=False) total_length = len(sequence) self.assertGreater( total_length, 4, "Issue with the testing sequence, please update it, it's too short" ) # Test with max model input length model_max_length = tokenizer.model_max_length self.assertEqual(model_max_length, 100) seq_1 = seq_0 * model_max_length sequence1 = tokenizer(seq_1, add_special_tokens=False) total_length1 = len(sequence1["input_ids"]) self.assertGreater( total_length1, model_max_length, "Issue with the testing sequence, please update it, it's too short", ) # Simple padding_strategies = ( [False, True, "longest"] if tokenizer.pad_token and tokenizer.pad_token_id >= 0 else [False] ) for padding_state in padding_strategies: with self.subTest(f"Padding: {padding_state}"): for truncation_state in [True, "longest_first", "only_first"]: with self.subTest(f"Truncation: {truncation_state}"): output = tokenizer(seq_1, padding=padding_state, truncation=truncation_state) self.assertEqual(len(output["input_ids"]), model_max_length) output = tokenizer([seq_1], padding=padding_state, truncation=truncation_state) self.assertEqual(len(output["input_ids"][0]), model_max_length) # Simple with no truncation # Reset warnings tokenizer.deprecation_warnings = {} with self.assertLogs("transformers", level="WARNING") as cm: output = tokenizer(seq_1, padding=padding_state, truncation=False) self.assertNotEqual(len(output["input_ids"]), model_max_length) self.assertEqual(len(cm.records), 1) self.assertTrue( cm.records[0].message.startswith( "Token indices sequence length is longer than the specified maximum sequence length" " for this model" ) ) tokenizer.deprecation_warnings = {} with self.assertLogs("transformers", level="WARNING") as cm: output = tokenizer([seq_1], padding=padding_state, truncation=False) self.assertNotEqual(len(output["input_ids"][0]), model_max_length) self.assertEqual(len(cm.records), 1) self.assertTrue( cm.records[0].message.startswith( "Token indices sequence length is longer than the specified maximum sequence length" " for this model" ) ) # Overflowing tokens stride = 2 # modify padding because it's activated by default in seamlessM4T information = tokenizer( seq_0, max_length=total_length - 2, add_special_tokens=False, stride=stride, truncation="longest_first", return_overflowing_tokens=True, padding=False, # add_prefix_space=False, ) # Overflowing tokens are handled quite differently in slow and fast tokenizers if isinstance(tokenizer, PreTrainedTokenizerFast): truncated_sequence = information["input_ids"][0] overflowing_tokens = information["input_ids"][1] self.assertEqual(len(information["input_ids"]), 2) self.assertEqual(len(truncated_sequence), total_length - 2) self.assertEqual(truncated_sequence, sequence[:-2]) self.assertEqual(len(overflowing_tokens), 2 + stride) self.assertEqual(overflowing_tokens, sequence[-(2 + stride) :]) else: truncated_sequence = information["input_ids"] overflowing_tokens = information["overflowing_tokens"] self.assertEqual(len(truncated_sequence), total_length - 2) self.assertEqual(truncated_sequence, sequence[:-2]) self.assertEqual(len(overflowing_tokens), 2 + stride) self.assertEqual(overflowing_tokens, sequence[-(2 + stride) :]) @unittest.skip(reason="By defaults, uses pad_to_multiple_of which breaks the test") def test_maximum_encoding_length_pair_input(self): pass def test_padding_to_multiple_of(self): tokenizers = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}"): if tokenizer.pad_token is None: self.skipTest(reason="No padding token.") else: empty_tokens = tokenizer("", padding=True, pad_to_multiple_of=8) normal_tokens = tokenizer("This is a sample input", padding=True, pad_to_multiple_of=8) for key, value in empty_tokens.items(): self.assertEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8") for key, value in normal_tokens.items(): self.assertEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8") # default to padding=True so need to precise which padding is called normal_tokens = tokenizer("This", pad_to_multiple_of=8, padding=False) for key, value in normal_tokens.items(): self.assertNotEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8") # Should also work with truncation normal_tokens = tokenizer("This", padding=True, truncation=True, pad_to_multiple_of=8) for key, value in normal_tokens.items(): self.assertEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8") # truncation to something which is not a multiple of pad_to_multiple_of raises an error self.assertRaises( ValueError, tokenizer.__call__, "This", padding=True, truncation=True, max_length=12, pad_to_multiple_of=8, ) @require_torch def test_prepare_seq2seq_batch(self): if not self.test_seq2seq: self.skipTest(reason="test_seq2seq is set to False") tokenizers = self.get_tokenizers() for tokenizer in tokenizers: with self.subTest(f"{tokenizer.__class__.__name__}"): # Longer text that will definitely require truncation. src_text = [ " UN Chief Says There Is No Military Solution in Syria", " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for" " Syria is that 'there is no military solution' to the nearly five-year conflict and more weapons" " will only worsen the violence and misery for millions of people.", ] tgt_text = [ "Şeful ONU declară că nu există o soluţie militară în Siria", "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al" ' Rusiei pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi' " că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", ] try: batch = tokenizer.prepare_seq2seq_batch( src_texts=src_text, tgt_texts=tgt_text, max_length=3, max_target_length=10, return_tensors="pt", src_lang="eng", tgt_lang="ron", pad_to_multiple_of=None, ) except NotImplementedError: self.skipTest(reason="Encountered NotImplementedError when calling prepare_seq2seq_batch") self.assertEqual(batch.input_ids.shape[1], 3) self.assertEqual(batch.labels.shape[1], 10) # TODO: not working for tgt_text # max_target_length will default to max_length if not specified batch = tokenizer.prepare_seq2seq_batch( src_texts=src_text, tgt_texts=tgt_text, max_length=4, return_tensors="pt", pad_to_multiple_of=None, ) self.assertEqual(batch.input_ids.shape[1], 4) self.assertEqual(batch.labels.shape[1], 4) batch_encoder_only = tokenizer.prepare_seq2seq_batch( src_texts=src_text, max_length=4, max_target_length=10, return_tensors="pt", pad_to_multiple_of=None, ) self.assertEqual(batch_encoder_only.input_ids.shape[1], 4) self.assertEqual(batch_encoder_only.attention_mask.shape[1], 4) self.assertNotIn("decoder_input_ids", batch_encoder_only) @unittest.skip(reason="Unfortunately way too slow to build a BPE with SentencePiece.") def test_save_slow_from_fast_and_reload_fast(self): pass # Copied from tests.models.nllb.test_tokenization_nllb.NllbTokenizationTest.test_special_tokens_initialization def test_special_tokens_initialization(self): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): added_tokens = [AddedToken("<special>", lstrip=True)] tokenizer_r = self.get_rust_tokenizer( pretrained_name, additional_special_tokens=added_tokens, **kwargs ) r_output = tokenizer_r.encode("Hey this is a <special> token") special_token_id = tokenizer_r.encode("<special>", add_special_tokens=False)[0] self.assertTrue(special_token_id in r_output) if self.test_slow_tokenizer: tokenizer_cr = self.get_rust_tokenizer( pretrained_name, additional_special_tokens=added_tokens, **kwargs, # , from_slow=True <- unfortunately too slow to convert ) tokenizer_p = self.tokenizer_class.from_pretrained( pretrained_name, additional_special_tokens=added_tokens, **kwargs ) p_output = tokenizer_p.encode("Hey this is a <special> token") cr_output = tokenizer_cr.encode("Hey this is a <special> token") self.assertEqual(p_output, r_output) self.assertEqual(cr_output, r_output) self.assertTrue(special_token_id in p_output) self.assertTrue(special_token_id in cr_output) @unittest.skip( "encode_plus and batch_encode_plus are deprecated and __call__ do some processing, so we expect different results." ) def test_call(self): pass def test_training_new_tokenizer(self): # This feature only exists for fast tokenizers if not self.test_rust_tokenizer: self.skipTest(reason="test_rust_tokenizer is set to False") tokenizer = self.get_rust_tokenizer() new_tokenizer = tokenizer.train_new_from_iterator(SMALL_TRAINING_CORPUS, 100) # Test we can use the new tokenizer with something not seen during training inputs = new_tokenizer(["This is the first sentence", "This sentence is different 🤗."]) self.assertEqual(len(inputs["input_ids"]), 2) decoded_input = new_tokenizer.decode(inputs["input_ids"][0], skip_special_tokens=True) expected_result = "This is the first sentence" if tokenizer.backend_tokenizer.normalizer is not None: expected_result = tokenizer.backend_tokenizer.normalizer.normalize_str(expected_result) self.assertEqual(expected_result, decoded_input) # We check that the parameters of the tokenizer remained the same # Check we have the same number of added_tokens for both pair and non-pair inputs. # make sure it has the same prefix tokens first new_tokenizer.tgt_lang = tokenizer.tgt_lang tokenizer.tgt_lang = tokenizer.tgt_lang self.assertEqual(tokenizer.num_special_tokens_to_add(False), new_tokenizer.num_special_tokens_to_add(False)) self.assertEqual(tokenizer.num_special_tokens_to_add(True), new_tokenizer.num_special_tokens_to_add(True)) # Check we have the correct max_length for both pair and non-pair inputs. self.assertEqual(tokenizer.max_len_single_sentence, new_tokenizer.max_len_single_sentence) self.assertEqual(tokenizer.max_len_sentences_pair, new_tokenizer.max_len_sentences_pair) # Assert the set of special tokens match as we didn't ask to change them self.assertSequenceEqual( tokenizer.all_special_tokens_extended, new_tokenizer.all_special_tokens_extended, ) self.assertDictEqual(tokenizer.special_tokens_map, new_tokenizer.special_tokens_map) @unittest.skip(reason="Fails because of the hack of adding <unk> in _tokenize") def test_pickle_subword_regularization_tokenizer(self): pass @unittest.skip(reason="Fails because of the hack of adding <unk> in _tokenize") def test_subword_regularization_tokenizer(self): pass @require_torch @require_sentencepiece @require_tokenizers class SeamlessM4TDistilledIntegrationTest(unittest.TestCase): checkpoint_name = "facebook/hf-seamless-m4t-medium" src_text = [ " UN Chief Says There Is No Military Solution in Syria", """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.""", ] tgt_text = [ "Şeful ONU declară că nu există o soluţie militară în Siria", "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" ' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor' " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", ] expected_src_tokens = [256047, 16297, 134408, 8165, 248066, 14734, 950, 1135, 105721, 3573, 83, 27352, 108, 49486, 3] # fmt: skip @classmethod def setUpClass(cls): cls.tokenizer: SeamlessM4TTokenizer = SeamlessM4TTokenizer.from_pretrained( cls.checkpoint_name, src_lang="eng", tgt_lang="ron" ) # cls.pad_token_id = 1 return cls def test_language_codes(self): self.assertEqual(self.tokenizer.convert_tokens_to_ids("__ace_Latn__"), 256002) self.assertEqual(self.tokenizer.convert_tokens_to_ids("__shn__"), 256152) self.assertEqual(self.tokenizer.convert_tokens_to_ids("__eng__"), 256047) self.assertEqual(self.tokenizer.convert_tokens_to_ids("__fra__"), 256057) self.assertEqual(self.tokenizer.convert_tokens_to_ids("__quy__"), 256144) def test_tokenizer_tgt_lang(self): ids = self.tokenizer(self.src_text, src_lang="fra").input_ids[0] self.assertListEqual(self.expected_src_tokens[1:], ids[1 : len(self.expected_src_tokens)]) self.assertEqual(256057, ids[0]) rest_ids = ids[len(self.expected_src_tokens) :] self.assertListEqual([0] * len(rest_ids), rest_ids) ids = self.tokenizer(self.src_text, src_lang="__shn__").input_ids[0] self.assertListEqual(self.expected_src_tokens[1:], ids[1 : len(self.expected_src_tokens)]) self.assertEqual(256152, ids[0]) # Copied from tests.models.nllb.test_tokenization_nllb.NllbDistilledIntegrationTest.test_enro_tokenizer_decode_ignores_language_codes def test_enro_tokenizer_decode_ignores_language_codes(self): self.assertIn(RO_CODE, self.tokenizer.all_special_ids) generated_ids = [RO_CODE, 4254, 98068, 112923, 39072, 3909, 713, 102767, 26, 17314, 35642, 14683, 33118, 2022, 66987, 2, 256047] # fmt: skip result = self.tokenizer.decode(generated_ids, skip_special_tokens=True) expected_romanian = self.tokenizer.decode(generated_ids[1:], skip_special_tokens=True) self.assertEqual(result, expected_romanian) self.assertNotIn(self.tokenizer.eos_token, result) def test_enro_tokenizer_truncation(self): src_text = ["this is gunna be a long sentence " * 20] assert isinstance(src_text[0], str) desired_max_length = 10 ids = self.tokenizer(src_text, max_length=desired_max_length, truncation=True).input_ids[0] self.assertEqual(ids[-1], 3) self.assertEqual(ids[0], EN_CODE) self.assertEqual(len(ids), desired_max_length) @require_torch def test_enro_tokenizer_prepare_batch(self): batch = self.tokenizer( self.src_text, text_target=self.tgt_text, padding=True, truncation=True, max_length=len(self.expected_src_tokens), pad_to_multiple_of=None, return_tensors="pt", ) batch["decoder_input_ids"] = shift_tokens_right( batch["labels"], self.tokenizer.pad_token_id, self.tokenizer.convert_tokens_to_ids("__ron__") ) self.assertIsInstance(batch, BatchEncoding) self.assertEqual((2, 15), batch.input_ids.shape) self.assertEqual((2, 15), batch.attention_mask.shape) result = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens, result) self.assertEqual(RO_CODE, batch.decoder_input_ids[0, 0]) # EOS # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens, [EN_CODE]) self.assertEqual(self.tokenizer.suffix_tokens, [self.tokenizer.eos_token_id]) def test_seq2seq_max_length(self): batch = self.tokenizer( self.src_text, padding=True, truncation=True, max_length=3, return_tensors="pt", pad_to_multiple_of=None ) targets = self.tokenizer( text_target=self.tgt_text, padding=True, truncation=True, max_length=10, return_tensors="pt" ) labels = targets["input_ids"] batch["decoder_input_ids"] = shift_tokens_right( labels, self.tokenizer.pad_token_id, decoder_start_token_id=self.tokenizer.convert_tokens_to_ids(self.tokenizer.tgt_lang), ) self.assertEqual(batch.input_ids.shape[1], 3) self.assertEqual(batch.decoder_input_ids.shape[1], 10) @require_torch def test_tokenizer_translation(self): inputs = self.tokenizer._build_translation_inputs( "A test", return_tensors="pt", src_lang="eng", tgt_lang="fra" ) self.assertEqual( nested_simplify(inputs), { # A, test, EOS, en_XX "input_ids": [[256047, 70, 7356, 3]], "attention_mask": [[1, 1, 1, 1]], # ar_AR "forced_bos_token_id": 256057, }, ) @require_sentencepiece @require_tokenizers class CommonSpmIntegrationTests(unittest.TestCase): """ A class that regroups important test to make sure that we properly handle the special tokens. """ @classmethod def setUpClass(cls): tokenizer = SeamlessM4TTokenizer(SAMPLE_VOCAB, extra_ids=0, add_bos_token=False, legacy=False) tokenizer.add_special_tokens({"additional_special_tokens": [AddedToken("<s>", rstrip=False, lstrip=False)]}) cls.tokenizer = tokenizer return cls def test_add_dummy_prefix(self): # make sure `'▁'` is prepended, and outputs match sp_model's # `sentencepiece.NormalizerSpec.add_dummy_prefix` attribute input_ids = self.tokenizer.encode(". Hello") self.assertEqual(input_ids, [3, 1, 8, 5, 157, 87, 21, 3]) sp_encode = self.tokenizer.sp_model.encode(". Hello") # [bos, lang_id, _] + offset_sp_encode self.assertEqual(input_ids[:-1], [3, 1, 8] + [i + self.tokenizer.fairseq_offset for i in sp_encode]) tokens = self.tokenizer.tokenize(". Hello") self.assertEqual(tokens, ["▁", ".", "▁He", "ll", "o"]) tokens = self.tokenizer.tokenize("") self.assertEqual(tokens, []) self.assertEqual(tokens, self.tokenizer.sp_model.encode("", out_type=str)) tokens = self.tokenizer.tokenize(" ") self.assertEqual(tokens, []) self.assertEqual(tokens, self.tokenizer.sp_model.encode(" ", out_type=str)) tokens = self.tokenizer.tokenize("▁") self.assertEqual(tokens, []) self.assertEqual(tokens, self.tokenizer.sp_model.encode("▁", out_type=str)) def test_remove_extra_whitespaces(self): # make sure the extra spaces are eaten. Since the sample vocab does not have # `______`. sentencepiece.NormalizerSpec.remove_extra_whitespaces attribute is set to False input_ids = self.tokenizer.encode(" . Hello") self.assertEqual(input_ids, [3, 1, 8, 5, 157, 87, 21, 3]) sp_encode = self.tokenizer.sp_model.encode(" . Hello") self.assertEqual([i - self.tokenizer.fairseq_offset for i in input_ids[2:-1]], [7] + sp_encode) tokens = self.tokenizer.tokenize(" . Hello") self.assertEqual(tokens, ["▁", ".", "▁He", "ll", "o"]) # `'▁'` is also a whitespace input_ids = self.tokenizer.encode("▁He is not") self.assertEqual(input_ids, [3, 1, 157, 47, 45, 3]) tokens = self.tokenizer.tokenize("▁He is not") sp_encode = [ self.tokenizer.sp_model.piece_to_id("▁He"), self.tokenizer.sp_model.piece_to_id("▁is"), self.tokenizer.sp_model.piece_to_id("▁not"), ] self.assertEqual([i - self.tokenizer.fairseq_offset for i in input_ids[2:-1]], sp_encode) self.assertEqual(tokens, ["▁He", "▁is", "▁not"]) # no extra space added input_ids = self.tokenizer.encode("▁He is not<s> ▁He") self.assertEqual(input_ids, [3, 1, 157, 47, 45, 2, 157, 3]) tokens = self.tokenizer.tokenize("▁He is not<s> ▁He") self.assertEqual(tokens, ["▁He", "▁is", "▁not", "<s>", "▁He"]) # spaces are eaten by spm + our strip # make sure that the output after the extra id is the same as if # extra_id was not there input_ids = self.tokenizer.encode("▁He is not ▁He") self.assertEqual(input_ids, [3, 1, 157, 47, 45, 157, 3]) tokens = self.tokenizer.tokenize("▁He is not ▁He") self.assertEqual(tokens, ["▁He", "▁is", "▁not", "▁He"]) # spaces are eaten by spm even if not start def test_character_after_special_token(self): # Make sure that `tokenizer.tokenize` is similar to # adding the equivalent special token to the vocab input_ids = self.tokenizer.encode("Hey <s>I") self.assertEqual(input_ids, [3, 1, 157, 31, 2, 101, 3]) sp_encode = self.tokenizer.sp_model.encode("Hey .I") # the last token besides eos should be 100 offset self.assertEqual(input_ids[-2] - self.tokenizer.fairseq_offset, sp_encode[-1]) tokens = self.tokenizer.tokenize("<s>I") self.assertEqual(tokens, ["<s>", "I"]) input_ids = self.tokenizer.encode("Hello, <s>,") self.assertEqual(input_ids, [3, 1, 157, 87, 21, 4, 2, 4, 3]) tokens = self.tokenizer.tokenize("Hello, <s>,") self.assertEqual(tokens, ["▁He", "ll", "o", ",", "<s>", ","]) def test_special_tokens_strip(self): input_ids = self.tokenizer.encode(" <s> ,") self.assertEqual(input_ids, [3, 1, 2, 8, 4, 3]) tokens = self.tokenizer.tokenize(" <s> ,") # spaces are eaten by rstrip / lstrip + spm sp_model.encode(" ") = [] self.assertEqual(tokens, ["<s>", "▁", ","]) input_ids = self.tokenizer.encode("No <s> ▁He") self.assertEqual(input_ids, [3, 1, 285, 2, 157, 3]) tokens = self.tokenizer.tokenize("No <s> ▁He") self.assertEqual(tokens, ["▁No", "<s>", "▁He"]) # spaces are eaten by rstrip / lstrip
transformers/tests/models/seamless_m4t/test_tokenization_seamless_m4t.py/0
{ "file_path": "transformers/tests/models/seamless_m4t/test_tokenization_seamless_m4t.py", "repo_id": "transformers", "token_count": 15006 }
540
# Copyright 2025 The HuggingFace Inc. 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. """Testing suite for the PyTorch Gemma3 model.""" import unittest from io import BytesIO import requests from PIL import Image from transformers import is_torch_available from transformers.testing_utils import ( cleanup, require_read_token, require_torch_accelerator, slow, torch_device, ) if is_torch_available(): from transformers import ShieldGemma2ForImageClassification, ShieldGemma2Processor @slow @require_torch_accelerator @require_read_token class ShieldGemma2IntegrationTest(unittest.TestCase): def tearDown(self): cleanup(torch_device, gc_collect=True) def test_model(self): model_id = "google/shieldgemma-2-4b-it" processor = ShieldGemma2Processor.from_pretrained(model_id, padding_side="left") url = "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/cow_beach_1.png" response = requests.get(url) image = Image.open(BytesIO(response.content)) model = ShieldGemma2ForImageClassification.from_pretrained(model_id, load_in_4bit=True) inputs = processor(images=[image], return_tensors="pt").to(torch_device) output = model(**inputs) self.assertEqual(len(output.probabilities), 3) for element in output.probabilities: self.assertEqual(len(element), 2)
transformers/tests/models/shieldgemma2/test_modeling_shieldgemma2.py/0
{ "file_path": "transformers/tests/models/shieldgemma2/test_modeling_shieldgemma2.py", "repo_id": "transformers", "token_count": 678 }
541
# Copyright 2020 The SqueezeBert authors and 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 unittest from transformers import SqueezeBertConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, ) class SqueezeBertModelTester: def __init__( self, parent, batch_size=13, seq_length=7, is_training=True, use_input_mask=True, use_token_type_ids=False, use_labels=True, vocab_size=99, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=64, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size=16, type_sequence_label_size=2, initializer_range=0.02, num_labels=3, num_choices=4, scope=None, q_groups=2, k_groups=2, v_groups=2, post_attention_groups=2, intermediate_groups=4, output_groups=1, ): self.parent = parent self.batch_size = batch_size self.seq_length = seq_length self.is_training = is_training self.use_input_mask = use_input_mask self.use_token_type_ids = use_token_type_ids self.use_labels = use_labels self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.intermediate_size = intermediate_size self.hidden_act = hidden_act self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.max_position_embeddings = max_position_embeddings self.type_vocab_size = type_vocab_size self.type_sequence_label_size = type_sequence_label_size self.initializer_range = initializer_range self.num_labels = num_labels self.num_choices = num_choices self.scope = scope self.q_groups = q_groups self.k_groups = k_groups self.v_groups = v_groups self.post_attention_groups = post_attention_groups self.intermediate_groups = intermediate_groups self.output_groups = output_groups def prepare_config_and_inputs(self): input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) input_mask = None if self.use_input_mask: input_mask = random_attention_mask([self.batch_size, self.seq_length]) sequence_labels = None token_labels = None choice_labels = None if self.use_labels: sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) choice_labels = ids_tensor([self.batch_size], self.num_choices) config = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def get_config(self): return SqueezeBertConfig( embedding_size=self.hidden_size, vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, hidden_act=self.hidden_act, attention_probs_dropout_prob=self.hidden_dropout_prob, attention_dropout=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, initializer_range=self.initializer_range, q_groups=self.q_groups, k_groups=self.k_groups, v_groups=self.v_groups, post_attention_groups=self.post_attention_groups, intermediate_groups=self.intermediate_groups, output_groups=self.output_groups, ) def create_and_check_squeezebert_model( self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels ): model = SqueezeBertModel(config=config) model.to(torch_device) model.eval() result = model(input_ids, input_mask) result = model(input_ids) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) def create_and_check_squeezebert_for_masked_lm( self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels ): model = SqueezeBertForMaskedLM(config=config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, labels=token_labels) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) def create_and_check_squeezebert_for_question_answering( self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels ): model = SqueezeBertForQuestionAnswering(config=config) model.to(torch_device) model.eval() result = model( input_ids, attention_mask=input_mask, start_positions=sequence_labels, end_positions=sequence_labels ) self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length)) self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length)) def create_and_check_squeezebert_for_sequence_classification( self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels ): config.num_labels = self.num_labels model = SqueezeBertForSequenceClassification(config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, labels=sequence_labels) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels)) def create_and_check_squeezebert_for_token_classification( self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels ): config.num_labels = self.num_labels model = SqueezeBertForTokenClassification(config=config) model.to(torch_device) model.eval() result = model(input_ids, attention_mask=input_mask, labels=token_labels) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels)) def create_and_check_squeezebert_for_multiple_choice( self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels ): config.num_choices = self.num_choices model = SqueezeBertForMultipleChoice(config=config) model.to(torch_device) model.eval() multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() result = model( multiple_choice_inputs_ids, attention_mask=multiple_choice_input_mask, labels=choice_labels, ) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices)) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() (config, input_ids, input_mask, sequence_labels, token_labels, choice_labels) = config_and_inputs inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class SqueezeBertModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( ( SqueezeBertModel, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, ) if is_torch_available() else None ) pipeline_model_mapping = ( { "feature-extraction": SqueezeBertModel, "fill-mask": SqueezeBertForMaskedLM, "question-answering": SqueezeBertForQuestionAnswering, "text-classification": SqueezeBertForSequenceClassification, "token-classification": SqueezeBertForTokenClassification, "zero-shot": SqueezeBertForSequenceClassification, } if is_torch_available() else {} ) test_pruning = False test_resize_embeddings = True test_head_masking = False def setUp(self): self.model_tester = SqueezeBertModelTester(self) self.config_tester = ConfigTester(self, config_class=SqueezeBertConfig, dim=37) def test_config(self): self.config_tester.run_common_tests() def test_squeezebert_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_model(*config_and_inputs) def test_for_masked_lm(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_masked_lm(*config_and_inputs) def test_for_question_answering(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_question_answering(*config_and_inputs) def test_for_sequence_classification(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_sequence_classification(*config_and_inputs) def test_for_token_classification(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_token_classification(*config_and_inputs) def test_for_multiple_choice(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_squeezebert_for_multiple_choice(*config_and_inputs) @slow def test_model_from_pretrained(self): model_name = "squeezebert/squeezebert-uncased" model = SqueezeBertModel.from_pretrained(model_name) self.assertIsNotNone(model) @require_sentencepiece @require_tokenizers @require_torch class SqueezeBertModelIntegrationTest(unittest.TestCase): @slow def test_inference_classification_head(self): model = SqueezeBertForSequenceClassification.from_pretrained("squeezebert/squeezebert-mnli") input_ids = torch.tensor([[1, 29414, 232, 328, 740, 1140, 12695, 69, 13, 1588, 2]]) output = model(input_ids)[0] expected_shape = torch.Size((1, 3)) self.assertEqual(output.shape, expected_shape) expected_tensor = torch.tensor([[0.6401, -0.0349, -0.6041]]) torch.testing.assert_close(output, expected_tensor, rtol=1e-4, atol=1e-4)
transformers/tests/models/squeezebert/test_modeling_squeezebert.py/0
{ "file_path": "transformers/tests/models/squeezebert/test_modeling_squeezebert.py", "repo_id": "transformers", "token_count": 5265 }
542
# Copyright 2021 The HuggingFace Inc. 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. """Testing suite for the PyTorch TrOCR model.""" import unittest from transformers import TrOCRConfig from transformers.testing_utils import is_torch_available, require_torch, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers.models.trocr.modeling_trocr import TrOCRDecoder, TrOCRForCausalLM @require_torch class TrOCRStandaloneDecoderModelTester: def __init__( self, parent, vocab_size=99, batch_size=13, d_model=16, decoder_seq_length=7, is_training=True, is_decoder=True, use_attention_mask=True, use_cache=False, use_labels=True, decoder_start_token_id=2, decoder_ffn_dim=32, decoder_layers=2, decoder_attention_heads=4, max_position_embeddings=30, pad_token_id=0, bos_token_id=1, eos_token_id=2, scope=None, ): self.parent = parent self.batch_size = batch_size self.decoder_seq_length = decoder_seq_length # For common tests self.seq_length = self.decoder_seq_length self.is_training = is_training self.use_attention_mask = use_attention_mask self.use_labels = use_labels self.vocab_size = vocab_size self.d_model = d_model self.hidden_size = d_model self.num_hidden_layers = decoder_layers self.decoder_layers = decoder_layers self.decoder_ffn_dim = decoder_ffn_dim self.decoder_attention_heads = decoder_attention_heads self.num_attention_heads = decoder_attention_heads self.eos_token_id = eos_token_id self.bos_token_id = bos_token_id self.pad_token_id = pad_token_id self.decoder_start_token_id = decoder_start_token_id self.use_cache = use_cache self.max_position_embeddings = max_position_embeddings self.scope = None self.decoder_key_length = decoder_seq_length self.base_model_out_len = 2 self.decoder_attention_idx = 1 def prepare_config_and_inputs(self): input_ids = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size) attention_mask = None if self.use_attention_mask: attention_mask = ids_tensor([self.batch_size, self.decoder_seq_length], vocab_size=2) lm_labels = None if self.use_labels: lm_labels = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size) config = TrOCRConfig( vocab_size=self.vocab_size, d_model=self.d_model, decoder_layers=self.decoder_layers, decoder_ffn_dim=self.decoder_ffn_dim, decoder_attention_heads=self.decoder_attention_heads, eos_token_id=self.eos_token_id, bos_token_id=self.bos_token_id, use_cache=self.use_cache, pad_token_id=self.pad_token_id, decoder_start_token_id=self.decoder_start_token_id, max_position_embeddings=self.max_position_embeddings, ) return (config, input_ids, attention_mask, lm_labels) def create_and_check_decoder_model_past( self, config, input_ids, attention_mask, lm_labels, ): config.use_cache = True model = TrOCRDecoder(config=config).to(torch_device).eval() input_ids = input_ids[:2] input_ids[input_ids == 0] += 1 # first forward pass outputs = model(input_ids, use_cache=True) outputs_use_cache_conf = model(input_ids) outputs_no_past = model(input_ids, use_cache=False) self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf)) self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1) past_key_values = outputs["past_key_values"] # create hypothetical next token and extent to next_input_ids next_tokens = ids_tensor((2, 1), config.vocab_size - 1) + 1 # append to next input_ids and next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) output_from_no_past = model(next_input_ids)["last_hidden_state"] output_from_past = model(next_tokens, past_key_values=past_key_values)["last_hidden_state"] # select random slice random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item() output_from_no_past_slice = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach() output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach() # test that outputs are equal for slice assert torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, input_ids, attention_mask, lm_labels = config_and_inputs inputs_dict = {"input_ids": input_ids, "attention_mask": attention_mask} return config, inputs_dict @require_torch class TrOCRStandaloneDecoderModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (TrOCRDecoder, TrOCRForCausalLM) if is_torch_available() else () pipeline_model_mapping = {"text-generation": TrOCRForCausalLM} if is_torch_available() else {} fx_compatible = True test_pruning = False def setUp(self): self.model_tester = TrOCRStandaloneDecoderModelTester(self, is_training=False) self.config_tester = ConfigTester(self, config_class=TrOCRConfig) @unittest.skip(reason="Not yet implemented") def test_inputs_embeds(self): pass def test_config(self): self.config_tester.run_common_tests() def test_decoder_model_past(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past(*config_and_inputs) @unittest.skip(reason="Decoder cannot keep gradients") def test_retain_grad_hidden_states_attentions(self): return @unittest.skip(reason="The model doesn't support left padding") # and it's not used enough to be worth fixing :) def test_left_padding_compatibility(self): pass
transformers/tests/models/trocr/test_modeling_trocr.py/0
{ "file_path": "transformers/tests/models/trocr/test_modeling_trocr.py", "repo_id": "transformers", "token_count": 3043 }
543
# 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 itertools import os import random import tempfile import unittest import numpy as np from datasets import Audio, load_dataset from transformers import UnivNetFeatureExtractor from transformers.testing_utils import check_json_file_has_correct_format, require_torch, slow from transformers.utils.import_utils import is_torch_available from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_torch_available(): import torch global_rng = random.Random() # Copied from tests.models.whisper.test_feature_extraction_whisper.floats_list def floats_list(shape, scale=1.0, rng=None, name=None): """Creates a random float32 tensor""" if rng is None: rng = global_rng values = [] for batch_idx in range(shape[0]): values.append([]) for _ in range(shape[1]): values[-1].append(rng.random() * scale) return values class UnivNetFeatureExtractionTester: def __init__( self, parent, batch_size=7, min_seq_length=400, max_seq_length=2000, feature_size=1, sampling_rate=24000, padding_value=0.0, do_normalize=True, num_mel_bins=100, hop_length=256, win_length=1024, win_function="hann_window", filter_length=1024, max_length_s=10, fmin=0.0, fmax=12000, mel_floor=1e-9, center=False, compression_factor=1.0, compression_clip_val=1e-5, normalize_min=-11.512925148010254, normalize_max=2.3143386840820312, model_in_channels=64, pad_end_length=10, ): self.parent = parent self.batch_size = batch_size self.min_seq_length = min_seq_length self.max_seq_length = max_seq_length self.seq_length_diff = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) self.feature_size = feature_size self.sampling_rate = sampling_rate self.padding_value = padding_value self.do_normalize = do_normalize self.num_mel_bins = num_mel_bins self.hop_length = hop_length self.win_length = win_length self.win_function = win_function self.filter_length = filter_length self.max_length_s = max_length_s self.fmin = fmin self.fmax = fmax self.mel_floor = mel_floor self.center = center self.compression_factor = compression_factor self.compression_clip_val = compression_clip_val self.normalize_min = normalize_min self.normalize_max = normalize_max self.model_in_channels = model_in_channels self.pad_end_length = pad_end_length def prepare_feat_extract_dict(self): return { "feature_size": self.feature_size, "sampling_rate": self.sampling_rate, "padding_value": self.padding_value, "do_normalize": self.do_normalize, "num_mel_bins": self.num_mel_bins, "hop_length": self.hop_length, "win_length": self.win_length, "win_function": self.win_function, "filter_length": self.filter_length, "max_length_s": self.max_length_s, "fmin": self.fmin, "fmax": self.fmax, "mel_floor": self.mel_floor, "center": self.center, "compression_factor": self.compression_factor, "compression_clip_val": self.compression_clip_val, "normalize_min": self.normalize_min, "normalize_max": self.normalize_max, "model_in_channels": self.model_in_channels, "pad_end_length": self.pad_end_length, } def prepare_inputs_for_common(self, equal_length=False, numpify=False): def _flatten(list_of_lists): return list(itertools.chain(*list_of_lists)) if equal_length: speech_inputs = floats_list((self.batch_size, self.max_seq_length)) else: # make sure that inputs increase in size speech_inputs = [ _flatten(floats_list((x, self.feature_size))) for x in range(self.min_seq_length, self.max_seq_length, self.seq_length_diff) ] if numpify: speech_inputs = [np.asarray(x) for x in speech_inputs] return speech_inputs class UnivNetFeatureExtractionTest(SequenceFeatureExtractionTestMixin, unittest.TestCase): feature_extraction_class = UnivNetFeatureExtractor def setUp(self): self.feat_extract_tester = UnivNetFeatureExtractionTester(self) # Copied from tests.models.whisper.test_feature_extraction_whisper.WhisperFeatureExtractionTest.test_feat_extract_from_and_save_pretrained def test_feat_extract_from_and_save_pretrained(self): feat_extract_first = self.feature_extraction_class(**self.feat_extract_dict) with tempfile.TemporaryDirectory() as tmpdirname: saved_file = feat_extract_first.save_pretrained(tmpdirname)[0] check_json_file_has_correct_format(saved_file) feat_extract_second = self.feature_extraction_class.from_pretrained(tmpdirname) dict_first = feat_extract_first.to_dict() dict_second = feat_extract_second.to_dict() mel_1 = feat_extract_first.mel_filters mel_2 = feat_extract_second.mel_filters self.assertTrue(np.allclose(mel_1, mel_2)) self.assertEqual(dict_first, dict_second) # Copied from tests.models.whisper.test_feature_extraction_whisper.WhisperFeatureExtractionTest.test_feat_extract_to_json_file def test_feat_extract_to_json_file(self): feat_extract_first = self.feature_extraction_class(**self.feat_extract_dict) with tempfile.TemporaryDirectory() as tmpdirname: json_file_path = os.path.join(tmpdirname, "feat_extract.json") feat_extract_first.to_json_file(json_file_path) feat_extract_second = self.feature_extraction_class.from_json_file(json_file_path) dict_first = feat_extract_first.to_dict() dict_second = feat_extract_second.to_dict() mel_1 = feat_extract_first.mel_filters mel_2 = feat_extract_second.mel_filters self.assertTrue(np.allclose(mel_1, mel_2)) self.assertEqual(dict_first, dict_second) def test_call(self): # Tests that all call wrap to encode_plus and batch_encode_plus feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) # create three inputs of length 800, 1000, and 1200 speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] np_speech_inputs = [np.asarray(speech_input) for speech_input in speech_inputs] # Test feature size input_features = feature_extractor( np_speech_inputs, padding="max_length", max_length=1600, return_tensors="np" ).input_features self.assertTrue(input_features.ndim == 3) # Note: for some reason I get a weird padding error when feature_size > 1 # self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size) # Note: we use the shape convention (batch_size, seq_len, num_mel_bins) self.assertTrue(input_features.shape[-1] == feature_extractor.num_mel_bins) # Test not batched input encoded_sequences_1 = feature_extractor(speech_inputs[0], return_tensors="np").input_features encoded_sequences_2 = feature_extractor(np_speech_inputs[0], return_tensors="np").input_features self.assertTrue(np.allclose(encoded_sequences_1, encoded_sequences_2, atol=1e-3)) # Test batched encoded_sequences_1 = feature_extractor(speech_inputs, return_tensors="np").input_features encoded_sequences_2 = feature_extractor(np_speech_inputs, return_tensors="np").input_features for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2): self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3)) # Test 2-D numpy arrays are batched. speech_inputs = [floats_list((1, x))[0] for x in (800, 800, 800)] np_speech_inputs = np.asarray(speech_inputs) encoded_sequences_1 = feature_extractor(speech_inputs, return_tensors="np").input_features encoded_sequences_2 = feature_extractor(np_speech_inputs, return_tensors="np").input_features for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2): self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3)) # Test truncation required speech_inputs = [ floats_list((1, x))[0] for x in range((feature_extractor.num_max_samples - 100), (feature_extractor.num_max_samples + 500), 200) ] np_speech_inputs = [np.asarray(speech_input) for speech_input in speech_inputs] speech_inputs_truncated = [x[: feature_extractor.num_max_samples] for x in speech_inputs] np_speech_inputs_truncated = [np.asarray(speech_input) for speech_input in speech_inputs_truncated] encoded_sequences_1 = feature_extractor(np_speech_inputs, return_tensors="np").input_features encoded_sequences_2 = feature_extractor(np_speech_inputs_truncated, return_tensors="np").input_features for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2): self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3)) def test_batched_unbatched_consistency(self): feature_extractor = self.feature_extraction_class(**self.feat_extract_dict) speech_inputs = floats_list((1, 800))[0] np_speech_inputs = np.asarray(speech_inputs) # Test unbatched vs batched list encoded_sequences_1 = feature_extractor(speech_inputs, return_tensors="np").input_features encoded_sequences_2 = feature_extractor([speech_inputs], return_tensors="np").input_features for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2): self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3)) # Test np.ndarray vs list[np.ndarray] encoded_sequences_1 = feature_extractor(np_speech_inputs, return_tensors="np").input_features encoded_sequences_2 = feature_extractor([np_speech_inputs], return_tensors="np").input_features for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2): self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3)) # Test unbatched np.ndarray vs batched np.ndarray encoded_sequences_1 = feature_extractor(np_speech_inputs, return_tensors="np").input_features encoded_sequences_2 = feature_extractor( np.expand_dims(np_speech_inputs, axis=0), return_tensors="np" ).input_features for enc_seq_1, enc_seq_2 in zip(encoded_sequences_1, encoded_sequences_2): self.assertTrue(np.allclose(enc_seq_1, enc_seq_2, atol=1e-3)) def test_generate_noise(self): feature_extractor = self.feature_extraction_class(**self.feat_extract_dict) speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] features = feature_extractor(speech_inputs, return_noise=True) input_features = features.input_features noise_features = features.noise_sequence for spectrogram, noise in zip(input_features, noise_features): self.assertEqual(spectrogram.shape[0], noise.shape[0]) def test_pad_end(self): feature_extractor = self.feature_extraction_class(**self.feat_extract_dict) speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] input_features1 = feature_extractor(speech_inputs, padding=False, pad_end=False).input_features input_features2 = feature_extractor(speech_inputs, padding=False, pad_end=True).input_features for spectrogram1, spectrogram2 in zip(input_features1, input_features2): self.assertEqual(spectrogram1.shape[0] + self.feat_extract_tester.pad_end_length, spectrogram2.shape[0]) def test_generate_noise_and_pad_end(self): feature_extractor = self.feature_extraction_class(**self.feat_extract_dict) speech_inputs = [floats_list((1, x))[0] for x in range(800, 1400, 200)] features = feature_extractor(speech_inputs, padding=False, return_noise=True, pad_end=True) input_features = features.input_features noise_features = features.noise_sequence for spectrogram, noise in zip(input_features, noise_features): self.assertEqual(spectrogram.shape[0], noise.shape[0]) @require_torch def test_batch_decode(self): import torch feature_extractor = self.feature_extraction_class(**self.feat_extract_dict) input_lengths = list(range(800, 1400, 200)) pad_samples = feature_extractor.pad_end_length * feature_extractor.hop_length output_features = { "waveforms": torch.tensor(floats_list((3, max(input_lengths) + pad_samples))), "waveform_lengths": torch.tensor(input_lengths), } waveforms = feature_extractor.batch_decode(**output_features) for input_length, waveform in zip(input_lengths, waveforms): self.assertTrue(len(waveform.shape) == 1, msg="Individual output waveforms should be 1D") self.assertEqual(waveform.shape[0], input_length) @require_torch # Copied from tests.models.whisper.test_feature_extraction_whisper.WhisperFeatureExtractionTest.test_double_precision_pad def test_double_precision_pad(self): import torch feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()) np_speech_inputs = np.random.rand(100, 32).astype(np.float64) py_speech_inputs = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: np_processed = feature_extractor.pad([{"input_features": inputs}], return_tensors="np") self.assertTrue(np_processed.input_features.dtype == np.float32) pt_processed = feature_extractor.pad([{"input_features": inputs}], return_tensors="pt") self.assertTrue(pt_processed.input_features.dtype == torch.float32) def _load_datasamples(self, num_samples): ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") ds = ds.cast_column("audio", Audio(sampling_rate=self.feat_extract_tester.sampling_rate)) # automatic decoding with librispeech speech_samples = ds.sort("id")[:num_samples]["audio"] return [x["array"] for x in speech_samples], [x["sampling_rate"] for x in speech_samples] @slow @require_torch def test_integration(self): # fmt: off EXPECTED_INPUT_FEATURES = torch.tensor( [ -5.0229, -6.1358, -5.8346, -5.4447, -5.6707, -5.8577, -5.0464, -5.0058, -5.6015, -5.6410, -5.4325, -5.6116, -5.3700, -5.7956, -5.3196, -5.3274, -5.9655, -5.6057, -5.8382, -5.9602, -5.9005, -5.9123, -5.7669, -6.1441, -5.5168, -5.1405, -5.3927, -6.0032, -5.5784, -5.3728 ], ) # fmt: on input_speech, sr = self._load_datasamples(1) feature_extractor = UnivNetFeatureExtractor() input_features = feature_extractor(input_speech, sampling_rate=sr[0], return_tensors="pt").input_features self.assertEqual(input_features.shape, (1, 548, 100)) input_features_mean = torch.mean(input_features) input_features_stddev = torch.std(input_features) EXPECTED_MEAN = torch.tensor(-6.18862009) EXPECTED_STDDEV = torch.tensor(2.80845642) torch.testing.assert_close(input_features_mean, EXPECTED_MEAN, rtol=5e-5, atol=5e-5) torch.testing.assert_close(input_features_stddev, EXPECTED_STDDEV) torch.testing.assert_close(input_features[0, :30, 0], EXPECTED_INPUT_FEATURES, rtol=1e-4, atol=1e-4)
transformers/tests/models/univnet/test_feature_extraction_univnet.py/0
{ "file_path": "transformers/tests/models/univnet/test_feature_extraction_univnet.py", "repo_id": "transformers", "token_count": 7230 }
544
# Copyright 2023 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 time import unittest import warnings import numpy as np import pytest import requests from packaging import version from transformers.testing_utils import ( is_flaky, require_torch, require_torch_accelerator, require_vision, slow, torch_device, ) from transformers.utils import is_torch_available, is_torchvision_available, is_vision_available from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import VitMatteImageProcessor if is_torchvision_available(): from transformers import VitMatteImageProcessorFast class VitMatteImageProcessingTester: def __init__( self, parent, batch_size=7, num_channels=3, image_size=18, min_resolution=30, max_resolution=400, do_rescale=True, rescale_factor=0.5, do_pad=True, size_divisibility=10, do_normalize=True, image_mean=[0.5, 0.5, 0.5], image_std=[0.5, 0.5, 0.5], ): self.parent = parent self.batch_size = batch_size self.num_channels = num_channels self.image_size = image_size self.min_resolution = min_resolution self.max_resolution = max_resolution self.do_rescale = do_rescale self.rescale_factor = rescale_factor self.do_pad = do_pad self.size_divisibility = size_divisibility self.do_normalize = do_normalize self.image_mean = image_mean self.image_std = image_std def prepare_image_processor_dict(self): return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, "size_divisibility": self.size_divisibility, } def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False): return prepare_image_inputs( batch_size=self.batch_size, num_channels=self.num_channels, min_resolution=self.min_resolution, max_resolution=self.max_resolution, equal_resolution=equal_resolution, numpify=numpify, torchify=torchify, ) @require_torch @require_vision class VitMatteImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase): image_processing_class = VitMatteImageProcessor if is_vision_available() else None fast_image_processing_class = VitMatteImageProcessorFast if is_torchvision_available() else None def setUp(self): super().setUp() self.image_processor_tester = VitMatteImageProcessingTester(self) @property def image_processor_dict(self): return self.image_processor_tester.prepare_image_processor_dict() def test_image_processor_properties(self): for image_processing_class in self.image_processor_list: image_processing = image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(image_processing, "image_mean")) self.assertTrue(hasattr(image_processing, "image_std")) self.assertTrue(hasattr(image_processing, "do_normalize")) self.assertTrue(hasattr(image_processing, "do_rescale")) self.assertTrue(hasattr(image_processing, "rescale_factor")) self.assertTrue(hasattr(image_processing, "do_pad")) self.assertTrue(hasattr(image_processing, "size_divisibility")) def test_call_numpy(self): # create random numpy tensors image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True) for image in image_inputs: self.assertIsInstance(image, np.ndarray) # Test not batched input (image processor does not support batched inputs) image = image_inputs[0] trimap = np.random.randint(0, 3, size=image.shape[:2]) for image_processing_class in self.image_processor_list: image_processing = image_processing_class(**self.image_processor_dict) encoded_images = image_processing(images=image, trimaps=trimap, return_tensors="pt").pixel_values # Verify that width and height can be divided by size_divisibility and that correct dimensions got merged self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisibility == 0) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisibility == 0) self.assertTrue(encoded_images.shape[-3] == 4) def test_call_pytorch(self): # create random PyTorch tensors image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True) for image in image_inputs: self.assertIsInstance(image, torch.Tensor) # Test not batched input (image processor does not support batched inputs) image = image_inputs[0] trimap = np.random.randint(0, 3, size=image.shape[1:]) for image_processing_class in self.image_processor_list: image_processing = image_processing_class(**self.image_processor_dict) encoded_images = image_processing(images=image, trimaps=trimap, return_tensors="pt").pixel_values # Verify that width and height can be divided by size_divisibility and that correct dimensions got merged self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisibility == 0) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisibility == 0) self.assertTrue(encoded_images.shape[-3] == 4) # create batched tensors image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=True, torchify=True) image_input = torch.stack(image_inputs, dim=0) self.assertIsInstance(image_input, torch.Tensor) self.assertTrue(image_input.shape[1] == 3) trimap_shape = [image_input.shape[0]] + [1] + list(image_input.shape)[2:] trimap_input = torch.randint(0, 3, trimap_shape, dtype=torch.uint8) self.assertIsInstance(trimap_input, torch.Tensor) self.assertTrue(trimap_input.shape[1] == 1) for image_processing_class in self.image_processor_list: image_processing = image_processing_class(**self.image_processor_dict) encoded_images = image_processing(images=image, trimaps=trimap, return_tensors="pt").pixel_values # Verify that width and height can be divided by size_divisibility and that correct dimensions got merged self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisibility == 0) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisibility == 0) self.assertTrue(encoded_images.shape[-3] == 4) def test_call_pil(self): # create random PIL images image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False) for image in image_inputs: self.assertIsInstance(image, Image.Image) # Test not batched input (image processor does not support batched inputs) image = image_inputs[0] trimap = np.random.randint(0, 3, size=image.size[::-1]) for image_processing_class in self.image_processor_list: image_processing = image_processing_class(**self.image_processor_dict) encoded_images = image_processing(images=image, trimaps=trimap, return_tensors="pt").pixel_values # Verify that width and height can be divided by size_divisibility and that correct dimensions got merged self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisibility == 0) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisibility == 0) self.assertTrue(encoded_images.shape[-3] == 4) def test_call_numpy_4_channels(self): # Test that can process images which have an arbitrary number of channels # create random numpy tensors self.image_processor_tester.num_channels = 4 image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True) # Test not batched input (image processor does not support batched inputs) image = image_inputs[0] trimap = np.random.randint(0, 3, size=image.shape[:2]) for image_processing_class in self.image_processor_list: image_processor = image_processing_class(**self.image_processor_dict) encoded_images = image_processor( images=image, trimaps=trimap, input_data_format="channels_last", image_mean=0, image_std=1, return_tensors="pt", ).pixel_values # Verify that width and height can be divided by size_divisibility and that correct dimensions got merged self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisibility == 0) self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisibility == 0) self.assertTrue(encoded_images.shape[-3] == 5) def test_padding_slow(self): image_processing = self.image_processing_class(**self.image_processor_dict) image = np.random.randn(3, 249, 491) images = image_processing.pad_image(image) assert images.shape == (3, 256, 512) image = np.random.randn(3, 249, 512) images = image_processing.pad_image(image) assert images.shape == (3, 256, 512) def test_padding_fast(self): # extra test because name is different for fast image processor image_processing = self.fast_image_processing_class(**self.image_processor_dict) image = torch.rand(3, 249, 491) images = image_processing._pad_image(image) assert images.shape == (3, 256, 512) image = torch.rand(3, 249, 512) images = image_processing._pad_image(image) assert images.shape == (3, 256, 512) def test_image_processor_preprocess_arguments(self): # vitmatte require additional trimap input for image_processor # that is why we override original common test for image_processing_class in self.image_processor_list: image_processor = image_processing_class(**self.image_processor_dict) image = self.image_processor_tester.prepare_image_inputs()[0] trimap = np.random.randint(0, 3, size=image.size[::-1]) with warnings.catch_warnings(record=True) as raised_warnings: warnings.simplefilter("always") image_processor(image, trimaps=trimap, extra_argument=True) messages = " ".join([str(w.message) for w in raised_warnings]) self.assertGreaterEqual(len(raised_warnings), 1) self.assertIn("extra_argument", messages) @is_flaky() def test_fast_is_faster_than_slow(self): if not self.test_slow_image_processor or not self.test_fast_image_processor: self.skipTest(reason="Skipping speed test") if self.image_processing_class is None or self.fast_image_processing_class is None: self.skipTest(reason="Skipping speed test as one of the image processors is not defined") def measure_time(image_processor, images, trimaps): # Warmup for _ in range(5): _ = image_processor(images, trimaps=trimaps, return_tensors="pt") all_times = [] for _ in range(10): start = time.time() _ = image_processor(images, trimaps=trimaps, return_tensors="pt") all_times.append(time.time() - start) # Take the average of the fastest 3 runs avg_time = sum(sorted(all_times[:3])) / 3.0 return avg_time dummy_images = torch.randint(0, 255, (4, 3, 400, 800), dtype=torch.uint8) dummy_trimaps = torch.randint(0, 3, (4, 400, 800), dtype=torch.uint8) image_processor_slow = self.image_processing_class(**self.image_processor_dict) image_processor_fast = self.fast_image_processing_class(**self.image_processor_dict) fast_time = measure_time(image_processor_fast, dummy_images, dummy_trimaps) slow_time = measure_time(image_processor_slow, dummy_images, dummy_trimaps) self.assertLessEqual(fast_time, slow_time) def test_slow_fast_equivalence(self): if not self.test_slow_image_processor or not self.test_fast_image_processor: self.skipTest(reason="Skipping slow/fast equivalence test") if self.image_processing_class is None or self.fast_image_processing_class is None: self.skipTest(reason="Skipping slow/fast equivalence test as one of the image processors is not defined") dummy_image = Image.open( requests.get("http://images.cocodataset.org/val2017/000000039769.jpg", stream=True).raw ) dummy_trimap = np.random.randint(0, 3, size=dummy_image.size[::-1]) image_processor_slow = self.image_processing_class(**self.image_processor_dict) image_processor_fast = self.fast_image_processing_class(**self.image_processor_dict) encoding_slow = image_processor_slow(dummy_image, trimaps=dummy_trimap, return_tensors="pt") encoding_fast = image_processor_fast(dummy_image, trimaps=dummy_trimap, return_tensors="pt") self._assert_slow_fast_tensors_equivalence(encoding_slow.pixel_values, encoding_fast.pixel_values) def test_slow_fast_equivalence_batched(self): # this only checks on equal resolution, since the slow processor doesn't work otherwise if not self.test_slow_image_processor or not self.test_fast_image_processor: self.skipTest(reason="Skipping slow/fast equivalence test") if self.image_processing_class is None or self.fast_image_processing_class is None: self.skipTest(reason="Skipping slow/fast equivalence test as one of the image processors is not defined") if hasattr(self.image_processor_tester, "do_center_crop") and self.image_processor_tester.do_center_crop: self.skipTest( reason="Skipping as do_center_crop is True and center_crop functions are not equivalent for fast and slow processors" ) dummy_images = self.image_processor_tester.prepare_image_inputs(equal_resolution=True, torchify=True) dummy_trimaps = [np.random.randint(0, 3, size=image.shape[1:]) for image in dummy_images] image_processor_slow = self.image_processing_class(**self.image_processor_dict) image_processor_fast = self.fast_image_processing_class(**self.image_processor_dict) encoding_slow = image_processor_slow(dummy_images, trimaps=dummy_trimaps, return_tensors="pt") encoding_fast = image_processor_fast(dummy_images, trimaps=dummy_trimaps, return_tensors="pt") self._assert_slow_fast_tensors_equivalence(encoding_slow.pixel_values, encoding_fast.pixel_values) @slow @require_torch_accelerator @require_vision @pytest.mark.torch_compile_test def test_can_compile_fast_image_processor(self): # override as trimaps are needed for the image processor if self.fast_image_processing_class is None: self.skipTest("Skipping compilation test as fast image processor is not defined") if version.parse(torch.__version__) < version.parse("2.3"): self.skipTest(reason="This test requires torch >= 2.3 to run.") torch.compiler.reset() input_image = torch.randint(0, 255, (3, 224, 224), dtype=torch.uint8) dummy_trimap = np.random.randint(0, 3, size=input_image.shape[1:]) image_processor = self.fast_image_processing_class(**self.image_processor_dict) output_eager = image_processor(input_image, dummy_trimap, device=torch_device, return_tensors="pt") image_processor = torch.compile(image_processor, mode="reduce-overhead") output_compiled = image_processor(input_image, dummy_trimap, device=torch_device, return_tensors="pt") torch.testing.assert_close(output_eager.pixel_values, output_compiled.pixel_values, rtol=1e-4, atol=1e-4)
transformers/tests/models/vitmatte/test_image_processing_vitmatte.py/0
{ "file_path": "transformers/tests/models/vitmatte/test_image_processing_vitmatte.py", "repo_id": "transformers", "token_count": 6945 }
545
# Copyright 2021 The HuggingFace Inc. 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. """Testing suite for the PyTorch WavLM model.""" import math import unittest import pytest from datasets import load_dataset from transformers import WavLMConfig, is_torch_available from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ( ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor, random_attention_mask, ) from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( Wav2Vec2FeatureExtractor, WavLMForAudioFrameClassification, WavLMForCTC, WavLMForSequenceClassification, WavLMForXVector, WavLMModel, ) class WavLMModelTester: def __init__( self, parent, batch_size=13, seq_length=1024, # speech is longer is_training=False, hidden_size=16, feat_extract_norm="group", feat_extract_dropout=0.0, feat_extract_activation="gelu", conv_dim=(32, 32, 32), conv_stride=(4, 4, 4), conv_kernel=(8, 8, 8), conv_bias=False, num_conv_pos_embeddings=16, num_conv_pos_embedding_groups=2, num_hidden_layers=2, num_attention_heads=2, hidden_dropout_prob=0.1, # this is most likely not correctly set yet intermediate_size=20, layer_norm_eps=1e-5, hidden_act="gelu", initializer_range=0.02, vocab_size=32, do_stable_layer_norm=False, tdnn_dim=(32, 32), tdnn_kernel=(3, 3), tdnn_dilation=(1, 1), xvector_output_dim=32, scope=None, ): self.parent = parent self.batch_size = batch_size self.seq_length = seq_length self.is_training = is_training self.hidden_size = hidden_size self.feat_extract_norm = feat_extract_norm self.feat_extract_dropout = feat_extract_dropout self.feat_extract_activation = feat_extract_activation self.conv_dim = conv_dim self.conv_stride = conv_stride self.conv_kernel = conv_kernel self.conv_bias = conv_bias self.num_conv_pos_embeddings = num_conv_pos_embeddings self.num_conv_pos_embedding_groups = num_conv_pos_embedding_groups self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.hidden_dropout_prob = hidden_dropout_prob self.intermediate_size = intermediate_size self.layer_norm_eps = layer_norm_eps self.hidden_act = hidden_act self.initializer_range = initializer_range self.vocab_size = vocab_size self.do_stable_layer_norm = do_stable_layer_norm self.tdnn_dim = tdnn_dim self.tdnn_kernel = tdnn_kernel self.tdnn_dilation = tdnn_dilation self.xvector_output_dim = xvector_output_dim self.scope = scope output_seq_length = self.seq_length for kernel, stride in zip(self.conv_kernel, self.conv_stride): output_seq_length = (output_seq_length - (kernel - 1)) / stride self.output_seq_length = int(math.ceil(output_seq_length)) self.encoder_seq_length = self.output_seq_length def prepare_config_and_inputs(self): input_values = floats_tensor([self.batch_size, self.seq_length], scale=1.0) attention_mask = random_attention_mask([self.batch_size, self.seq_length]) config = self.get_config() return config, input_values, attention_mask def get_config(self): return WavLMConfig( hidden_size=self.hidden_size, feat_extract_norm=self.feat_extract_norm, feat_extract_dropout=self.feat_extract_dropout, feat_extract_activation=self.feat_extract_activation, conv_dim=self.conv_dim, conv_stride=self.conv_stride, conv_kernel=self.conv_kernel, conv_bias=self.conv_bias, num_conv_pos_embeddings=self.num_conv_pos_embeddings, num_conv_pos_embedding_groups=self.num_conv_pos_embedding_groups, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, hidden_dropout_prob=self.hidden_dropout_prob, intermediate_size=self.intermediate_size, layer_norm_eps=self.layer_norm_eps, hidden_act=self.hidden_act, initializer_range=self.initializer_range, vocab_size=self.vocab_size, tdnn_dim=self.tdnn_dim, tdnn_kernel=self.tdnn_kernel, tdnn_dilation=self.tdnn_dilation, xvector_output_dim=self.xvector_output_dim, ) def create_and_check_model(self, config, input_values, attention_mask): model = WavLMModel(config=config) model.to(torch_device) model.eval() result = model(input_values, attention_mask=attention_mask) self.parent.assertEqual( result.last_hidden_state.shape, (self.batch_size, self.output_seq_length, self.hidden_size) ) def check_ctc_loss(self, config, input_values, *args): model = WavLMForCTC(config=config) model.to(torch_device) # make sure that dropout is disabled model.eval() input_values = input_values[:3] attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.long) input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths)) labels = ids_tensor((input_values.shape[0], min(max_length_labels) - 1), model.config.vocab_size) # pad input for i in range(len(input_lengths)): input_values[i, input_lengths[i] :] = 0.0 attention_mask[i, input_lengths[i] :] = 0 model.config.ctc_loss_reduction = "sum" sum_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item() model.config.ctc_loss_reduction = "mean" mean_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item() self.parent.assertTrue(isinstance(sum_loss, float)) self.parent.assertTrue(isinstance(mean_loss, float)) def check_seq_classifier_loss(self, config, input_values, *args): model = WavLMForSequenceClassification(config=config) model.to(torch_device) # make sure that dropout is disabled model.eval() input_values = input_values[:3] attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.long) input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] labels = ids_tensor((input_values.shape[0], 1), len(model.config.id2label)) # pad input for i in range(len(input_lengths)): input_values[i, input_lengths[i] :] = 0.0 attention_mask[i, input_lengths[i] :] = 0 masked_loss = model(input_values, attention_mask=attention_mask, labels=labels).loss.item() unmasked_loss = model(input_values, labels=labels).loss.item() self.parent.assertTrue(isinstance(masked_loss, float)) self.parent.assertTrue(isinstance(unmasked_loss, float)) self.parent.assertTrue(masked_loss != unmasked_loss) def check_ctc_training(self, config, input_values, *args): config.ctc_zero_infinity = True model = WavLMForCTC(config=config) model.to(torch_device) model.train() # freeze feature encoder model.freeze_feature_encoder() input_values = input_values[:3] input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths)) labels = ids_tensor((input_values.shape[0], max(max_length_labels) - 2), model.config.vocab_size) # pad input for i in range(len(input_lengths)): input_values[i, input_lengths[i] :] = 0.0 if max_length_labels[i] < labels.shape[-1]: # it's important that we make sure that target lengths are at least # one shorter than logit lengths to prevent -inf labels[i, max_length_labels[i] - 1 :] = -100 loss = model(input_values, labels=labels).loss self.parent.assertFalse(torch.isinf(loss).item()) loss.backward() def check_seq_classifier_training(self, config, input_values, *args): config.ctc_zero_infinity = True model = WavLMForSequenceClassification(config=config) model.to(torch_device) model.train() # freeze everything but the classification head model.freeze_base_model() input_values = input_values[:3] input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] labels = ids_tensor((input_values.shape[0], 1), len(model.config.id2label)) # pad input for i in range(len(input_lengths)): input_values[i, input_lengths[i] :] = 0.0 loss = model(input_values, labels=labels).loss self.parent.assertFalse(torch.isinf(loss).item()) loss.backward() def check_output_attentions(self, config, input_values, attention_mask): model = WavLMModel(config=config) model.config.layerdrop = 1.0 model.to(torch_device) model.train() outputs = model(input_values, attention_mask=attention_mask, output_attentions=True) self.parent.assertTrue(len(outputs.attentions) > 0) def check_labels_out_of_vocab(self, config, input_values, *args): model = WavLMForCTC(config) model.to(torch_device) model.train() input_values = input_values[:3] input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] max_length_labels = model._get_feat_extract_output_lengths(torch.tensor(input_lengths)) labels = ids_tensor((input_values.shape[0], max(max_length_labels) - 2), model.config.vocab_size + 100) with pytest.raises(ValueError): model(input_values, labels=labels) def prepare_config_and_inputs_for_common(self): config, input_values, attention_mask = self.prepare_config_and_inputs() inputs_dict = {"input_values": input_values, "attention_mask": attention_mask} return config, inputs_dict @require_torch class WavLMModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( (WavLMForCTC, WavLMModel, WavLMForAudioFrameClassification, WavLMForSequenceClassification, WavLMForXVector) if is_torch_available() else () ) pipeline_model_mapping = ( { "audio-classification": WavLMForSequenceClassification, "automatic-speech-recognition": WavLMForCTC, "feature-extraction": WavLMModel, } if is_torch_available() else {} ) test_pruning = False test_headmasking = False def setUp(self): self.model_tester = WavLMModelTester(self) self.config_tester = ConfigTester(self, config_class=WavLMConfig, hidden_size=37) def test_config(self): self.config_tester.run_common_tests() def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) def test_ctc_loss_inference(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.check_ctc_loss(*config_and_inputs) def test_seq_classifier_loss_inference(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.check_seq_classifier_loss(*config_and_inputs) def test_ctc_train(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.check_ctc_training(*config_and_inputs) def test_seq_classifier_train(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.check_seq_classifier_training(*config_and_inputs) def test_output_attentions(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.check_output_attentions(*config_and_inputs) def test_labels_out_of_vocab(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.check_labels_out_of_vocab(*config_and_inputs) @unittest.skip(reason="WavLM has no inputs_embeds") def test_inputs_embeds(self): pass # `input_ids` is renamed to `input_values` @unittest.skip(reason="WavLM has no input_ids") def test_forward_signature(self): pass @unittest.skip(reason="WavLM has no token embeddings") def test_resize_tokens_embeddings(self): pass def test_model_get_set_embeddings(self): pass # WavLM uses PyTorch's multi-head-attention class # and thus can't retain gradients on attentions def test_retain_grad_hidden_states_attentions(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() config.output_hidden_states = True config.output_attentions = True # no need to test all models as different heads yield the same functionality model_class = self.all_model_classes[0] model = model_class(config) model.to(torch_device) # set layer drop to 0 model.config.layerdrop = 0.0 input_values = inputs_dict["input_values"] input_lengths = torch.tensor( [input_values.shape[1] for _ in range(input_values.shape[0])], dtype=torch.long, device=torch_device ) output_lengths = model._get_feat_extract_output_lengths(input_lengths) labels = ids_tensor((input_values.shape[0], output_lengths[0] - 2), self.model_tester.vocab_size) inputs_dict["attention_mask"] = torch.ones_like(inputs_dict["attention_mask"]) inputs_dict["labels"] = labels outputs = model(**inputs_dict) output = outputs[0] # Encoder-/Decoder-only models hidden_states = outputs.hidden_states[0] hidden_states.retain_grad() output.flatten()[0].backward(retain_graph=True) self.assertIsNotNone(hidden_states.grad) def test_initialization(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() configs_no_init = _config_zero_init(config) for model_class in self.all_model_classes: model = model_class(config=configs_no_init) for name, param in model.named_parameters(): uniform_init_parms = [ "conv.weight", "conv.parametrizations.weight", "masked_spec_embed", "codevectors", "quantizer.weight_proj.weight", "project_hid.weight", "project_hid.bias", "project_q.weight", "project_q.bias", "feature_projection.projection.weight", "feature_projection.projection.bias", "label_embeddings_concat", "rel_attn_embed", "objective.weight", ] if param.requires_grad: if any(x in name for x in uniform_init_parms): self.assertTrue( -1.0 <= ((param.data.mean() * 1e9).round() / 1e9).item() <= 1.0, msg=f"Parameter {name} of model {model_class} seems not properly initialized", ) else: self.assertIn( ((param.data.mean() * 1e9).round() / 1e9).item(), [0.0, 1.0], msg=f"Parameter {name} of model {model_class} seems not properly initialized", ) # overwrite from test_modeling_common def _mock_init_weights(self, module): if hasattr(module, "weight") and module.weight is not None: module.weight.data.fill_(3) if hasattr(module, "weight_g") and module.weight_g is not None: module.weight_g.data.fill_(3) if hasattr(module, "weight_v") and module.weight_v is not None: module.weight_v.data.fill_(3) if hasattr(module, "bias") and module.bias is not None: module.bias.data.fill_(3) if hasattr(module, "codevectors") and module.codevectors is not None: module.codevectors.data.fill_(3) if hasattr(module, "masked_spec_embed") and module.masked_spec_embed is not None: module.masked_spec_embed.data.fill_(3) @unittest.skip(reason="Feed forward chunking is not implemented for WavLM") def test_feed_forward_chunking(self): pass @slow def test_model_from_pretrained(self): model = WavLMModel.from_pretrained("microsoft/wavlm-base-plus") self.assertIsNotNone(model) @require_torch @require_torchaudio @slow class WavLMModelIntegrationTest(unittest.TestCase): def _load_datasamples(self, num_samples): ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") # automatic decoding with librispeech speech_samples = ds.sort("id").filter( lambda x: x["id"] in [f"1272-141231-000{i}" for i in range(num_samples)] )[:num_samples]["audio"] return [x["array"] for x in speech_samples] def _load_superb(self, task, num_samples): ds = load_dataset("anton-l/superb_dummy", task, split="test") return ds[:num_samples] def test_inference_base(self): model = WavLMModel.from_pretrained("microsoft/wavlm-base-plus").to(torch_device) feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained( "microsoft/wavlm-base-plus", return_attention_mask=True ) input_speech = self._load_datasamples(2) inputs = feature_extractor(input_speech, return_tensors="pt", padding=True) input_values = inputs.input_values.to(torch_device) attention_mask = inputs.attention_mask.to(torch_device) with torch.no_grad(): hidden_states_slice = ( model(input_values, attention_mask=attention_mask).last_hidden_state[:, -2:, -2:].cpu() ) EXPECTED_HIDDEN_STATES_SLICE = torch.tensor( [[[0.0577, 0.1161], [0.0579, 0.1165]], [[0.0199, 0.1237], [0.0059, 0.0605]]] ) torch.testing.assert_close(hidden_states_slice, EXPECTED_HIDDEN_STATES_SLICE, rtol=5e-2, atol=5e-2) def test_inference_large(self): model = WavLMModel.from_pretrained("microsoft/wavlm-large").to(torch_device) feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained( "microsoft/wavlm-large", return_attention_mask=True ) input_speech = self._load_datasamples(2) inputs = feature_extractor(input_speech, return_tensors="pt", padding=True) input_values = inputs.input_values.to(torch_device) attention_mask = inputs.attention_mask.to(torch_device) with torch.no_grad(): hidden_states_slice = ( model(input_values, attention_mask=attention_mask).last_hidden_state[:, -2:, -2:].cpu() ) EXPECTED_HIDDEN_STATES_SLICE = torch.tensor( [[[0.2122, 0.0500], [0.2118, 0.0563]], [[0.1353, 0.1818], [0.2453, 0.0595]]] ) torch.testing.assert_close(hidden_states_slice, EXPECTED_HIDDEN_STATES_SLICE, rtol=5e-2, atol=5e-2) def test_inference_diarization(self): model = WavLMForAudioFrameClassification.from_pretrained("microsoft/wavlm-base-plus-sd").to(torch_device) processor = Wav2Vec2FeatureExtractor.from_pretrained("microsoft/wavlm-base-plus-sd") input_data = self._load_superb("sd", 4) inputs = processor(input_data["speech"], return_tensors="pt", padding=True, sampling_rate=16_000) input_values = inputs.input_values.to(torch_device) attention_mask = inputs.attention_mask.to(torch_device) with torch.no_grad(): outputs = model(input_values, attention_mask=attention_mask) # labels is a one-hot array of shape (num_frames, num_speakers) labels = (outputs.logits > 0).long() # s3prl logits for the same batch expected_logits = torch.tensor( [ [[-5.9566, -8.6554], [-5.7137, -8.9386], [-5.7906, -7.0973], [-5.7829, -5.9999]], [[-5.2086, -7.7878], [-4.8890, -7.9312], [-4.2004, -3.9101], [-5.4480, -4.6932]], [[-4.6105, -6.7178], [-5.1930, -6.1635], [-2.6228, -4.1123], [-2.7646, -3.1576]], [[-4.4477, -7.9206], [-3.9339, -7.3707], [-4.9528, -4.8242], [-3.6921, -2.9687]], ], device=torch_device, ) self.assertEqual(labels[0, :, 0].sum(), 258) self.assertEqual(labels[0, :, 1].sum(), 647) torch.testing.assert_close(outputs.logits[:, :4], expected_logits, rtol=1e-2, atol=1e-2) def test_inference_speaker_verification(self): model = WavLMForXVector.from_pretrained("microsoft/wavlm-base-plus-sv").to(torch_device) processor = Wav2Vec2FeatureExtractor.from_pretrained("microsoft/wavlm-base-plus-sv") input_data = self._load_superb("si", 4) inputs = processor(input_data["speech"], return_tensors="pt", padding=True) labels = torch.tensor([5, 1, 1, 3], device=torch_device).T with torch.no_grad(): input_values = inputs.input_values.to(torch_device) attention_mask = inputs.attention_mask.to(torch_device) outputs = model(input_values, attention_mask=attention_mask, labels=labels) embeddings = torch.nn.functional.normalize(outputs.embeddings, dim=-1) cosine_sim = torch.nn.CosineSimilarity(dim=-1) # id10002 vs id10002 self.assertAlmostEqual(cosine_sim(embeddings[1], embeddings[2]).item(), 0.9787, 3) # id10006 vs id10002 self.assertAlmostEqual(cosine_sim(embeddings[0], embeddings[1]).item(), 0.5064, 3) # id10002 vs id10004 self.assertAlmostEqual(cosine_sim(embeddings[2], embeddings[3]).item(), 0.4780, 3) self.assertAlmostEqual(outputs.loss.item(), 18.4154, 2)
transformers/tests/models/wavlm/test_modeling_wavlm.py/0
{ "file_path": "transformers/tests/models/wavlm/test_modeling_wavlm.py", "repo_id": "transformers", "token_count": 10610 }
546
# Copyright 2022 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_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_torch_available, is_vision_available, ) from transformers.pipelines import DocumentQuestionAnsweringPipeline, pipeline from transformers.pipelines.document_question_answering import apply_tesseract from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_detectron2, require_pytesseract, require_torch, require_torch_bf16, require_vision, slow, ) from .test_pipelines_common import ANY if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers.image_utils import load_image else: class Image: @staticmethod def open(*args, **kwargs): pass def load_image(_): return None # This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace, # so we can expect it to be available. INVOICE_URL = ( "https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png" ) @is_pipeline_test @require_torch @require_vision class DocumentQuestionAnsweringPipelineTests(unittest.TestCase): model_mapping = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING @require_pytesseract @require_vision def get_test_pipeline( self, model, tokenizer=None, image_processor=None, feature_extractor=None, processor=None, dtype="float32", ): dqa_pipeline = DocumentQuestionAnsweringPipeline( model=model, tokenizer=tokenizer, feature_extractor=feature_extractor, image_processor=image_processor, processor=processor, dtype=dtype, max_new_tokens=20, ) image = INVOICE_URL word_boxes = list(zip(*apply_tesseract(load_image(image), None, ""))) question = "What is the placebo?" examples = [ { "image": load_image(image), "question": question, }, { "image": image, "question": question, }, { "image": image, "question": question, "word_boxes": word_boxes, }, ] return dqa_pipeline, examples def run_pipeline_test(self, dqa_pipeline, examples): outputs = dqa_pipeline(examples, top_k=2) self.assertEqual( outputs, [ [ {"score": ANY(float), "answer": ANY(str), "start": ANY(int), "end": ANY(int)}, {"score": ANY(float), "answer": ANY(str), "start": ANY(int), "end": ANY(int)}, ] ] * 3, ) @require_torch @require_detectron2 @require_pytesseract def test_small_model_pt(self): dqa_pipeline = pipeline( "document-question-answering", model="hf-internal-testing/tiny-random-layoutlmv2-for-dqa-test" ) image = INVOICE_URL question = "How many cats are there?" expected_output = [ {"score": 0.0001, "answer": "oy 2312/2019", "start": 38, "end": 39}, {"score": 0.0001, "answer": "oy 2312/2019 DUE", "start": 38, "end": 40}, ] outputs = dqa_pipeline(image=image, question=question, top_k=2) self.assertEqual(nested_simplify(outputs, decimals=4), expected_output) outputs = dqa_pipeline({"image": image, "question": question}, top_k=2) self.assertEqual(nested_simplify(outputs, decimals=4), expected_output) # This image does not detect ANY text in it, meaning layoutlmv2 should fail. # Empty answer probably image = "./tests/fixtures/tests_samples/COCO/000000039769.png" outputs = dqa_pipeline(image=image, question=question, top_k=2) self.assertEqual(outputs, []) # We can optionally pass directly the words and bounding boxes image = "./tests/fixtures/tests_samples/COCO/000000039769.png" words = [] boxes = [] outputs = dqa_pipeline(image=image, question=question, words=words, boxes=boxes, top_k=2) self.assertEqual(outputs, []) @require_torch @require_torch_bf16 @require_detectron2 @require_pytesseract def test_small_model_pt_bf16(self): dqa_pipeline = pipeline( "document-question-answering", model="hf-internal-testing/tiny-random-layoutlmv2-for-dqa-test", dtype=torch.bfloat16, ) image = INVOICE_URL question = "How many cats are there?" expected_output = [ {"score": 0.0001, "answer": "oy 2312/2019", "start": 38, "end": 39}, {"score": 0.0001, "answer": "oy 2312/2019 DUE", "start": 38, "end": 40}, ] outputs = dqa_pipeline(image=image, question=question, top_k=2) self.assertEqual(nested_simplify(outputs, decimals=4), expected_output) outputs = dqa_pipeline({"image": image, "question": question}, top_k=2) self.assertEqual(nested_simplify(outputs, decimals=4), expected_output) # This image does not detect ANY text in it, meaning layoutlmv2 should fail. # Empty answer probably image = "./tests/fixtures/tests_samples/COCO/000000039769.png" outputs = dqa_pipeline(image=image, question=question, top_k=2) self.assertEqual(outputs, []) # We can optionally pass directly the words and bounding boxes image = "./tests/fixtures/tests_samples/COCO/000000039769.png" words = [] boxes = [] outputs = dqa_pipeline(image=image, question=question, words=words, boxes=boxes, top_k=2) self.assertEqual(outputs, []) # TODO: Enable this once hf-internal-testing/tiny-random-donut is implemented # @require_torch # def test_small_model_pt_donut(self): # dqa_pipeline = pipeline("document-question-answering", model="hf-internal-testing/tiny-random-donut") # # dqa_pipeline = pipeline("document-question-answering", model="../tiny-random-donut") # image = "https://templates.invoicehome.com/invoice-template-us-neat-750px.png" # question = "How many cats are there?" # # outputs = dqa_pipeline(image=image, question=question, top_k=2) # self.assertEqual( # nested_simplify(outputs, decimals=4), [{"score": 0.8799, "answer": "2"}, {"score": 0.296, "answer": "1"}] # ) @slow @require_torch @require_detectron2 @require_pytesseract def test_large_model_pt(self): dqa_pipeline = pipeline( "document-question-answering", model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa", revision="9977165", ) image = INVOICE_URL question = "What is the invoice number?" outputs = dqa_pipeline(image=image, question=question, top_k=2) self.assertEqual( nested_simplify(outputs, decimals=4), [ {"score": 0.9944, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0009, "answer": "us-001", "start": 16, "end": 16}, ], ) outputs = dqa_pipeline({"image": image, "question": question}, top_k=2) self.assertEqual( nested_simplify(outputs, decimals=4), [ {"score": 0.9944, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0009, "answer": "us-001", "start": 16, "end": 16}, ], ) outputs = dqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}], top_k=2 ) self.assertEqual( nested_simplify(outputs, decimals=4), [ [ {"score": 0.9944, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.0009, "answer": "us-001", "start": 16, "end": 16}, ], ] * 2, ) @slow @require_torch @require_detectron2 @require_pytesseract def test_large_model_pt_chunk(self): dqa_pipeline = pipeline( "document-question-answering", model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa", revision="9977165", max_seq_len=50, ) image = INVOICE_URL question = "What is the invoice number?" outputs = dqa_pipeline(image=image, question=question, top_k=2) self.assertEqual( nested_simplify(outputs, decimals=4), [ {"score": 0.9974, "answer": "1110212019", "start": 23, "end": 23}, {"score": 0.9948, "answer": "us-001", "start": 16, "end": 16}, ], ) outputs = dqa_pipeline({"image": image, "question": question}, top_k=2) self.assertEqual( nested_simplify(outputs, decimals=4), [ {"score": 0.9974, "answer": "1110212019", "start": 23, "end": 23}, {"score": 0.9948, "answer": "us-001", "start": 16, "end": 16}, ], ) outputs = dqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}], top_k=2 ) self.assertEqual( nested_simplify(outputs, decimals=4), [ [ {"score": 0.9974, "answer": "1110212019", "start": 23, "end": 23}, {"score": 0.9948, "answer": "us-001", "start": 16, "end": 16}, ] ] * 2, ) @slow @require_torch @require_pytesseract @require_vision def test_large_model_pt_layoutlm(self): tokenizer = AutoTokenizer.from_pretrained( "impira/layoutlm-document-qa", revision="3dc6de3", add_prefix_space=True ) dqa_pipeline = pipeline( "document-question-answering", model="impira/layoutlm-document-qa", tokenizer=tokenizer, revision="3dc6de3", ) image = INVOICE_URL question = "What is the invoice number?" outputs = dqa_pipeline(image=image, question=question, top_k=2) self.assertEqual( nested_simplify(outputs, decimals=3), [ {"score": 0.425, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.082, "answer": "1110212019", "start": 23, "end": 23}, ], ) outputs = dqa_pipeline({"image": image, "question": question}, top_k=2) self.assertEqual( nested_simplify(outputs, decimals=3), [ {"score": 0.425, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.082, "answer": "1110212019", "start": 23, "end": 23}, ], ) outputs = dqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}], top_k=2 ) self.assertEqual( nested_simplify(outputs, decimals=3), [ [ {"score": 0.425, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.082, "answer": "1110212019", "start": 23, "end": 23}, ] ] * 2, ) word_boxes = list(zip(*apply_tesseract(load_image(image), None, ""))) # This model should also work if `image` is set to None outputs = dqa_pipeline({"image": None, "word_boxes": word_boxes, "question": question}, top_k=2) self.assertEqual( nested_simplify(outputs, decimals=3), [ {"score": 0.425, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.082, "answer": "1110212019", "start": 23, "end": 23}, ], ) @slow @require_torch @require_pytesseract @require_vision def test_large_model_pt_layoutlm_chunk(self): tokenizer = AutoTokenizer.from_pretrained( "impira/layoutlm-document-qa", revision="3dc6de3", add_prefix_space=True ) dqa_pipeline = pipeline( "document-question-answering", model="impira/layoutlm-document-qa", tokenizer=tokenizer, revision="3dc6de3", max_seq_len=50, ) image = INVOICE_URL question = "What is the invoice number?" outputs = dqa_pipeline(image=image, question=question, top_k=2) self.assertEqual( nested_simplify(outputs, decimals=4), [ {"score": 0.9999, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.9998, "answer": "us-001", "start": 16, "end": 16}, ], ) outputs = dqa_pipeline( [{"image": image, "question": question}, {"image": image, "question": question}], top_k=2 ) self.assertEqual( nested_simplify(outputs, decimals=4), [ [ {"score": 0.9999, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.9998, "answer": "us-001", "start": 16, "end": 16}, ] ] * 2, ) word_boxes = list(zip(*apply_tesseract(load_image(image), None, ""))) # This model should also work if `image` is set to None outputs = dqa_pipeline({"image": None, "word_boxes": word_boxes, "question": question}, top_k=2) self.assertEqual( nested_simplify(outputs, decimals=4), [ {"score": 0.9999, "answer": "us-001", "start": 16, "end": 16}, {"score": 0.9998, "answer": "us-001", "start": 16, "end": 16}, ], ) @slow @require_torch def test_large_model_pt_donut(self): dqa_pipeline = pipeline( "document-question-answering", model="naver-clova-ix/donut-base-finetuned-docvqa", tokenizer=AutoTokenizer.from_pretrained("naver-clova-ix/donut-base-finetuned-docvqa"), image_processor="naver-clova-ix/donut-base-finetuned-docvqa", ) image = INVOICE_URL question = "What is the invoice number?" outputs = dqa_pipeline(image=image, question=question, top_k=2) self.assertEqual(nested_simplify(outputs, decimals=4), [{"answer": "us-001"}])
transformers/tests/pipelines/test_pipelines_document_question_answering.py/0
{ "file_path": "transformers/tests/pipelines/test_pipelines_document_question_answering.py", "repo_id": "transformers", "token_count": 7457 }
547
# 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 ( MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING, TextGenerationPipeline, logging, pipeline, ) from transformers.testing_utils import ( CaptureLogger, is_pipeline_test, require_accelerate, require_torch, require_torch_accelerator, require_torch_or_tf, torch_device, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf class TextGenerationPipelineTests(unittest.TestCase): model_mapping = MODEL_FOR_CAUSAL_LM_MAPPING tf_model_mapping = TF_MODEL_FOR_CAUSAL_LM_MAPPING @require_torch def test_small_model_pt(self): text_generator = pipeline( task="text-generation", model="hf-internal-testing/tiny-random-LlamaForCausalLM", framework="pt", max_new_tokens=10, ) # Using `do_sample=False` to force deterministic output outputs = text_generator("This is a test", do_sample=False) self.assertEqual(outputs, [{"generated_text": "This is a testкт MéxicoWSAnimImportдели pip letscosatur"}]) outputs = text_generator(["This is a test", "This is a second test"], do_sample=False) self.assertEqual( outputs, [ [{"generated_text": "This is a testкт MéxicoWSAnimImportдели pip letscosatur"}], [{"generated_text": "This is a second testкт MéxicoWSAnimImportдели Düsseld bootstrap learn user"}], ], ) outputs = text_generator("This is a test", do_sample=True, num_return_sequences=2, return_tensors=True) self.assertEqual( outputs, [ {"generated_token_ids": ANY(list)}, {"generated_token_ids": ANY(list)}, ], ) @require_torch def test_small_chat_model_pt(self): text_generator = pipeline( task="text-generation", model="hf-internal-testing/tiny-gpt2-with-chatml-template", framework="pt", ) # Using `do_sample=False` to force deterministic output chat1 = [ {"role": "system", "content": "This is a system message."}, {"role": "user", "content": "This is a test"}, ] chat2 = [ {"role": "system", "content": "This is a system message."}, {"role": "user", "content": "This is a second test"}, ] outputs = text_generator(chat1, do_sample=False, max_new_tokens=10) expected_chat1 = chat1 + [ { "role": "assistant", "content": " factors factors factors factors factors factors factors factors factors factors", } ] self.assertEqual( outputs, [ {"generated_text": expected_chat1}, ], ) outputs = text_generator([chat1, chat2], do_sample=False, max_new_tokens=10) expected_chat2 = chat2 + [ { "role": "assistant", "content": " stairs stairs stairs stairs stairs stairs stairs stairs stairs stairs", } ] self.assertEqual( outputs, [ [{"generated_text": expected_chat1}], [{"generated_text": expected_chat2}], ], ) @require_torch def test_small_chat_model_continue_final_message(self): # Here we check that passing a chat that ends in an assistant message is handled correctly # by continuing the final message rather than starting a new one text_generator = pipeline( task="text-generation", model="hf-internal-testing/tiny-gpt2-with-chatml-template", framework="pt", ) # Using `do_sample=False` to force deterministic output chat1 = [ {"role": "system", "content": "This is a system message."}, {"role": "user", "content": "This is a test"}, {"role": "assistant", "content": "This is"}, ] outputs = text_generator(chat1, do_sample=False, max_new_tokens=10) # Assert that we continued the last message and there isn't a sneaky <|im_end|> self.assertEqual( outputs, [ { "generated_text": [ {"role": "system", "content": "This is a system message."}, {"role": "user", "content": "This is a test"}, { "role": "assistant", "content": "This is stairs stairs stairs stairs stairs stairs stairs stairs stairs stairs", }, ] } ], ) @require_torch def test_small_chat_model_continue_final_message_override(self): # Here we check that passing a chat that ends in an assistant message is handled correctly # by continuing the final message rather than starting a new one text_generator = pipeline( task="text-generation", model="hf-internal-testing/tiny-gpt2-with-chatml-template", framework="pt", ) # Using `do_sample=False` to force deterministic output chat1 = [ {"role": "system", "content": "This is a system message."}, {"role": "user", "content": "This is a test"}, ] outputs = text_generator(chat1, do_sample=False, max_new_tokens=10, continue_final_message=True) # Assert that we continued the last message and there isn't a sneaky <|im_end|> self.assertEqual( outputs, [ { "generated_text": [ {"role": "system", "content": "This is a system message."}, { "role": "user", "content": "This is a test stairs stairs stairs stairs stairs stairs stairs stairs stairs stairs", }, ] } ], ) @require_torch def test_small_chat_model_with_dataset_pt(self): from torch.utils.data import Dataset from transformers.pipelines.pt_utils import KeyDataset class MyDataset(Dataset): data = [ [ {"role": "system", "content": "This is a system message."}, {"role": "user", "content": "This is a test"}, ], ] def __len__(self): return 1 def __getitem__(self, i): return {"text": self.data[i]} text_generator = pipeline( task="text-generation", model="hf-internal-testing/tiny-gpt2-with-chatml-template", framework="pt", ) dataset = MyDataset() key_dataset = KeyDataset(dataset, "text") for outputs in text_generator(key_dataset, do_sample=False, max_new_tokens=10): expected_chat = dataset.data[0] + [ { "role": "assistant", "content": " factors factors factors factors factors factors factors factors factors factors", } ] self.assertEqual( outputs, [ {"generated_text": expected_chat}, ], ) @require_torch def test_small_chat_model_with_iterator_pt(self): from transformers.pipelines.pt_utils import PipelineIterator text_generator = pipeline( task="text-generation", model="hf-internal-testing/tiny-gpt2-with-chatml-template", framework="pt", ) # Using `do_sample=False` to force deterministic output chat1 = [ {"role": "system", "content": "This is a system message."}, {"role": "user", "content": "This is a test"}, ] chat2 = [ {"role": "system", "content": "This is a system message."}, {"role": "user", "content": "This is a second test"}, ] expected_chat1 = chat1 + [ { "role": "assistant", "content": " factors factors factors factors factors factors factors factors factors factors", } ] expected_chat2 = chat2 + [ { "role": "assistant", "content": " stairs stairs stairs stairs stairs stairs stairs stairs stairs stairs", } ] def data(): yield from [chat1, chat2] outputs = text_generator(data(), do_sample=False, max_new_tokens=10) assert isinstance(outputs, PipelineIterator) outputs = list(outputs) self.assertEqual( outputs, [ [{"generated_text": expected_chat1}], [{"generated_text": expected_chat2}], ], ) def get_test_pipeline( self, model, tokenizer=None, image_processor=None, feature_extractor=None, processor=None, dtype="float32", ): text_generator = TextGenerationPipeline( model=model, tokenizer=tokenizer, feature_extractor=feature_extractor, image_processor=image_processor, processor=processor, dtype=dtype, max_new_tokens=5, ) return text_generator, ["This is a test", "Another test"] def test_stop_sequence_stopping_criteria(self): prompt = """Hello I believe in""" text_generator = pipeline( "text-generation", model="hf-internal-testing/tiny-random-gpt2", max_new_tokens=5, do_sample=False ) output = text_generator(prompt) self.assertEqual( output, [{"generated_text": "Hello I believe in fe fe fe fe fe"}], ) output = text_generator(prompt, stop_sequence=" fe") self.assertEqual(output, [{"generated_text": "Hello I believe in fe"}]) def run_pipeline_test(self, text_generator, _): model = text_generator.model tokenizer = text_generator.tokenizer outputs = text_generator("This is a test") self.assertEqual(outputs, [{"generated_text": ANY(str)}]) self.assertTrue(outputs[0]["generated_text"].startswith("This is a test")) outputs = text_generator("This is a test", return_full_text=False) self.assertEqual(outputs, [{"generated_text": ANY(str)}]) self.assertNotIn("This is a test", outputs[0]["generated_text"]) text_generator = pipeline( task="text-generation", model=model, tokenizer=tokenizer, return_full_text=False, max_new_tokens=5 ) outputs = text_generator("This is a test") self.assertEqual(outputs, [{"generated_text": ANY(str)}]) self.assertNotIn("This is a test", outputs[0]["generated_text"]) outputs = text_generator("This is a test", return_full_text=True) self.assertEqual(outputs, [{"generated_text": ANY(str)}]) self.assertTrue(outputs[0]["generated_text"].startswith("This is a test")) outputs = text_generator(["This is great !", "Something else"], num_return_sequences=2, do_sample=True) self.assertEqual( outputs, [ [{"generated_text": ANY(str)}, {"generated_text": ANY(str)}], [{"generated_text": ANY(str)}, {"generated_text": ANY(str)}], ], ) if text_generator.tokenizer.pad_token is not None: outputs = text_generator( ["This is great !", "Something else"], num_return_sequences=2, batch_size=2, do_sample=True ) self.assertEqual( outputs, [ [{"generated_text": ANY(str)}, {"generated_text": ANY(str)}], [{"generated_text": ANY(str)}, {"generated_text": ANY(str)}], ], ) with self.assertRaises(ValueError): outputs = text_generator("test", return_full_text=True, return_text=True) with self.assertRaises(ValueError): outputs = text_generator("test", return_full_text=True, return_tensors=True) with self.assertRaises(ValueError): outputs = text_generator("test", return_text=True, return_tensors=True) # Empty prompt is slightly special # it requires BOS token to exist. # Special case for Pegasus which will always append EOS so will # work even without BOS. if ( text_generator.tokenizer.bos_token_id is not None or "Pegasus" in tokenizer.__class__.__name__ or "Git" in model.__class__.__name__ ): outputs = text_generator("") self.assertEqual(outputs, [{"generated_text": ANY(str)}]) else: with self.assertRaises((ValueError, AssertionError)): outputs = text_generator("", add_special_tokens=False) if text_generator.framework == "tf": # TF generation does not support max_new_tokens, and it's impossible # to control long generation with only max_length without # fancy calculation, dismissing tests for now. self.skipTest(reason="TF generation does not support max_new_tokens") # We don't care about infinite range models. # They already work. # Skip this test for XGLM, since it uses sinusoidal positional embeddings which are resized on-the-fly. EXTRA_MODELS_CAN_HANDLE_LONG_INPUTS = [ "RwkvForCausalLM", "XGLMForCausalLM", "GPTNeoXForCausalLM", "GPTNeoXJapaneseForCausalLM", "FuyuForCausalLM", "LlamaForCausalLM", ] if ( tokenizer.model_max_length < 10000 and text_generator.model.__class__.__name__ not in EXTRA_MODELS_CAN_HANDLE_LONG_INPUTS ): # Handling of large generations if str(text_generator.device) == "cpu": with self.assertRaises((RuntimeError, IndexError, ValueError, AssertionError)): text_generator("This is a test" * 500, max_new_tokens=5) outputs = text_generator("This is a test" * 500, handle_long_generation="hole", max_new_tokens=5) # Hole strategy cannot work if str(text_generator.device) == "cpu": with self.assertRaises(ValueError): text_generator( "This is a test" * 500, handle_long_generation="hole", max_new_tokens=tokenizer.model_max_length + 10, ) @require_torch @require_accelerate @require_torch_accelerator def test_small_model_pt_bloom_accelerate(self): import torch # Classic `model_kwargs` pipe = pipeline( model="hf-internal-testing/tiny-random-bloom", model_kwargs={"device_map": "auto", "dtype": torch.bfloat16}, max_new_tokens=5, do_sample=False, ) self.assertEqual(pipe.model.lm_head.weight.dtype, torch.bfloat16) out = pipe("This is a test") self.assertEqual( out, [{"generated_text": ("This is a test test test test test test")}], ) # Upgraded those two to real pipeline arguments (they just get sent for the model as they're unlikely to mean anything else.) pipe = pipeline( model="hf-internal-testing/tiny-random-bloom", device_map="auto", dtype=torch.bfloat16, max_new_tokens=5, do_sample=False, ) self.assertEqual(pipe.model.lm_head.weight.dtype, torch.bfloat16) out = pipe("This is a test") self.assertEqual( out, [{"generated_text": ("This is a test test test test test test")}], ) # dtype will be automatically set to torch.bfloat16 if not provided - check: https://github.com/huggingface/transformers/pull/38882 pipe = pipeline( model="hf-internal-testing/tiny-random-bloom", device_map="auto", max_new_tokens=5, do_sample=False ) self.assertEqual(pipe.model.lm_head.weight.dtype, torch.bfloat16) out = pipe("This is a test") self.assertEqual( out, [{"generated_text": ("This is a test test test test test test")}], ) @require_torch @require_torch_accelerator def test_small_model_fp16(self): import torch pipe = pipeline( model="hf-internal-testing/tiny-random-bloom", device=torch_device, dtype=torch.float16, max_new_tokens=3, ) pipe("This is a test") @require_torch @require_accelerate @require_torch_accelerator def test_pipeline_accelerate_top_p(self): import torch pipe = pipeline( model="hf-internal-testing/tiny-random-bloom", device_map=torch_device, dtype=torch.float16, max_new_tokens=3, ) pipe("This is a test", do_sample=True, top_p=0.5) def test_pipeline_length_setting_warning(self): prompt = """Hello world""" text_generator = pipeline("text-generation", model="hf-internal-testing/tiny-random-gpt2", max_new_tokens=5) if text_generator.model.framework == "tf": logger = logging.get_logger("transformers.generation.tf_utils") else: logger = logging.get_logger("transformers.generation.utils") logger_msg = "Both `max_new_tokens`" # The beginning of the message to be checked in this test # Both are set by the user -> log warning with CaptureLogger(logger) as cl: _ = text_generator(prompt, max_length=10, max_new_tokens=1) self.assertIn(logger_msg, cl.out) # The user only sets one -> no warning with CaptureLogger(logger) as cl: _ = text_generator(prompt, max_new_tokens=1) self.assertNotIn(logger_msg, cl.out) with CaptureLogger(logger) as cl: _ = text_generator(prompt, max_length=10, max_new_tokens=None) self.assertNotIn(logger_msg, cl.out) def test_return_dict_in_generate(self): text_generator = pipeline("text-generation", model="hf-internal-testing/tiny-random-gpt2", max_new_tokens=2) out = text_generator( ["This is great !", "Something else"], return_dict_in_generate=True, output_logits=True, output_scores=True ) self.assertEqual( out, [ [ { "generated_text": ANY(str), "logits": ANY(list), "scores": ANY(list), }, ], [ { "generated_text": ANY(str), "logits": ANY(list), "scores": ANY(list), }, ], ], ) @require_torch def test_pipeline_assisted_generation(self): """Tests that we can run assisted generation in the pipeline""" model = "hf-internal-testing/tiny-random-MistralForCausalLM" pipe = pipeline("text-generation", model=model, assistant_model=model, max_new_tokens=2) # We can run the pipeline prompt = "Hello world" _ = pipe(prompt) # It is running assisted generation under the hood (e.g. flags incompatible with assisted gen will crash) with self.assertRaises(ValueError): _ = pipe(prompt, generate_kwargs={"num_beams": 2}) @require_torch def test_pipeline_skip_special_tokens(self): """Tests that we can use `skip_special_tokens=False` to get the special tokens in the output""" model_id = "google/gemma-3-270m-it" chat = [{"role": "user", "content": "What's your name?"}] generator = pipeline("text-generation", model=model_id) # normal pipeline use output = generator(chat, max_new_tokens=20, do_sample=False) self.assertNotIn("<end_of_turn>", str(output[0]["generated_text"])) # forcing special tokens to be included in the output output = generator(chat, max_new_tokens=1000, do_sample=False, skip_special_tokens=False) self.assertIn("<end_of_turn>", str(output[0]["generated_text"]))
transformers/tests/pipelines/test_pipelines_text_generation.py/0
{ "file_path": "transformers/tests/pipelines/test_pipelines_text_generation.py", "repo_id": "transformers", "token_count": 10147 }
548
# Copyright 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 tempfile import unittest from transformers import AutoModelForCausalLM, AutoTokenizer, FPQuantConfig from transformers.testing_utils import ( backend_empty_cache, require_accelerate, require_fp_quant, require_qutlass, require_torch_gpu, require_torch_multi_gpu, slow, torch_device, ) @require_torch_gpu class FPQuantConfigTest(unittest.TestCase): def test_to_dict(self): """ Simple test that checks if one uses a config and converts it to a dict, the dict is the same as the config object """ quantization_config = FPQuantConfig() config_to_dict = quantization_config.to_dict() for key in config_to_dict: self.assertEqual(getattr(quantization_config, key), config_to_dict[key]) def test_from_dict(self): """ Simple test that checks if one uses a dict and converts it to a config object, the config object is the same as the dict """ dict = {"modules_to_not_convert": ["embed_tokens", "lm_head"], "quant_method": "fp_quant"} quantization_config = FPQuantConfig.from_dict(dict) self.assertEqual(dict["modules_to_not_convert"], quantization_config.modules_to_not_convert) self.assertEqual(dict["quant_method"], quantization_config.quant_method) @slow @require_torch_gpu @require_fp_quant @require_qutlass @require_accelerate class FPQuantTest(unittest.TestCase): model_name = "unsloth/Llama-3.2-1B" input_text = "1 2 3 4" max_new_tokens = 4 EXPECTED_OUTPUT = "1 2 3 4 5 6" device_map = "cuda" # called only once for all test in this class @classmethod def setUpClass(cls): """ Setup quantized model """ quantization_config = FPQuantConfig(pseudoquantization=False) cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name) cls.quantized_model = AutoModelForCausalLM.from_pretrained( cls.model_name, device_map=cls.device_map, quantization_config=quantization_config ) def tearDown(self): gc.collect() backend_empty_cache(torch_device) gc.collect() def test_quantized_model(self): """ Simple test that checks if the quantized model is working properly """ input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) output = self.quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) def test_save_pretrained(self): """ Simple test that checks if the quantized model is working properly after being saved and loaded """ with tempfile.TemporaryDirectory() as tmpdirname: self.quantized_model.save_pretrained(tmpdirname) model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=self.device_map) input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens) self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) @require_torch_multi_gpu def test_quantized_model_multi_gpu(self): """ Simple test that checks if the quantized model is working properly with multiple GPUs set CUDA_VISIBLE_DEVICES=0,1 if you have more than 2 GPUs """ input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) quantization_config = FPQuantConfig() quantized_model = AutoModelForCausalLM.from_pretrained( self.model_name, device_map="auto", quantization_config=quantization_config ) self.assertTrue(set(quantized_model.hf_device_map.values()) == {0, 1}) output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) @require_torch_multi_gpu def test_save_pretrained_multi_gpu(self): """ Simple test that checks if the quantized model is working properly after being saved and loaded """ with tempfile.TemporaryDirectory() as tmpdirname: self.quantized_model.save_pretrained(tmpdirname) model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map="auto") self.assertTrue(set(model.hf_device_map.values()) == {0, 1}) input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens) self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) @slow @require_torch_gpu @require_fp_quant @require_accelerate class FPQuantPseudoquantTest(unittest.TestCase): model_name = "unsloth/Llama-3.2-1B" input_text = "1 2 3 4" max_new_tokens = 4 EXPECTED_OUTPUT = "1 2 3 4 5 6" device_map = "cuda" # called only once for all test in this class @classmethod def setUpClass(cls): """ Setup quantized model """ quantization_config = FPQuantConfig(pseudoquantization=True) cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name) cls.quantized_model = AutoModelForCausalLM.from_pretrained( cls.model_name, device_map=cls.device_map, quantization_config=quantization_config ) def tearDown(self): gc.collect() backend_empty_cache(torch_device) gc.collect() def test_quantized_model(self): """ Simple test that checks if the quantized model is working properly """ input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) output = self.quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) def test_save_pretrained(self): """ Simple test that checks if the quantized model is working properly after being saved and loaded """ with tempfile.TemporaryDirectory() as tmpdirname: self.quantized_model.save_pretrained(tmpdirname) model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=self.device_map) input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens) self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) @require_torch_multi_gpu def test_quantized_model_multi_gpu(self): """ Simple test that checks if the quantized model is working properly with multiple GPUs set CUDA_VISIBLE_DEVICES=0,1 if you have more than 2 GPUs """ input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) quantization_config = FPQuantConfig(pseudoquantization=True) quantized_model = AutoModelForCausalLM.from_pretrained( self.model_name, device_map="auto", quantization_config=quantization_config ) self.assertTrue(set(quantized_model.hf_device_map.values()) == {0, 1}) output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) @require_torch_multi_gpu def test_save_pretrained_multi_gpu(self): """ Simple test that checks if the quantized model is working properly after being saved and loaded """ with tempfile.TemporaryDirectory() as tmpdirname: self.quantized_model.save_pretrained(tmpdirname) model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map="auto") self.assertTrue(set(model.hf_device_map.values()) == {0, 1}) input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens) self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT)
transformers/tests/quantization/fp_quant_integration/test_fp_quant.py/0
{ "file_path": "transformers/tests/quantization/fp_quant_integration/test_fp_quant.py", "repo_id": "transformers", "token_count": 3681 }
549
import argparse import logging import sys import time import tensorflow as tf from datasets import load_dataset from packaging.version import parse from transformers import AutoTokenizer, TFAutoModelForSequenceClassification try: import tf_keras as keras except (ModuleNotFoundError, ImportError): import keras if parse(keras.__version__).major > 2: raise ValueError( "Your currently installed version of Keras is Keras 3, but this is not yet supported in " "Transformers. Please install the backwards-compatible tf-keras package with " "`pip install tf-keras`." ) if __name__ == "__main__": parser = argparse.ArgumentParser() # Hyperparameters sent by the client are passed as command-line arguments to the script. parser.add_argument("--epochs", type=int, default=1) parser.add_argument("--per_device_train_batch_size", type=int, default=16) parser.add_argument("--per_device_eval_batch_size", type=int, default=8) parser.add_argument("--model_name_or_path", type=str) parser.add_argument("--learning_rate", type=str, default=5e-5) parser.add_argument("--do_train", type=bool, default=True) parser.add_argument("--do_eval", type=bool, default=True) parser.add_argument("--output_dir", type=str) args, _ = parser.parse_known_args() # overwrite batch size until we have tf_glue.py args.per_device_train_batch_size = 16 args.per_device_eval_batch_size = 16 # Set up logging logger = logging.getLogger(__name__) logging.basicConfig( level=logging.getLevelName("INFO"), handlers=[logging.StreamHandler(sys.stdout)], format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", ) # Load model and tokenizer model = TFAutoModelForSequenceClassification.from_pretrained(args.model_name_or_path) tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path) # Load dataset train_dataset, test_dataset = load_dataset("stanfordnlp/imdb", split=["train", "test"]) train_dataset = train_dataset.shuffle().select(range(5000)) # smaller the size for train dataset to 5k test_dataset = test_dataset.shuffle().select(range(500)) # smaller the size for test dataset to 500 # Preprocess train dataset train_dataset = train_dataset.map( lambda e: tokenizer(e["text"], truncation=True, padding="max_length"), batched=True ) train_dataset.set_format(type="tensorflow", columns=["input_ids", "attention_mask", "label"]) train_features = { x: train_dataset[x].to_tensor(default_value=0, shape=[None, tokenizer.model_max_length]) for x in ["input_ids", "attention_mask"] } tf_train_dataset = tf.data.Dataset.from_tensor_slices((train_features, train_dataset["label"])).batch( args.per_device_train_batch_size ) # Preprocess test dataset test_dataset = test_dataset.map( lambda e: tokenizer(e["text"], truncation=True, padding="max_length"), batched=True ) test_dataset.set_format(type="tensorflow", columns=["input_ids", "attention_mask", "label"]) test_features = { x: test_dataset[x].to_tensor(default_value=0, shape=[None, tokenizer.model_max_length]) for x in ["input_ids", "attention_mask"] } tf_test_dataset = tf.data.Dataset.from_tensor_slices((test_features, test_dataset["label"])).batch( args.per_device_eval_batch_size ) # fine optimizer and loss optimizer = keras.optimizers.Adam(learning_rate=args.learning_rate) loss = keras.losses.SparseCategoricalCrossentropy(from_logits=True) metrics = [keras.metrics.SparseCategoricalAccuracy()] model.compile(optimizer=optimizer, loss=loss, metrics=metrics) start_train_time = time.time() train_results = model.fit(tf_train_dataset, epochs=args.epochs, batch_size=args.per_device_train_batch_size) end_train_time = time.time() - start_train_time logger.info("*** Train ***") logger.info(f"train_runtime = {end_train_time}") for key, value in train_results.history.items(): logger.info(f" {key} = {value}")
transformers/tests/sagemaker/scripts/tensorflow/run_tf.py/0
{ "file_path": "transformers/tests/sagemaker/scripts/tensorflow/run_tf.py", "repo_id": "transformers", "token_count": 1582 }
550
# Copyright 2018 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 copy import unittest import numpy as np from transformers.data.data_collator import default_data_collator from transformers.testing_utils import require_accelerate, require_torch from transformers.trainer_utils import RemoveColumnsCollator, find_executable_batch_size from transformers.utils import is_torch_available if is_torch_available(): import torch from torch import nn from torch.utils.data import IterableDataset from transformers.modeling_outputs import SequenceClassifierOutput from transformers.tokenization_utils_base import BatchEncoding from transformers.trainer_pt_utils import ( DistributedLengthGroupedSampler, DistributedSamplerWithLoop, DistributedTensorGatherer, EvalLoopContainer, IterableDatasetShard, LabelSmoother, LengthGroupedSampler, SequentialDistributedSampler, ShardSampler, get_parameter_names, numpy_pad_and_concatenate, torch_pad_and_concatenate, ) class TstLayer(nn.Module): def __init__(self, hidden_size): super().__init__() self.linear1 = nn.Linear(hidden_size, hidden_size) self.ln1 = nn.LayerNorm(hidden_size) self.linear2 = nn.Linear(hidden_size, hidden_size) self.ln2 = nn.LayerNorm(hidden_size) self.bias = nn.Parameter(torch.zeros(hidden_size)) def forward(self, x): h = self.ln1(nn.functional.relu(self.linear1(x))) h = nn.functional.relu(self.linear2(x)) return self.ln2(x + h + self.bias) class RandomIterableDataset(IterableDataset): # For testing, an iterable dataset of random length def __init__(self, p_stop=0.01, max_length=1000): self.p_stop = p_stop self.max_length = max_length self.generator = torch.Generator() def __iter__(self): count = 0 stop = False while not stop and count < self.max_length: yield count count += 1 number = torch.rand(1, generator=self.generator).item() stop = number < self.p_stop @require_torch class TrainerUtilsTest(unittest.TestCase): def test_distributed_tensor_gatherer(self): # Simulate a result with a dataset of size 21, 4 processes and chunks of lengths 2, 3, 1 world_size = 4 num_samples = 21 input_indices = [ [0, 1, 6, 7, 12, 13, 18, 19], [2, 3, 4, 8, 9, 10, 14, 15, 16, 20, 0, 1], [5, 11, 17, 2], ] predictions = np.random.normal(size=(num_samples, 13)) gatherer = DistributedTensorGatherer(world_size=world_size, num_samples=num_samples) for indices in input_indices: gatherer.add_arrays(predictions[indices]) result = gatherer.finalize() self.assertTrue(np.array_equal(result, predictions)) # With nested tensors gatherer = DistributedTensorGatherer(world_size=world_size, num_samples=num_samples) for indices in input_indices: gatherer.add_arrays([predictions[indices], [predictions[indices], predictions[indices]]]) result = gatherer.finalize() self.assertTrue(isinstance(result, list)) self.assertEqual(len(result), 2) self.assertTrue(isinstance(result[1], list)) self.assertEqual(len(result[1]), 2) self.assertTrue(np.array_equal(result[0], predictions)) self.assertTrue(np.array_equal(result[1][0], predictions)) self.assertTrue(np.array_equal(result[1][1], predictions)) def test_distributed_tensor_gatherer_different_shapes(self): # Simulate a result with a dataset of size 21, 4 processes and chunks of lengths 2, 3, 1 world_size = 4 num_samples = 21 input_indices = [ [0, 1, 6, 7, 12, 13, 18, 19], [2, 3, 4, 8, 9, 10, 14, 15, 16, 20, 0, 1], [5, 11, 17, 2], ] sequence_lengths = [8, 10, 13] predictions = np.random.normal(size=(num_samples, 13)) gatherer = DistributedTensorGatherer(world_size=world_size, num_samples=num_samples) for indices, seq_length in zip(input_indices, sequence_lengths): gatherer.add_arrays(predictions[indices, :seq_length]) result = gatherer.finalize() # Remove the extra samples added at the end for a round multiple of num processes. actual_indices = [input_indices[0], input_indices[1][:-2], input_indices[2][:-1]] for indices, seq_length in zip(actual_indices, sequence_lengths): self.assertTrue(np.array_equal(result[indices, :seq_length], predictions[indices, :seq_length])) # With nested tensors predictions = np.random.normal(size=(num_samples, 13)) gatherer = DistributedTensorGatherer(world_size=world_size, num_samples=num_samples) for indices, seq_length in zip(input_indices, sequence_lengths): gatherer.add_arrays([predictions[indices, :seq_length], predictions[indices]]) result = gatherer.finalize() for indices, seq_length in zip(actual_indices, sequence_lengths): self.assertTrue(np.array_equal(result[0][indices, :seq_length], predictions[indices, :seq_length])) self.assertTrue(np.array_equal(result[1], predictions)) # Check if works if varying seq_length is second gatherer = DistributedTensorGatherer(world_size=world_size, num_samples=num_samples) for indices, seq_length in zip(input_indices, sequence_lengths): gatherer.add_arrays([predictions[indices], predictions[indices, :seq_length]]) result = gatherer.finalize() self.assertTrue(np.array_equal(result[0], predictions)) for indices, seq_length in zip(actual_indices, sequence_lengths): self.assertTrue(np.array_equal(result[1][indices, :seq_length], predictions[indices, :seq_length])) def test_label_smoothing(self): epsilon = 0.1 num_labels = 12 random_logits = torch.randn(4, 5, num_labels) random_labels = torch.randint(0, num_labels, (4, 5)) loss = nn.functional.cross_entropy(random_logits.view(-1, num_labels), random_labels.view(-1)) model_output = SequenceClassifierOutput(logits=random_logits) label_smoothed_loss = LabelSmoother(0.1)(model_output, random_labels) log_probs = -nn.functional.log_softmax(random_logits, dim=-1) expected_loss = (1 - epsilon) * loss + epsilon * log_probs.mean() torch.testing.assert_close(label_smoothed_loss, expected_loss) # With a few -100 labels random_labels[0, 1] = -100 random_labels[2, 1] = -100 random_labels[2, 3] = -100 loss = nn.functional.cross_entropy(random_logits.view(-1, num_labels), random_labels.view(-1)) model_output = SequenceClassifierOutput(logits=random_logits) label_smoothed_loss = LabelSmoother(0.1)(model_output, random_labels) log_probs = -nn.functional.log_softmax(random_logits, dim=-1) # Mask the log probs with the -100 labels log_probs[0, 1] = 0.0 log_probs[2, 1] = 0.0 log_probs[2, 3] = 0.0 expected_loss = (1 - epsilon) * loss + epsilon * log_probs.sum() / (num_labels * 17) torch.testing.assert_close(label_smoothed_loss, expected_loss) def test_group_by_length(self): # Get some inputs of random lengths lengths = torch.randint(0, 25, (100,)).tolist() # Put one bigger than the others to check it ends up in first position lengths[32] = 50 indices = list(LengthGroupedSampler(4, lengths=lengths)) # The biggest element should be first self.assertEqual(lengths[indices[0]], 50) # The indices should be a permutation of range(100) self.assertEqual(sorted(indices), list(range(100))) def test_group_by_length_with_dict(self): # Get some inputs of random lengths data = [] for _ in range(6): input_ids = torch.randint(0, 25, (100,)).tolist() data.append({"input_ids": input_ids}) # Put one bigger than the others to check it ends up in first position data[3]["input_ids"] = torch.randint(0, 25, (105,)).tolist() indices = list(LengthGroupedSampler(4, dataset=data)) # The biggest element should be first self.assertEqual(len(data[indices[0]]["input_ids"]), 105) # The indices should be a permutation of range(6) self.assertEqual(sorted(indices), list(range(6))) def test_group_by_length_with_batch_encoding(self): # Get some inputs of random lengths data = [] for _ in range(6): input_ids = torch.randint(0, 25, (100,)).tolist() data.append(BatchEncoding({"input_ids": input_ids})) # Put one bigger than the others to check it ends up in first position data[3]["input_ids"] = torch.randint(0, 25, (105,)).tolist() indices = list(LengthGroupedSampler(4, dataset=data)) # The biggest element should be first self.assertEqual(len(data[indices[0]]["input_ids"]), 105) # The indices should be a permutation of range(6) self.assertEqual(sorted(indices), list(range(6))) def test_distributed_length_grouped(self): # Get some inputs of random lengths lengths = torch.randint(0, 25, (100,)).tolist() # Put one bigger than the others to check it ends up in first position lengths[32] = 50 indices_process_0 = list(DistributedLengthGroupedSampler(4, num_replicas=2, rank=0, lengths=lengths)) indices_process_1 = list(DistributedLengthGroupedSampler(4, num_replicas=2, rank=1, lengths=lengths)) # The biggest element should be first self.assertEqual(lengths[indices_process_0[0]], 50) # The indices should be a permutation of range(100) self.assertEqual(sorted(indices_process_0 + indices_process_1), list(range(100))) def test_get_parameter_names(self): model = nn.Sequential(TstLayer(128), nn.ModuleList([TstLayer(128), TstLayer(128)])) # fmt: off self.assertEqual( get_parameter_names(model, [nn.LayerNorm]), ['0.linear1.weight', '0.linear1.bias', '0.linear2.weight', '0.linear2.bias', '0.bias', '1.0.linear1.weight', '1.0.linear1.bias', '1.0.linear2.weight', '1.0.linear2.bias', '1.0.bias', '1.1.linear1.weight', '1.1.linear1.bias', '1.1.linear2.weight', '1.1.linear2.bias', '1.1.bias'] ) # fmt: on def test_get_parameter_names_rmsnorm(self): class RMSNorm(nn.Module): def __init__(self, hidden_size): super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.bias = nn.Parameter(torch.zeros(hidden_size)) class ModelWithRMSNorm(nn.Module): def __init__(self): super().__init__() self.linear = nn.Linear(128, 128) self.rmsnorm = RMSNorm(128) self.bias = nn.Parameter(torch.zeros(128)) model = ModelWithRMSNorm() # Test both type-based and name-based filtering decay_parameters = get_parameter_names(model, [], ["bias", "rmsnorm"]) # Parameters that should be in weight decay self.assertIn("linear.weight", decay_parameters) # Parameters that should NOT be in weight decay self.assertNotIn("linear.bias", decay_parameters) self.assertNotIn("rmsnorm.weight", decay_parameters) self.assertNotIn("rmsnorm.bias", decay_parameters) self.assertNotIn("bias", decay_parameters) def test_distributed_sampler_with_loop(self): batch_size = 16 for length in [23, 64, 123]: dataset = list(range(length)) shard1 = DistributedSamplerWithLoop(dataset, batch_size, num_replicas=2, rank=0) shard2 = DistributedSamplerWithLoop(dataset, batch_size, num_replicas=2, rank=1) # Set seeds shard1.set_epoch(0) shard2.set_epoch(0) # Sample samples1 = list(shard1) samples2 = list(shard2) self.assertTrue(len(samples1) % batch_size == 0) self.assertTrue(len(samples2) % batch_size == 0) total = [] for sample1, sample2 in zip(samples1, samples2): total += [sample1, sample2] self.assertEqual(set(total[:length]), set(dataset)) self.assertEqual(set(total[length:]), set(total[: (len(total) - length)])) def test_sequential_distributed_sampler(self): batch_size = 16 for length in [23, 64, 123]: dataset = list(range(length)) shard1 = SequentialDistributedSampler(dataset, num_replicas=2, rank=0) shard2 = SequentialDistributedSampler(dataset, num_replicas=2, rank=1) # Sample samples1 = list(shard1) samples2 = list(shard2) total = samples1 + samples2 self.assertListEqual(total[:length], dataset) self.assertListEqual(total[length:], dataset[: (len(total) - length)]) # With a batch_size passed shard1 = SequentialDistributedSampler(dataset, num_replicas=2, rank=0, batch_size=batch_size) shard2 = SequentialDistributedSampler(dataset, num_replicas=2, rank=1, batch_size=batch_size) # Sample samples1 = list(shard1) samples2 = list(shard2) self.assertTrue(len(samples1) % batch_size == 0) self.assertTrue(len(samples2) % batch_size == 0) total = samples1 + samples2 self.assertListEqual(total[:length], dataset) self.assertListEqual(total[length:], dataset[: (len(total) - length)]) def check_iterable_dataset_shard(self, dataset, batch_size, drop_last, num_processes=2, epoch=0): # Set the seed for the base dataset to get the proper reference. dataset.generator.manual_seed(epoch) reference = list(dataset) shards = [ IterableDatasetShard( dataset, batch_size=batch_size, drop_last=drop_last, num_processes=num_processes, process_index=i ) for i in range(num_processes) ] for shard in shards: shard.set_epoch(epoch) shard_lists = [list(shard) for shard in shards] for shard in shard_lists: # All shards have a number of samples that is a round multiple of batch size self.assertTrue(len(shard) % batch_size == 0) # All shards have the same number of samples self.assertEqual(len(shard), len(shard_lists[0])) for shard in shards: # All shards know the total number of samples self.assertEqual(shard.num_examples, len(reference)) observed = [] for idx in range(0, len(shard_lists[0]), batch_size): for shard in shard_lists: observed += shard[idx : idx + batch_size] # If drop_last is False we loop through samples at the beginning to have a size that is a round multiple of # batch_size if not drop_last: while len(reference) < len(observed): reference += reference self.assertListEqual(observed, reference[: len(observed)]) # Check equivalence between IterableDataset and ShardSampler dataset.generator.manual_seed(epoch) reference = list(dataset) sampler_shards = [ ShardSampler( reference, batch_size=batch_size, drop_last=drop_last, num_processes=num_processes, process_index=i ) for i in range(num_processes) ] for shard, sampler_shard in zip(shard_lists, sampler_shards): self.assertListEqual(shard, list(sampler_shard)) def test_iterable_dataset_shard(self): dataset = RandomIterableDataset() self.check_iterable_dataset_shard(dataset, 4, drop_last=True, num_processes=2, epoch=0) self.check_iterable_dataset_shard(dataset, 4, drop_last=False, num_processes=2, epoch=0) self.check_iterable_dataset_shard(dataset, 4, drop_last=True, num_processes=3, epoch=42) self.check_iterable_dataset_shard(dataset, 4, drop_last=False, num_processes=3, epoch=42) def test_iterable_dataset_shard_with_length(self): sampler_shards = [ IterableDatasetShard(list(range(100)), batch_size=4, drop_last=True, num_processes=2, process_index=i) for i in range(2) ] # Build expected shards: each process will have batches of size 4 until there is not enough elements to # form two full batches (so we stop at 96 = (100 // (4 * 2)) * 4) expected_shards = [[], []] current_shard = 0 for i in range(0, 96, 4): expected_shards[current_shard].extend(list(range(i, i + 4))) current_shard = 1 - current_shard self.assertListEqual([list(shard) for shard in sampler_shards], expected_shards) self.assertListEqual([len(shard) for shard in sampler_shards], [len(shard) for shard in expected_shards]) sampler_shards = [ IterableDatasetShard(list(range(100)), batch_size=4, drop_last=False, num_processes=2, process_index=i) for i in range(2) ] # When drop_last=False, we get two last full batches by looping back to the beginning. expected_shards[0].extend(list(range(96, 100))) expected_shards[1].extend(list(range(0, 4))) self.assertListEqual([list(shard) for shard in sampler_shards], expected_shards) self.assertListEqual([len(shard) for shard in sampler_shards], [len(shard) for shard in expected_shards]) def check_shard_sampler(self, dataset, batch_size, drop_last, num_processes=2): shards = [ ShardSampler( dataset, batch_size=batch_size, drop_last=drop_last, num_processes=num_processes, process_index=i ) for i in range(num_processes) ] shard_lists = [list(shard) for shard in shards] for shard in shard_lists: # All shards have a number of samples that is a round multiple of batch size self.assertTrue(len(shard) % batch_size == 0) # All shards have the same number of samples self.assertEqual(len(shard), len(shard_lists[0])) observed = [] for idx in range(0, len(shard_lists[0]), batch_size): for shard in shard_lists: observed += shard[idx : idx + batch_size] # If drop_last is False we loop through samples at the beginning to have a size that is a round multiple of # batch_size reference = copy.copy(dataset) if not drop_last: while len(reference) < len(observed): reference += reference self.assertListEqual(observed, reference[: len(observed)]) def test_shard_sampler(self): for n_elements in [64, 123]: dataset = list(range(n_elements)) self.check_shard_sampler(dataset, 4, drop_last=True, num_processes=2) self.check_shard_sampler(dataset, 4, drop_last=False, num_processes=2) self.check_shard_sampler(dataset, 4, drop_last=True, num_processes=3) self.check_shard_sampler(dataset, 4, drop_last=False, num_processes=3) @require_accelerate def test_executable_batch_size(self): batch_sizes = [] @find_executable_batch_size(starting_batch_size=64, auto_find_batch_size=True) def mock_training_loop_function(batch_size): nonlocal batch_sizes batch_sizes.append(batch_size) if batch_size > 16: raise RuntimeError("CUDA out of memory.") mock_training_loop_function() self.assertEqual(batch_sizes, [64, 57, 51, 45, 40, 36, 32, 28, 25, 22, 19, 17, 15]) @require_accelerate def test_executable_batch_size_no_search(self): batch_sizes = [] @find_executable_batch_size(starting_batch_size=64, auto_find_batch_size=False) def mock_training_loop_function(batch_size): nonlocal batch_sizes batch_sizes.append(batch_size) mock_training_loop_function() self.assertEqual(batch_sizes, [64]) @require_accelerate def test_executable_batch_size_with_error(self): @find_executable_batch_size(starting_batch_size=64, auto_find_batch_size=False) def mock_training_loop_function(batch_size): raise RuntimeError("CUDA out of memory.") with self.assertRaises(RuntimeError) as cm: mock_training_loop_function() self.assertEqual("CUDA out of memory", cm.args[0]) def test_pad_and_concatenate_with_1d(self): """Tests whether pad_and_concatenate works with scalars.""" array1 = 1.0 array2 = 2.0 result = numpy_pad_and_concatenate(array1, array2) self.assertTrue(np.array_equal(np.array([1.0, 2.0]), result)) tensor1 = torch.tensor(1.0) tensor2 = torch.tensor(2.0) result = torch_pad_and_concatenate(tensor1, tensor2) self.assertTrue(torch.equal(result, torch.Tensor([1.0, 2.0]))) def test_remove_columns_collator(self): class MockLogger: def __init__(self) -> None: self.called = 0 def info(self, msg): self.called += 1 self.last_msg = msg data_batch = [ {"col1": 1, "col2": 2, "col3": 3}, {"col1": 1, "col2": 2, "col3": 3}, ] logger = MockLogger() remove_columns_collator = RemoveColumnsCollator( default_data_collator, ["col1", "col2"], logger, "model", "training" ) self.assertNotIn("col3", remove_columns_collator(data_batch)) # check that the logging message is printed out only once remove_columns_collator(data_batch) remove_columns_collator(data_batch) self.assertEqual(logger.called, 1) self.assertIn("col3", logger.last_msg) def test_eval_loop_container(self): batch_1 = [ torch.ones([8, 5]), {"loss": torch.tensor(1.0)}, (torch.ones([8, 2, 3]), torch.ones([8, 2])), ] batch_2 = [ torch.ones([4, 5]), {"loss": torch.tensor(2.0)}, (torch.ones([4, 2, 3]), torch.ones([4, 6])), ] concat_container = EvalLoopContainer(do_nested_concat=True, padding_index=-100) concat_container.add(batch_1) concat_container.add(batch_2) concat_container.to_cpu_and_numpy() arrays = concat_container.get_arrays() # Test two nested batches concatenation self.assertIsInstance(arrays, list) self.assertEqual(len(arrays), 3) self.assertIsInstance(arrays[0], np.ndarray) self.assertEqual(arrays[0].shape, (12, 5)) self.assertIsInstance(arrays[1], dict) self.assertIsInstance(arrays[1]["loss"], np.ndarray) self.assertEqual(arrays[1]["loss"].shape, (2,)) self.assertTrue(np.allclose(arrays[1]["loss"], np.array([1.0, 2.0]))) self.assertIsInstance(arrays[2], tuple) self.assertEqual(len(arrays[2]), 2) self.assertEqual(arrays[2][0].shape, (12, 2, 3)) self.assertEqual(arrays[2][1].shape, (12, 6)) # check that first batch padded with padding index -100 after concatenation self.assertEqual(arrays[2][1][0][2], -100) # Test two batches with no concatenation list_container = EvalLoopContainer(do_nested_concat=False) list_container.add(batch_1) list_container.add(batch_2) list_container.to_cpu_and_numpy() arrays = list_container.get_arrays() self.assertEqual(len(arrays), 2) self.assertIsInstance(arrays, list) np_batch_1, np_batch_2 = arrays self.assertIsInstance(np_batch_1, list) self.assertEqual(len(np_batch_1), 3) self.assertIsInstance(np_batch_1[0], np.ndarray) self.assertIsInstance(np_batch_1[1], dict) self.assertIsInstance(np_batch_1[2], tuple) self.assertEqual(np_batch_1[0].shape, (8, 5)) self.assertEqual(np_batch_1[1]["loss"].shape, ()) self.assertEqual(np_batch_1[2][0].shape, (8, 2, 3)) self.assertEqual(np_batch_1[2][1].shape, (8, 2)) self.assertIsInstance(np_batch_2, list) self.assertEqual(len(np_batch_2), 3) self.assertIsInstance(np_batch_2[0], np.ndarray) self.assertIsInstance(np_batch_2[1], dict) self.assertIsInstance(np_batch_2[2], tuple) self.assertEqual(np_batch_2[0].shape, (4, 5)) self.assertEqual(np_batch_2[1]["loss"].shape, ()) self.assertEqual(np_batch_2[2][0].shape, (4, 2, 3)) self.assertEqual(np_batch_2[2][1].shape, (4, 6)) # Test no batches none_arr = EvalLoopContainer(do_nested_concat=True, padding_index=-100).get_arrays() self.assertIsNone(none_arr) none_arr = EvalLoopContainer(do_nested_concat=False).get_arrays() self.assertIsNone(none_arr) # Test one batch concat_container = EvalLoopContainer(do_nested_concat=True, padding_index=-100) concat_container.add(batch_1) arrays = concat_container.get_arrays() self.assertIsInstance(arrays, list) self.assertEqual(len(arrays), 3) self.assertIsInstance(arrays[0], np.ndarray) self.assertEqual(arrays[0].shape, (8, 5)) self.assertIsInstance(arrays[1], dict) self.assertIsInstance(arrays[1]["loss"], np.ndarray) self.assertEqual(arrays[1]["loss"].shape, ()) self.assertTrue(np.allclose(arrays[1]["loss"], np.array([1.0]))) self.assertIsInstance(arrays[2], tuple) self.assertEqual(len(arrays[2]), 2) self.assertEqual(arrays[2][0].shape, (8, 2, 3)) self.assertEqual(arrays[2][1].shape, (8, 2))
transformers/tests/trainer/test_trainer_utils.py/0
{ "file_path": "transformers/tests/trainer/test_trainer_utils.py", "repo_id": "transformers", "token_count": 12038 }
551
# Copyright 2019 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 json import os import shutil import sys import tempfile import unittest import unittest.mock as mock import warnings from pathlib import Path from huggingface_hub import HfFolder from requests.exceptions import HTTPError from transformers import AutoConfig, BertConfig, Florence2Config, GPT2Config from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import TOKEN, TemporaryHubRepo, is_staging_test, require_torch sys.path.append(str(Path(__file__).parent.parent.parent / "utils")) from test_module.custom_configuration import CustomConfig # noqa E402 config_common_kwargs = { "return_dict": False, "output_hidden_states": True, "output_attentions": True, "torchscript": True, "dtype": "float16", "use_bfloat16": True, "tf_legacy_loss": True, "pruned_heads": {"a": 1}, "tie_word_embeddings": False, "is_decoder": True, "cross_attention_hidden_size": 128, "add_cross_attention": True, "tie_encoder_decoder": True, "max_length": 50, "min_length": 3, "do_sample": True, "early_stopping": True, "num_beams": 3, "num_beam_groups": 3, "diversity_penalty": 0.5, "temperature": 2.0, "top_k": 10, "top_p": 0.7, "typical_p": 0.2, "repetition_penalty": 0.8, "length_penalty": 0.8, "no_repeat_ngram_size": 5, "encoder_no_repeat_ngram_size": 5, "bad_words_ids": [1, 2, 3], "num_return_sequences": 3, "chunk_size_feed_forward": 5, "output_scores": True, "return_dict_in_generate": True, "forced_bos_token_id": 2, "forced_eos_token_id": 3, "remove_invalid_values": True, "architectures": ["BertModel"], "finetuning_task": "translation", "id2label": {0: "label"}, "label2id": {"label": "0"}, "tokenizer_class": "BertTokenizerFast", "prefix": "prefix", "bos_token_id": 6, "pad_token_id": 7, "eos_token_id": 8, "sep_token_id": 9, "decoder_start_token_id": 10, "exponential_decay_length_penalty": (5, 1.01), "suppress_tokens": [0, 1], "begin_suppress_tokens": 2, "task_specific_params": {"translation": "some_params"}, "problem_type": "regression", } @is_staging_test class ConfigPushToHubTester(unittest.TestCase): @classmethod def setUpClass(cls): cls._token = TOKEN HfFolder.save_token(TOKEN) def test_push_to_hub(self): with TemporaryHubRepo(token=self._token) as tmp_repo: config = BertConfig( vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 ) config.push_to_hub(tmp_repo.repo_id, token=self._token) new_config = BertConfig.from_pretrained(tmp_repo.repo_id) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(v, getattr(new_config, k)) def test_push_to_hub_via_save_pretrained(self): with TemporaryHubRepo(token=self._token) as tmp_repo: config = BertConfig( vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(tmp_dir, repo_id=tmp_repo.repo_id, push_to_hub=True, token=self._token) new_config = BertConfig.from_pretrained(tmp_repo.repo_id) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(v, getattr(new_config, k)) def test_push_to_hub_in_organization(self): with TemporaryHubRepo(namespace="valid_org", token=self._token) as tmp_repo: config = BertConfig( vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 ) config.push_to_hub(tmp_repo.repo_id, token=self._token) new_config = BertConfig.from_pretrained(tmp_repo.repo_id) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(v, getattr(new_config, k)) def test_push_to_hub_in_organization_via_save_pretrained(self): with TemporaryHubRepo(namespace="valid_org", token=self._token) as tmp_repo: config = BertConfig( vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(tmp_dir, repo_id=tmp_repo.repo_id, push_to_hub=True, token=self._token) new_config = BertConfig.from_pretrained(tmp_repo.repo_id) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(v, getattr(new_config, k)) def test_push_to_hub_dynamic_config(self): with TemporaryHubRepo(token=self._token) as tmp_repo: CustomConfig.register_for_auto_class() config = CustomConfig(attribute=42) config.push_to_hub(tmp_repo.repo_id, token=self._token) # This has added the proper auto_map field to the config self.assertDictEqual(config.auto_map, {"AutoConfig": "custom_configuration.CustomConfig"}) new_config = AutoConfig.from_pretrained(tmp_repo.repo_id, trust_remote_code=True) # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module self.assertEqual(new_config.__class__.__name__, "CustomConfig") self.assertEqual(new_config.attribute, 42) class ConfigTestUtils(unittest.TestCase): def test_config_from_string(self): c = GPT2Config() # attempt to modify each of int/float/bool/str config records and verify they were updated n_embd = c.n_embd + 1 # int resid_pdrop = c.resid_pdrop + 1.0 # float scale_attn_weights = not c.scale_attn_weights # bool summary_type = c.summary_type + "foo" # str c.update_from_string( f"n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}" ) self.assertEqual(n_embd, c.n_embd, "mismatch for key: n_embd") self.assertEqual(resid_pdrop, c.resid_pdrop, "mismatch for key: resid_pdrop") self.assertEqual(scale_attn_weights, c.scale_attn_weights, "mismatch for key: scale_attn_weights") self.assertEqual(summary_type, c.summary_type, "mismatch for key: summary_type") def test_config_common_kwargs_is_complete(self): base_config = PretrainedConfig() missing_keys = [key for key in base_config.__dict__ if key not in config_common_kwargs] # If this part of the test fails, you have arguments to add in config_common_kwargs above. self.assertListEqual( missing_keys, [ "_output_attentions", "is_encoder_decoder", "_name_or_path", "_commit_hash", "_attn_implementation_internal", "transformers_version", ], ) keys_with_defaults = [key for key, value in config_common_kwargs.items() if value == getattr(base_config, key)] if len(keys_with_defaults) > 0: raise ValueError( "The following keys are set with the default values in" " `test_configuration_common.config_common_kwargs` pick another value for them:" f" {', '.join(keys_with_defaults)}." ) def test_nested_config_load_from_dict(self): config = AutoConfig.from_pretrained( "hf-internal-testing/tiny-random-CLIPModel", text_config={"num_hidden_layers": 2} ) self.assertNotIsInstance(config.text_config, dict) self.assertEqual(config.text_config.__class__.__name__, "CLIPTextConfig") def test_from_pretrained_subfolder(self): config = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder") self.assertIsNotNone(config) config = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder", subfolder="bert") self.assertIsNotNone(config) def test_cached_files_are_used_when_internet_is_down(self): # A mock response for an HTTP head request to emulate server down response_mock = mock.Mock() response_mock.status_code = 500 response_mock.headers = {} response_mock.raise_for_status.side_effect = HTTPError response_mock.json.return_value = {} # Download this model to make sure it's in the cache. _ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert") # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch("requests.Session.request", return_value=response_mock) as mock_head: _ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert") # This check we did call the fake head request mock_head.assert_called() def test_local_versioning(self): configuration = AutoConfig.from_pretrained("google-bert/bert-base-cased") configuration.configuration_files = ["config.4.0.0.json"] with tempfile.TemporaryDirectory() as tmp_dir: configuration.save_pretrained(tmp_dir) configuration.hidden_size = 2 json.dump(configuration.to_dict(), open(os.path.join(tmp_dir, "config.4.0.0.json"), "w")) # This should pick the new configuration file as the version of Transformers is > 4.0.0 new_configuration = AutoConfig.from_pretrained(tmp_dir) self.assertEqual(new_configuration.hidden_size, 2) # Will need to be adjusted if we reach v42 and this test is still here. # Should pick the old configuration file as the version of Transformers is < 4.42.0 configuration.configuration_files = ["config.42.0.0.json"] configuration.hidden_size = 768 configuration.save_pretrained(tmp_dir) shutil.move(os.path.join(tmp_dir, "config.4.0.0.json"), os.path.join(tmp_dir, "config.42.0.0.json")) new_configuration = AutoConfig.from_pretrained(tmp_dir) self.assertEqual(new_configuration.hidden_size, 768) def test_repo_versioning_before(self): # This repo has two configuration files, one for v4.0.0 and above with a different hidden size. repo = "hf-internal-testing/test-two-configs" import transformers as new_transformers new_transformers.configuration_utils.__version__ = "v4.0.0" new_configuration, kwargs = new_transformers.models.auto.AutoConfig.from_pretrained( repo, return_unused_kwargs=True ) self.assertEqual(new_configuration.hidden_size, 2) # This checks `_configuration_file` ia not kept in the kwargs by mistake. self.assertDictEqual(kwargs, {}) # Testing an older version by monkey-patching the version in the module it's used. import transformers as old_transformers old_transformers.configuration_utils.__version__ = "v3.0.0" old_configuration = old_transformers.models.auto.AutoConfig.from_pretrained(repo) self.assertEqual(old_configuration.hidden_size, 768) def test_saving_config_with_custom_generation_kwargs_raises_warning(self): config = BertConfig(min_length=3) # `min_length = 3` is a non-default generation kwarg with tempfile.TemporaryDirectory() as tmp_dir: with self.assertWarns(UserWarning) as cm: config.save_pretrained(tmp_dir) self.assertIn("min_length", str(cm.warning)) def test_get_non_default_generation_parameters(self): config = BertConfig() self.assertFalse(len(config._get_non_default_generation_parameters()) > 0) config = BertConfig(min_length=3) self.assertTrue(len(config._get_non_default_generation_parameters()) > 0) config = BertConfig(min_length=0) # `min_length = 0` is a default generation kwarg self.assertFalse(len(config._get_non_default_generation_parameters()) > 0) def test_loading_config_do_not_raise_future_warnings(self): """Regression test for https://github.com/huggingface/transformers/issues/31002.""" # Loading config should not raise a FutureWarning. It was the case before. with warnings.catch_warnings(): warnings.simplefilter("error") PretrainedConfig.from_pretrained("bert-base-uncased") def test_get_text_config(self): """Tests the `get_text_config` method.""" # 1. model with only text input -> returns the original config instance config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-LlamaForCausalLM") self.assertEqual(config.get_text_config(), config) self.assertEqual(config.get_text_config(decoder=True), config) # 2. composite model (VLM) -> returns the text component config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-LlavaForConditionalGeneration") self.assertEqual(config.get_text_config(), config.text_config) self.assertEqual(config.get_text_config(decoder=True), config.text_config) # 3. ! corner case! : composite model whose sub-config is an old composite model (should behave as above) config = Florence2Config() self.assertEqual(config.get_text_config(), config.text_config) self.assertEqual(config.get_text_config(decoder=True), config.text_config) # 4. old composite model -> may remove components based on the `decoder` or `encoder` argument config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-bart") self.assertEqual(config.get_text_config(), config) # both encoder_layers and decoder_layers exist self.assertTrue(getattr(config, "encoder_layers", None) is not None) self.assertTrue(getattr(config, "decoder_layers", None) is not None) decoder_config = config.get_text_config(decoder=True) self.assertNotEqual(decoder_config, config) self.assertEqual(decoder_config.num_hidden_layers, config.decoder_layers) self.assertTrue(getattr(decoder_config, "encoder_layers", None) is None) # encoder_layers is removed encoder_config = config.get_text_config(encoder=True) self.assertNotEqual(encoder_config, config) self.assertEqual(encoder_config.num_hidden_layers, config.encoder_layers) self.assertTrue(getattr(encoder_config, "decoder_layers", None) is None) # decoder_layers is removed @require_torch def test_bc_torch_dtype(self): import torch config = PretrainedConfig(dtype="bfloat16") self.assertEqual(config.dtype, torch.bfloat16) config = PretrainedConfig(torch_dtype="bfloat16") self.assertEqual(config.dtype, torch.bfloat16) # Check that if we pass both, `dtype` is used config = PretrainedConfig(dtype="bfloat16", torch_dtype="float32") self.assertEqual(config.dtype, torch.bfloat16) with tempfile.TemporaryDirectory() as tmpdirname: config.save_pretrained(tmpdirname) config = PretrainedConfig.from_pretrained(tmpdirname) self.assertEqual(config.dtype, torch.bfloat16) config = PretrainedConfig.from_pretrained(tmpdirname, dtype="float32") self.assertEqual(config.dtype, "float32") config = PretrainedConfig.from_pretrained(tmpdirname, torch_dtype="float32") self.assertEqual(config.dtype, "float32")
transformers/tests/utils/test_configuration_utils.py/0
{ "file_path": "transformers/tests/utils/test_configuration_utils.py", "repo_id": "transformers", "token_count": 6905 }
552
# 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 from transformers.testing_utils import is_torch_available, require_torch if is_torch_available(): import torch from torch.nn.attention.flex_attention import create_block_mask from transformers import DynamicCache, LlamaConfig from transformers.cache_utils import DynamicSlidingWindowLayer from transformers.masking_utils import create_causal_mask, create_chunked_causal_mask, find_packed_sequence_indices # fmt: off EXPECTED_PACKED_MASK = torch.tensor([[[ [ True, False, False, False, False, False, False, False, False, False], [ True, True, False, False, False, False, False, False, False, False], [ True, True, True, False, False, False, False, False, False, False], [ True, True, True, True, False, False, False, False, False, False], [False, False, False, False, True, False, False, False, False, False], [False, False, False, False, True, True, False, False, False, False], [False, False, False, False, False, False, True, False, False, False], [False, False, False, False, False, False, True, True, False, False], [False, False, False, False, False, False, True, True, True, False], [False, False, False, False, False, False, True, True, True, True]]], [[[ True, False, False, False, False, False, False, False, False, False], [ True, True, False, False, False, False, False, False, False, False], [ True, True, True, False, False, False, False, False, False, False], [ True, True, True, True, False, False, False, False, False, False], [ True, True, True, True, True, False, False, False, False, False], [ True, True, True, True, True, True, False, False, False, False], [False, False, False, False, False, False, True, False, False, False], [False, False, False, False, False, False, True, True, False, False], [False, False, False, False, False, False, True, True, True, False], [False, False, False, False, False, False, True, True, True, True] ]]], dtype=torch.bool) # fmt: on @require_torch class MaskTest(unittest.TestCase): def test_packed_sequence_mask_sdpa(self): config = LlamaConfig() config._attn_implementation = "sdpa" batch_size = 2 sequence_length = 10 cache_position = torch.arange(sequence_length) # First batch has 3 packed sequences of 4, 2 and 4 tokens respectively, second has 2 of 6 and 4 tokens position_ids = torch.tensor([[0, 1, 2, 3, 0, 1, 0, 1, 2, 3], [0, 1, 2, 3, 4, 5, 0, 1, 2, 3]]) causal_mask = create_causal_mask( config=config, # we only need batch size, seq_length and dtype here - we don't care about the values of the embeddings input_embeds=torch.empty((batch_size, sequence_length), dtype=torch.float16), attention_mask=None, cache_position=cache_position, past_key_values=None, position_ids=position_ids, ) self.assertTrue((causal_mask == EXPECTED_PACKED_MASK).all()) def test_packed_sequence_mask_eager(self): config = LlamaConfig() config._attn_implementation = "eager" batch_size = 2 sequence_length = 10 cache_position = torch.arange(sequence_length) # First batch has 3 packed sequences of 4, 2 and 4 tokens respectively, second has 2 of 6 and 4 tokens position_ids = torch.tensor([[0, 1, 2, 3, 0, 1, 0, 1, 2, 3], [0, 1, 2, 3, 4, 5, 0, 1, 2, 3]]) causal_mask = create_causal_mask( config=config, # we only need batch size, seq_length and dtype here - we don't care about the values of the embeddings input_embeds=torch.empty((batch_size, sequence_length), dtype=torch.float16), attention_mask=None, cache_position=cache_position, past_key_values=None, position_ids=position_ids, ) min_dtype = torch.finfo(torch.float16).min self.assertTrue((causal_mask == torch.where(EXPECTED_PACKED_MASK, 0.0, min_dtype)).all()) def test_packed_sequence_mask_flex_attention(self): config = LlamaConfig() config._attn_implementation = "flex_attention" batch_size = 2 sequence_length = 10 cache_position = torch.arange(sequence_length) # First batch has 3 packed sequences of 4, 2 and 4 tokens respectively, second has 2 of 6 and 4 tokens position_ids = torch.tensor([[0, 1, 2, 3, 0, 1, 0, 1, 2, 3], [0, 1, 2, 3, 4, 5, 0, 1, 2, 3]]) causal_mask = create_causal_mask( config=config, # we only need batch size, seq_length and dtype here - we don't care about the values of the embeddings input_embeds=torch.empty((batch_size, sequence_length), dtype=torch.float16), attention_mask=None, cache_position=cache_position, past_key_values=None, position_ids=position_ids, ) def dummy_mask_mod(b, h, q, kv): return EXPECTED_PACKED_MASK[b, h, q, kv] EXPECTED_BLOCK_MASK = create_block_mask(dummy_mask_mod, 2, None, 10, 10, device="cpu") # We compatre the str representations, as the BlockMask objects themselves cannot easily be compared self.assertEqual(causal_mask.to_string(), EXPECTED_BLOCK_MASK.to_string()) def test_find_packed_sequence_indices(self): position_ids = torch.tensor([[0, 1, 2, 3, 0, 1, 0, 1, 2, 3], [0, 1, 2, 3, 4, 5, 0, 1, 2, 3]]) EXPECTED_SEQUENCE_INDICES = torch.tensor([[0, 0, 0, 0, 1, 1, 2, 2, 2, 2], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1]]) self.assertTrue((find_packed_sequence_indices(position_ids) == EXPECTED_SEQUENCE_INDICES).all()) def test_chunked_mask_with_left_padding_and_large_prefill(self): # Make sur we have an attention_chunk_size in the config config = LlamaConfig(attention_chunk_size=3, attn_implementation="sdpa") batch_size = 2 sequence_length = 8 pad_tokens = 4 input_ids = torch.randint(100, 200, (batch_size, sequence_length)) attention_mask = torch.tensor( [[0 if i < pad_tokens else 1 for i in range(sequence_length)], [1] * sequence_length] ) inputs_embeds = torch.empty_like(input_ids, dtype=torch.float16) cache_position = torch.arange(sequence_length) position_ids = torch.empty(batch_size, sequence_length, dtype=cache_position.dtype) position_ids[0, :pad_tokens] = 1 position_ids[0, pad_tokens:] = torch.arange(sequence_length - pad_tokens) position_ids[1, :] = cache_position chunked_attention_mask = create_chunked_causal_mask( config=config, input_embeds=inputs_embeds, attention_mask=attention_mask, cache_position=cache_position, past_key_values=None, position_ids=position_ids, ) # fmt: off EXPECTED_CHUNKED_MASK = torch.tensor( # Here, for the padded sequence, the chunk size should start correctly at index 4 (otherwise, with 4 padding # tokens are chunk_size=3, the first chunk is from indices 0-2, then 3-6 if we don't account for the padding correctly) [[[[False, False, False, False, False, False, False, False], [False, False, False, False, False, False, False, False], [False, False, False, False, False, False, False, False], [False, False, False, False, False, False, False, False], [False, False, False, False, True, False, False, False], [False, False, False, False, True, True, False, False], [False, False, False, False, True, True, True, False], [False, False, False, False, False, False, False, True]]], [[[ True, False, False, False, False, False, False, False], [ True, True, False, False, False, False, False, False], [ True, True, True, False, False, False, False, False], [False, False, False, True, False, False, False, False], [False, False, False, True, True, False, False, False], [False, False, False, True, True, True, False, False], [False, False, False, False, False, False, True, False], [False, False, False, False, False, False, True, True]]]], dtype=torch.bool) # fmt: on self.assertTrue((chunked_attention_mask == EXPECTED_CHUNKED_MASK).all()) def test_chunked_mask_with_left_padding_decoding(self): # Make sur we have an attention_chunk_size in the config config = LlamaConfig(attention_chunk_size=4, attn_implementation="sdpa", num_hidden_layers=1) cache = DynamicCache(config=config) # Sanity check self.assertEqual(len(cache), 1) self.assertTrue(isinstance(cache.layers[0], DynamicSlidingWindowLayer)) # Fill-in the Cache (sequence length is bigger than chunk size here) batch_size = 2 prefill_size = 8 pad_tokens = 7 fake_kv = torch.rand(batch_size, 32, prefill_size, 32) cache.update(fake_kv, fake_kv, 0, torch.arange(prefill_size)) # Create a new input after the prefill input_ids = torch.randint(100, 200, (batch_size, 1)) attention_mask = torch.tensor( [[0 if i < pad_tokens else 1 for i in range(prefill_size + 1)], [1] * (prefill_size + 1)] ) inputs_embeds = torch.empty_like(input_ids, dtype=torch.float16) cache_position = torch.tensor([prefill_size], dtype=int) position_ids = torch.tensor([[prefill_size - pad_tokens], [prefill_size]]) chunked_attention_mask = create_chunked_causal_mask( config=config, input_embeds=inputs_embeds, attention_mask=attention_mask, cache_position=cache_position, past_key_values=cache, position_ids=position_ids, ) # To understand a bit more the following expected mask, here is the full 2d mask, where the "|" characters are the chunk # separators (where the tokens should stop seeing each other) # [0, 0, 0, 0, 0, 0, 0, | 1, 1], -> due to left padding, the first chunk only starts after the padding tokens # [| 1, 1, 1, 1, | 1, 1, 1, 1, | 1]]) -> easy case, each 4 tokens is a new chunk # fmt: off EXPECTED_CHUNKED_MASK = torch.tensor( # Here, for the padded sequence, the chunk size should start correctly at index 7 (the first unpadded # index), and so only indices 7 and 8 should be True [[[[False, False, True, True]]], # Here, for the unpadded sequence, the chunks start at index 0. Since we have 9 tokens in total, the last # token (index 8) will only see itself (we have 2 full chunks before) [[[False, False, False, True]]]], dtype=torch.bool) # fmt: on self.assertTrue((chunked_attention_mask == EXPECTED_CHUNKED_MASK).all())
transformers/tests/utils/test_masking_utils.py/0
{ "file_path": "transformers/tests/utils/test_masking_utils.py", "repo_id": "transformers", "token_count": 4888 }
553
# coding=utf-8 # 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 inspect import os import re from transformers.configuration_utils import PretrainedConfig from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py PATH_TO_TRANSFORMERS = "src/transformers" # This is to make sure the transformers module imported is the one in the repo. transformers = direct_transformers_import(PATH_TO_TRANSFORMERS) CONFIG_MAPPING = transformers.models.auto.configuration_auto.CONFIG_MAPPING SPECIAL_CASES_TO_ALLOW = { "xLSTMConfig": ["add_out_norm", "chunkwise_kernel", "sequence_kernel", "step_kernel"], "Ernie4_5Config": ["tie_word_embeddings"], "Ernie4_5_MoeConfig": ["tie_word_embeddings"], "Lfm2Config": ["full_attn_idxs", "tie_word_embeddings"], # used internally during generation to provide the custom logit processors with their necessary information "DiaConfig": [ "delay_pattern", ], # 'max_position_embeddings' is not used in modeling file, but needed for eval frameworks like Huggingface's lighteval (https://github.com/huggingface/lighteval/blob/af24080ea4f16eaf1683e353042a2dfc9099f038/src/lighteval/models/base_model.py#L264). # periods and offsets are not used in modeling file, but used in the configuration file to define `layers_block_type` and `layers_num_experts`. "BambaConfig": [ "attn_layer_indices", ], "Dots1Config": ["max_window_layers"], "JambaConfig": [ "max_position_embeddings", "attn_layer_offset", "attn_layer_period", "expert_layer_offset", "expert_layer_period", ], "Qwen2Config": ["use_sliding_window", "max_window_layers"], "Qwen2MoeConfig": ["use_sliding_window"], "Qwen2VLTextConfig": ["use_sliding_window", "max_window_layers"], "Qwen2_5_VLTextConfig": ["use_sliding_window", "max_window_layers"], "Qwen2_5OmniTextConfig": ["use_sliding_window", "max_window_layers"], "Qwen2_5OmniTalkerConfig": ["use_sliding_window", "max_window_layers"], "Qwen3Config": ["max_window_layers", "use_sliding_window"], # now use `layer_types` instead "Qwen3MoeConfig": ["max_window_layers", "use_sliding_window"], # `cache_implementation` should be in the default generation config, but we don't yet support per-model # generation configs (TODO joao) "Gemma2Config": ["tie_word_embeddings", "cache_implementation"], "Cohere2Config": ["cache_implementation"], # Dropout with this value was declared but never used "Phi3Config": ["embd_pdrop"], # used to compute the property `self.chunk_length` "EncodecConfig": ["overlap"], # used to compute `frame_rate` "XcodecConfig": ["sample_rate", "audio_channels"], # used to compute the property `self.layers_block_type` "RecurrentGemmaConfig": ["block_types"], # used as in the config to define `intermediate_size` "MambaConfig": ["expand"], # used as in the config to define `intermediate_size` "FalconMambaConfig": ["expand"], # used as `self.bert_model = BertModel(config, ...)` "DPRConfig": True, "FuyuConfig": True, # not used in modeling files, but it's an important information "FSMTConfig": ["langs"], # used internally in the configuration class file "GPTNeoConfig": ["attention_types"], # used internally in the configuration class file "EsmConfig": ["is_folding_model"], # used during training (despite we don't have training script for these models yet) "Mask2FormerConfig": ["ignore_value"], # `ignore_value` used during training (despite we don't have training script for these models yet) # `norm` used in conversion script (despite not using in the modeling file) "OneFormerConfig": ["ignore_value", "norm"], # used internally in the configuration class file "T5Config": ["feed_forward_proj"], # used internally in the configuration class file # `tokenizer_class` get default value `T5Tokenizer` intentionally "MT5Config": ["feed_forward_proj", "tokenizer_class"], "UMT5Config": ["feed_forward_proj", "tokenizer_class"], # used internally in the configuration class file "LongT5Config": ["feed_forward_proj"], # used internally in the configuration class file "Pop2PianoConfig": ["feed_forward_proj"], # used internally in the configuration class file "SwitchTransformersConfig": ["feed_forward_proj"], # having default values other than `1e-5` - we can't fix them without breaking "BioGptConfig": ["layer_norm_eps"], # having default values other than `1e-5` - we can't fix them without breaking "GLPNConfig": ["layer_norm_eps"], # having default values other than `1e-5` - we can't fix them without breaking "SegformerConfig": ["layer_norm_eps"], # having default values other than `1e-5` - we can't fix them without breaking "CvtConfig": ["layer_norm_eps"], # having default values other than `1e-5` - we can't fix them without breaking "PerceiverConfig": ["layer_norm_eps"], # used internally to calculate the feature size "InformerConfig": ["num_static_real_features", "num_time_features"], # used internally to calculate the feature size "TimeSeriesTransformerConfig": ["num_static_real_features", "num_time_features"], # used internally to calculate the feature size "AutoformerConfig": ["num_static_real_features", "num_time_features"], # used internally to calculate `mlp_dim` "SamVisionConfig": ["mlp_ratio"], # used internally to calculate `mlp_dim` "SamHQVisionConfig": ["mlp_ratio"], # For (head) training, but so far not implemented "ClapAudioConfig": ["num_classes"], # Not used, but providing useful information to users "SpeechT5HifiGanConfig": ["sampling_rate"], # used internally in the configuration class file "UdopConfig": ["feed_forward_proj"], # Actually used in the config or generation config, in that case necessary for the sub-components generation "SeamlessM4TConfig": [ "max_new_tokens", "t2u_max_new_tokens", "t2u_decoder_attention_heads", "t2u_decoder_ffn_dim", "t2u_decoder_layers", "t2u_encoder_attention_heads", "t2u_encoder_ffn_dim", "t2u_encoder_layers", "t2u_max_position_embeddings", ], # Actually used in the config or generation config, in that case necessary for the sub-components generation "SeamlessM4Tv2Config": [ "max_new_tokens", "t2u_decoder_attention_heads", "t2u_decoder_ffn_dim", "t2u_decoder_layers", "t2u_encoder_attention_heads", "t2u_encoder_ffn_dim", "t2u_encoder_layers", "t2u_max_position_embeddings", "t2u_variance_pred_dropout", "t2u_variance_predictor_embed_dim", "t2u_variance_predictor_hidden_dim", "t2u_variance_predictor_kernel_size", ], "ZambaConfig": [ "tie_word_embeddings", "attn_layer_offset", "attn_layer_period", ], "MllamaTextConfig": [ "initializer_range", ], "MllamaVisionConfig": [ "initializer_range", "supported_aspect_ratios", ], "ConditionalDetrConfig": [ "bbox_cost", "bbox_loss_coefficient", "class_cost", "cls_loss_coefficient", "dice_loss_coefficient", "focal_alpha", "giou_cost", "giou_loss_coefficient", "mask_loss_coefficient", ], "DabDetrConfig": [ "dilation", "bbox_cost", "bbox_loss_coefficient", "class_cost", "cls_loss_coefficient", "focal_alpha", "giou_cost", "giou_loss_coefficient", ], "DetrConfig": [ "bbox_cost", "bbox_loss_coefficient", "class_cost", "dice_loss_coefficient", "eos_coefficient", "giou_cost", "giou_loss_coefficient", "mask_loss_coefficient", ], "DFineConfig": [ "eos_coefficient", "focal_loss_alpha", "focal_loss_gamma", "matcher_alpha", "matcher_bbox_cost", "matcher_class_cost", "matcher_gamma", "matcher_giou_cost", "use_focal_loss", "weight_loss_bbox", "weight_loss_giou", "weight_loss_vfl", "weight_loss_fgl", "weight_loss_ddf", ], "GroundingDinoConfig": [ "bbox_cost", "bbox_loss_coefficient", "class_cost", "focal_alpha", "giou_cost", "giou_loss_coefficient", ], "MMGroundingDinoConfig": [ "bbox_cost", "bbox_loss_coefficient", "class_cost", "focal_alpha", "giou_cost", "giou_loss_coefficient", ], "RTDetrConfig": [ "eos_coefficient", "focal_loss_alpha", "focal_loss_gamma", "matcher_alpha", "matcher_bbox_cost", "matcher_class_cost", "matcher_gamma", "matcher_giou_cost", "use_focal_loss", "weight_loss_bbox", "weight_loss_giou", "weight_loss_vfl", ], "RTDetrV2Config": [ "eos_coefficient", "focal_loss_alpha", "focal_loss_gamma", "matcher_alpha", "matcher_bbox_cost", "matcher_class_cost", "matcher_gamma", "matcher_giou_cost", "use_focal_loss", "weight_loss_bbox", "weight_loss_giou", "weight_loss_vfl", ], "YolosConfig": [ "bbox_cost", "bbox_loss_coefficient", "class_cost", "eos_coefficient", "giou_cost", "giou_loss_coefficient", ], "GPTNeoXConfig": ["rotary_emb_base"], "Gemma3Config": ["boi_token_index", "eoi_token_index"], "Gemma3TextConfig": ["cache_implementation", "tie_word_embeddings"], "ShieldGemma2Config": [ "boi_token_index", "eoi_token_index", "initializer_range", "mm_tokens_per_image", "text_config", "vision_config", ], "Llama4Config": ["boi_token_index", "eoi_token_index"], "Llama4TextConfig": [ "interleave_moe_layer_step", "no_rope_layer_interval", "no_rope_layers", "output_router_logits", "router_aux_loss_coef", "router_jitter_noise", "cache_implementation", "attention_chunk_size", ], "Llama4VisionConfig": ["multi_modal_projector_bias", "norm_eps"], "ModernBertDecoderConfig": [ "embedding_dropout", "hidden_activation", "initializer_cutoff_factor", "intermediate_size", "max_position_embeddings", "mlp_bias", "mlp_dropout", "classifier_activation", "global_attn_every_n_layers", "local_attention", "local_rope_theta", ], # position_embedding_type not used and deprecated. Should be deleted in v4.55 "LayoutLMConfig": ["position_embedding_type"], "MarkupLMConfig": ["position_embedding_type"], "SmolLM3Config": ["no_rope_layer_interval"], "Gemma3nVisionConfig": ["architecture", "do_pooling", "model_args"], # this is for use in `timm` } # TODO (ydshieh): Check the failing cases, try to fix them or move some cases to the above block once we are sure SPECIAL_CASES_TO_ALLOW.update( { "CLIPSegConfig": True, "DeformableDetrConfig": True, "DinatConfig": True, "DonutSwinConfig": True, "FastSpeech2ConformerConfig": True, "FSMTConfig": True, "LayoutLMv2Config": True, "MaskFormerSwinConfig": True, "MT5Config": True, # For backward compatibility with trust remote code models "MptConfig": True, "MptAttentionConfig": True, "OneFormerConfig": True, "PerceiverConfig": True, "RagConfig": True, "SpeechT5Config": True, "SwinConfig": True, "Swin2SRConfig": True, "Swinv2Config": True, "SwitchTransformersConfig": True, "TableTransformerConfig": True, "TapasConfig": True, "UniSpeechConfig": True, "UniSpeechSatConfig": True, "WavLMConfig": True, "WhisperConfig": True, # TODO: @Arthur (for `alignment_head` and `alignment_layer`) "JukeboxPriorConfig": True, # TODO: @Younes (for `is_decoder`) "Pix2StructTextConfig": True, "IdeficsConfig": True, "IdeficsVisionConfig": True, "IdeficsPerceiverConfig": True, # TODO: @Arthur/Joao (`hidden_act` unused) "GptOssConfig": True, } ) def check_attribute_being_used(config_class, attributes, default_value, source_strings): """Check if any name in `attributes` is used in one of the strings in `source_strings` Args: config_class (`type`): The configuration class for which the arguments in its `__init__` will be checked. attributes (`List[str]`): The name of an argument (or attribute) and its variant names if any. default_value (`Any`): A default value for the attribute in `attributes` assigned in the `__init__` of `config_class`. source_strings (`List[str]`): The python source code strings in the same modeling directory where `config_class` is defined. The file containing the definition of `config_class` should be excluded. """ attribute_used = False for attribute in attributes: for modeling_source in source_strings: # check if we can find `config.xxx`, `getattr(config, "xxx", ...)` or `getattr(self.config, "xxx", ...)` if ( f"config.{attribute}" in modeling_source or f'getattr(config, "{attribute}"' in modeling_source or f'getattr(self.config, "{attribute}"' in modeling_source or ( "TextConfig" in config_class.__name__ and f"config.get_text_config().{attribute}" in modeling_source ) ): attribute_used = True # Deal with multi-line cases elif ( re.search( rf'getattr[ \t\v\n\r\f]*\([ \t\v\n\r\f]*(self\.)?config,[ \t\v\n\r\f]*"{attribute}"', modeling_source, ) is not None ): attribute_used = True if attribute_used: break if attribute_used: break # common and important attributes, even if they do not always appear in the modeling files attributes_to_allow = [ "initializer_range", "bos_index", "eos_index", "pad_index", "unk_index", "mask_index", "image_token_id", # for VLMs "video_token_id", "image_seq_length", "video_seq_length", "image_size", "text_config", # may appear as `get_text_config()` "use_cache", "out_features", "out_indices", "sampling_rate", # backbone related arguments passed to load_backbone "use_pretrained_backbone", "backbone", "backbone_config", "use_timm_backbone", "backbone_kwargs", # rope attributes may not appear directly in the modeling but are used "rope_theta", "partial_rotary_factor", "pretraining_tp", "boi_token_id", "eoi_token_id", ] attributes_used_in_generation = ["encoder_no_repeat_ngram_size"] # Special cases to be allowed case_allowed = True if not attribute_used: case_allowed = False for attribute in attributes: # Allow if the default value in the configuration class is different from the one in `PretrainedConfig` if attribute in ["is_encoder_decoder"] and default_value is True: case_allowed = True elif attribute in ["tie_word_embeddings"] and default_value is False: case_allowed = True # Allow cases without checking the default value in the configuration class elif attribute in attributes_to_allow + attributes_used_in_generation: case_allowed = True elif attribute.endswith("_token_id"): case_allowed = True # configuration class specific cases if not case_allowed: allowed_cases = SPECIAL_CASES_TO_ALLOW.get(config_class.__name__, []) case_allowed = allowed_cases is True or attribute in allowed_cases return attribute_used or case_allowed def check_config_attributes_being_used(config_class): """Check the arguments in `__init__` of `config_class` are used in the modeling files in the same directory Args: config_class (`type`): The configuration class for which the arguments in its `__init__` will be checked. """ # Get the parameters in `__init__` of the configuration class, and the default values if any signature = dict(inspect.signature(config_class.__init__).parameters) parameter_names = [x for x in list(signature.keys()) if x not in ["self", "kwargs"]] parameter_defaults = [signature[param].default for param in parameter_names] # If `attribute_map` exists, an attribute can have different names to be used in the modeling files, and as long # as one variant is used, the test should pass reversed_attribute_map = {} if len(config_class.attribute_map) > 0: reversed_attribute_map = {v: k for k, v in config_class.attribute_map.items()} # Get the path to modeling source files config_source_file = inspect.getsourcefile(config_class) model_dir = os.path.dirname(config_source_file) # Let's check against all frameworks: as long as one framework uses an attribute, we are good. modeling_paths = [os.path.join(model_dir, fn) for fn in os.listdir(model_dir) if fn.startswith("modeling_")] # Get the source code strings modeling_sources = [] for path in modeling_paths: if os.path.isfile(path): with open(path, encoding="utf8") as fp: modeling_sources.append(fp.read()) unused_attributes = [] for config_param, default_value in zip(parameter_names, parameter_defaults): # `attributes` here is all the variant names for `config_param` attributes = [config_param] # some configuration classes have non-empty `attribute_map`, and both names could be used in the # corresponding modeling files. As long as one of them appears, it is fine. if config_param in reversed_attribute_map: attributes.append(reversed_attribute_map[config_param]) if not check_attribute_being_used(config_class, attributes, default_value, modeling_sources): unused_attributes.append(attributes[0]) return sorted(unused_attributes) def check_config_attributes(): """Check the arguments in `__init__` of all configuration classes are used in python files""" configs_with_unused_attributes = {} for _config_class in list(CONFIG_MAPPING.values()): # Skip deprecated models if "models.deprecated" in _config_class.__module__: continue # Some config classes are not in `CONFIG_MAPPING` (e.g. `CLIPVisionConfig`, `Blip2VisionConfig`, etc.) config_classes_in_module = [ cls for name, cls in inspect.getmembers( inspect.getmodule(_config_class), lambda x: inspect.isclass(x) and issubclass(x, PretrainedConfig) and inspect.getmodule(x) == inspect.getmodule(_config_class), ) ] for config_class in config_classes_in_module: unused_attributes = check_config_attributes_being_used(config_class) if len(unused_attributes) > 0: configs_with_unused_attributes[config_class.__name__] = unused_attributes if len(configs_with_unused_attributes) > 0: error = "The following configuration classes contain unused attributes in the corresponding modeling files:\n" for name, attributes in configs_with_unused_attributes.items(): error += f"{name}: {attributes}\n" raise ValueError(error) if __name__ == "__main__": check_config_attributes()
transformers/utils/check_config_attributes.py/0
{ "file_path": "transformers/utils/check_config_attributes.py", "repo_id": "transformers", "token_count": 8865 }
554
import ast from collections import defaultdict # Function to perform topological sorting def topological_sort(dependencies: dict) -> list[list[str]]: """Given the dependencies graph construct sorted list of list of modular files For example, returned list of lists might be: [ ["../modular_llama.py", "../modular_gemma.py"], # level 0 ["../modular_llama4.py", "../modular_gemma2.py"], # level 1 ["../modular_glm4.py"], # level 2 ] which means llama and gemma do not depend on any other modular models, while llama4 and gemma2 depend on the models in the first list, and glm4 depends on the models in the second and (optionally) in the first list. """ # Nodes are the name of the models to convert (we only add those to the graph) nodes = {node.rsplit("modular_", 1)[1].replace(".py", "") for node in dependencies} # This will be a graph from models to convert, to models to convert that should be converted before (as they are a dependency) graph = {} name_mapping = {} for node, deps in dependencies.items(): node_name = node.rsplit("modular_", 1)[1].replace(".py", "") dep_names = {dep.split(".")[-2] for dep in deps} dependencies = {dep for dep in dep_names if dep in nodes and dep != node_name} graph[node_name] = dependencies name_mapping[node_name] = node sorting_list = [] while len(graph) > 0: # Find the nodes with 0 out-degree leaf_nodes = {node for node in graph if len(graph[node]) == 0} # Add them to the list as next level sorting_list.append([name_mapping[node] for node in leaf_nodes]) # Remove the leafs from the graph (and from the deps of other nodes) graph = {node: deps - leaf_nodes for node, deps in graph.items() if node not in leaf_nodes} return sorting_list # Function to extract class and import info from a file def extract_classes_and_imports(file_path): with open(file_path, "r", encoding="utf-8") as file: tree = ast.parse(file.read(), filename=file_path) imports = set() for node in ast.walk(tree): if isinstance(node, (ast.Import, ast.ImportFrom)): module = node.module if isinstance(node, ast.ImportFrom) else None if module and (".modeling_" in module or "transformers.models" in module): imports.add(module) return imports # Function to map dependencies between classes def map_dependencies(py_files): dependencies = defaultdict(set) # First pass: Extract all classes and map to files for file_path in py_files: # dependencies[file_path].add(None) class_to_file = extract_classes_and_imports(file_path) for module in class_to_file: dependencies[file_path].add(module) return dependencies def find_priority_list(py_files): """ Given a list of modular files, sorts them by topological order. Modular models that DON'T depend on other modular models will be higher in the topological order. Args: py_files: List of paths to the modular files Returns: Ordered list of lists of files and their dependencies (dict) For example, ordered_files might be: [ ["../modular_llama.py", "../modular_gemma.py"], # level 0 ["../modular_llama4.py", "../modular_gemma2.py"], # level 1 ["../modular_glm4.py"], # level 2 ] which means llama and gemma do not depend on any other modular models, while llama4 and gemma2 depend on the models in the first list, and glm4 depends on the models in the second and (optionally) in the first list. """ dependencies = map_dependencies(py_files) ordered_files = topological_sort(dependencies) return ordered_files, dependencies
transformers/utils/create_dependency_mapping.py/0
{ "file_path": "transformers/utils/create_dependency_mapping.py", "repo_id": "transformers", "token_count": 1477 }
555
# 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. """ Script to find a candidate list of models to deprecate based on the number of downloads and the date of the last commit. """ import argparse import glob import json import os from collections import defaultdict from datetime import datetime, timezone from pathlib import Path from git import Repo from huggingface_hub import HfApi api = HfApi() PATH_TO_REPO = Path(__file__).parent.parent.resolve() repo = Repo(PATH_TO_REPO) class HubModelLister: """ Utility for getting models from the hub based on tags. Handles errors without crashing the script. """ def __init__(self, tags): self.tags = tags self.model_list = api.list_models(tags=tags) def __iter__(self): try: yield from self.model_list except Exception as e: print(f"Error: {e}") return def _extract_commit_hash(commits): for commit in commits: if commit.startswith("commit "): return commit.split(" ")[1] return "" def get_list_of_repo_model_paths(models_dir): # Get list of all models in the library models = glob.glob(os.path.join(models_dir, "*/modeling_*.py")) # Remove flax and tf models models = [model for model in models if "_flax_" not in model] models = [model for model in models if "_tf_" not in model] # Get list of all deprecated models in the library deprecated_models = glob.glob(os.path.join(models_dir, "deprecated", "*")) # For each deprecated model, remove the deprecated models from the list of all models as well as the symlink path for deprecated_model in deprecated_models: deprecated_model_name = "/" + deprecated_model.split("/")[-1] + "/" models = [model for model in models if deprecated_model_name not in model] # Remove deprecated models models = [model for model in models if "/deprecated" not in model] # Remove auto models = [model for model in models if "/auto/" not in model] return models def get_list_of_models_to_deprecate( thresh_num_downloads=5_000, thresh_date=None, use_cache=False, save_model_info=False, max_num_models=-1, ): if thresh_date is None: thresh_date = datetime.now(timezone.utc).replace(year=datetime.now(timezone.utc).year - 1) else: thresh_date = datetime.strptime(thresh_date, "%Y-%m-%d").replace(tzinfo=timezone.utc) models_dir = PATH_TO_REPO / "src/transformers/models" model_paths = get_list_of_repo_model_paths(models_dir=models_dir) if use_cache and os.path.exists("models_info.json"): with open("models_info.json", "r") as f: models_info = json.load(f) # Convert datetimes back to datetime objects for model, info in models_info.items(): info["first_commit_datetime"] = datetime.fromisoformat(info["first_commit_datetime"]) else: # Build a dictionary of model info: first commit datetime, commit hash, model path models_info = defaultdict(dict) for model_path in model_paths: model = model_path.split("/")[-2] if model in models_info: continue commits = repo.git.log("--diff-filter=A", "--", model_path).split("\n") commit_hash = _extract_commit_hash(commits) commit_obj = repo.commit(commit_hash) committed_datetime = commit_obj.committed_datetime models_info[model]["commit_hash"] = commit_hash models_info[model]["first_commit_datetime"] = committed_datetime models_info[model]["model_path"] = model_path models_info[model]["downloads"] = 0 # Some tags on the hub are formatted differently than in the library tags = [model] if "_" in model: tags.append(model.replace("_", "-")) models_info[model]["tags"] = tags # Filter out models which were added less than a year ago models_info = { model: info for model, info in models_info.items() if info["first_commit_datetime"] < thresh_date } # We make successive calls to the hub, filtering based on the model tags n_seen = 0 for model, model_info in models_info.items(): for model_tag in model_info["tags"]: model_list = HubModelLister(tags=model_tag) for i, hub_model in enumerate(model_list): n_seen += 1 if i % 100 == 0: print(f"Processing model {i} for tag {model_tag}") if max_num_models != -1 and i > n_seen: break if hub_model.private: continue model_info["downloads"] += hub_model.downloads if save_model_info and not (use_cache and os.path.exists("models_info.json")): # Make datetimes serializable for model, info in models_info.items(): info["first_commit_datetime"] = info["first_commit_datetime"].isoformat() with open("models_info.json", "w") as f: json.dump(models_info, f, indent=4) print("\nFinding models to deprecate:") n_models_to_deprecate = 0 models_to_deprecate = {} for model, info in models_info.items(): n_downloads = info["downloads"] if n_downloads < thresh_num_downloads: n_models_to_deprecate += 1 models_to_deprecate[model] = info print(f"\nModel: {model}") print(f"Downloads: {n_downloads}") print(f"Date: {info['first_commit_datetime']}") print("\nModels to deprecate: ", "\n" + "\n".join(models_to_deprecate.keys())) print(f"\nNumber of models to deprecate: {n_models_to_deprecate}") print("Before deprecating make sure to verify the models, including if they're used as a module in other models.") if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--save_model_info", action="store_true", help="Save the retrieved model info to a json file.") parser.add_argument( "--use_cache", action="store_true", help="Use the cached model info instead of calling the hub." ) parser.add_argument( "--thresh_num_downloads", type=int, default=5_000, help="Threshold number of downloads below which a model should be deprecated. Default is 5,000.", ) parser.add_argument( "--thresh_date", type=str, default=None, help="Date to consider the first commit from. Format: YYYY-MM-DD. If unset, defaults to one year ago from today.", ) parser.add_argument( "--max_num_models", type=int, default=-1, help="Maximum number of models to consider from the hub. -1 means all models. Useful for testing.", ) args = parser.parse_args() models_to_deprecate = get_list_of_models_to_deprecate( thresh_num_downloads=args.thresh_num_downloads, thresh_date=args.thresh_date, use_cache=args.use_cache, save_model_info=args.save_model_info, max_num_models=args.max_num_models, )
transformers/utils/models_to_deprecate.py/0
{ "file_path": "transformers/utils/models_to_deprecate.py", "repo_id": "transformers", "token_count": 3165 }
556
# coding=utf-8 # Copyright 2022 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 sorts the names in the auto mappings defines in the auto modules in alphabetical order. Use from the root of the repo with: ```bash python utils/sort_auto_mappings.py ``` to auto-fix all the auto mappings (used in `make style`). To only check if the mappings are properly sorted (as used in `make quality`), do: ```bash python utils/sort_auto_mappings.py --check_only ``` """ import argparse import os import re from typing import Optional # Path are set with the intent you should run this script from the root of the repo. PATH_TO_AUTO_MODULE = "src/transformers/models/auto" # re pattern that matches mapping introductions: # SUPER_MODEL_MAPPING_NAMES = OrderedDict or SUPER_MODEL_MAPPING = OrderedDict _re_intro_mapping = re.compile(r"[A-Z_]+_MAPPING(\s+|_[A-Z_]+\s+)=\s+OrderedDict") # re pattern that matches identifiers in mappings _re_identifier = re.compile(r'\s*\(\s*"(\S[^"]+)"') def sort_auto_mapping(fname: str, overwrite: bool = False) -> Optional[bool]: """ Sort all auto mappings in a file. Args: fname (`str`): The name of the file where we want to sort auto-mappings. overwrite (`bool`, *optional*, defaults to `False`): Whether or not to fix and overwrite the file. Returns: `Optional[bool]`: Returns `None` if `overwrite=True`. Otherwise returns `True` if the file has an auto-mapping improperly sorted, `False` if the file is okay. """ with open(fname, "r", encoding="utf-8") as f: content = f.read() lines = content.split("\n") new_lines = [] line_idx = 0 while line_idx < len(lines): if _re_intro_mapping.search(lines[line_idx]) is not None: # Start of a new mapping! indent = len(re.search(r"^(\s*)\S", lines[line_idx]).groups()[0]) + 8 while not lines[line_idx].startswith(" " * indent + "("): new_lines.append(lines[line_idx]) line_idx += 1 blocks = [] while lines[line_idx].strip() != "]": # Blocks either fit in one line or not if lines[line_idx].strip() == "(": start_idx = line_idx while not lines[line_idx].startswith(" " * indent + ")"): line_idx += 1 blocks.append("\n".join(lines[start_idx : line_idx + 1])) else: blocks.append(lines[line_idx]) line_idx += 1 # Sort blocks by their identifiers blocks = sorted(blocks, key=lambda x: _re_identifier.search(x).groups()[0]) new_lines += blocks else: new_lines.append(lines[line_idx]) line_idx += 1 if overwrite: with open(fname, "w", encoding="utf-8") as f: f.write("\n".join(new_lines)) else: return "\n".join(new_lines) != content def sort_all_auto_mappings(overwrite: bool = False): """ Sort all auto mappings in the library. Args: overwrite (`bool`, *optional*, defaults to `False`): Whether or not to fix and overwrite the file. """ fnames = [os.path.join(PATH_TO_AUTO_MODULE, f) for f in os.listdir(PATH_TO_AUTO_MODULE) if f.endswith(".py")] diffs = [sort_auto_mapping(fname, overwrite=overwrite) for fname in fnames] if not overwrite and any(diffs): failures = [f for f, d in zip(fnames, diffs) if d] raise ValueError( f"The following files have auto mappings that need sorting: {', '.join(failures)}. Run `make style` to fix" " this." ) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--check_only", action="store_true", help="Whether to only check or fix style.") args = parser.parse_args() sort_all_auto_mappings(not args.check_only)
transformers/utils/sort_auto_mappings.py/0
{ "file_path": "transformers/utils/sort_auto_mappings.py", "repo_id": "transformers", "token_count": 1813 }
557
# coding=utf-8 # 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. """A script running `create_dummy_models.py` with a pre-defined set of arguments. This file is intended to be used in a CI workflow file without the need of specifying arguments. It creates and uploads tiny models for all model classes (if their tiny versions are not on the Hub yet), as well as produces an updated version of `tests/utils/tiny_model_summary.json`. That updated file should be merged into the `main` branch of `transformers` so the pipeline testing will use the latest created/updated tiny models. """ import argparse import copy import json import multiprocessing import os import time from create_dummy_models import COMPOSITE_MODELS, create_tiny_models from huggingface_hub import ModelFilter, hf_api import transformers from transformers import AutoFeatureExtractor, AutoImageProcessor, AutoTokenizer from transformers.image_processing_utils import BaseImageProcessor def get_all_model_names(): model_names = set() # Each auto modeling files contains multiple mappings. Let's get them in a dynamic way. for module_name in ["modeling_auto", "modeling_tf_auto", "modeling_flax_auto"]: module = getattr(transformers.models.auto, module_name, None) if module is None: continue # all mappings in a single auto modeling file mapping_names = [ x for x in dir(module) if x.endswith("_MAPPING_NAMES") and (x.startswith("MODEL_") or x.startswith("TF_MODEL_") or x.startswith("FLAX_MODEL_")) ] for name in mapping_names: mapping = getattr(module, name) if mapping is not None: for v in mapping.values(): if isinstance(v, (list, tuple)): model_names.update(v) elif isinstance(v, str): model_names.add(v) return sorted(model_names) def get_tiny_model_names_from_repo(): # All model names defined in auto mappings model_names = set(get_all_model_names()) with open("tests/utils/tiny_model_summary.json") as fp: tiny_model_info = json.load(fp) tiny_models_names = set() for model_base_name in tiny_model_info: tiny_models_names.update(tiny_model_info[model_base_name]["model_classes"]) # Remove a tiny model name if one of its framework implementation hasn't yet a tiny version on the Hub. not_on_hub = model_names.difference(tiny_models_names) for model_name in copy.copy(tiny_models_names): if not model_name.startswith("TF") and f"TF{model_name}" in not_on_hub: tiny_models_names.remove(model_name) elif model_name.startswith("TF") and model_name[2:] in not_on_hub: tiny_models_names.remove(model_name) return sorted(tiny_models_names) def get_tiny_model_summary_from_hub(output_path): special_models = COMPOSITE_MODELS.values() # All tiny model base names on Hub model_names = get_all_model_names() models = hf_api.list_models( filter=ModelFilter( author="hf-internal-testing", ) ) _models = set() for x in models: model = x.id org, model = model.split("/") if not model.startswith("tiny-random-"): continue model = model.replace("tiny-random-", "") if not model[0].isupper(): continue if model not in model_names and model not in special_models: continue _models.add(model) models = sorted(_models) # All tiny model names on Hub summary = {} for model in models: repo_id = f"hf-internal-testing/tiny-random-{model}" model = model.split("-")[0] try: repo_info = hf_api.repo_info(repo_id) content = { "tokenizer_classes": set(), "processor_classes": set(), "model_classes": set(), "sha": repo_info.sha, } except Exception: continue try: time.sleep(1) tokenizer_fast = AutoTokenizer.from_pretrained(repo_id) content["tokenizer_classes"].add(tokenizer_fast.__class__.__name__) except Exception: pass try: time.sleep(1) tokenizer_slow = AutoTokenizer.from_pretrained(repo_id, use_fast=False) content["tokenizer_classes"].add(tokenizer_slow.__class__.__name__) except Exception: pass try: time.sleep(1) img_p = AutoImageProcessor.from_pretrained(repo_id) content["processor_classes"].add(img_p.__class__.__name__) except Exception: pass try: time.sleep(1) feat_p = AutoFeatureExtractor.from_pretrained(repo_id) if not isinstance(feat_p, BaseImageProcessor): content["processor_classes"].add(feat_p.__class__.__name__) except Exception: pass try: time.sleep(1) model_class = getattr(transformers, model) m = model_class.from_pretrained(repo_id) content["model_classes"].add(m.__class__.__name__) except Exception: pass try: time.sleep(1) model_class = getattr(transformers, f"TF{model}") m = model_class.from_pretrained(repo_id) content["model_classes"].add(m.__class__.__name__) except Exception: pass content["tokenizer_classes"] = sorted(content["tokenizer_classes"]) content["processor_classes"] = sorted(content["processor_classes"]) content["model_classes"] = sorted(content["model_classes"]) summary[model] = content with open(os.path.join(output_path, "hub_tiny_model_summary.json"), "w") as fp: json.dump(summary, fp, ensure_ascii=False, indent=4) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--num_workers", default=1, type=int, help="The number of workers to run.") args = parser.parse_args() # This has to be `spawn` to avoid hanging forever! multiprocessing.set_start_method("spawn") output_path = "tiny_models" all = True model_types = None models_to_skip = get_tiny_model_names_from_repo() no_check = True upload = True organization = "hf-internal-testing" create_tiny_models( output_path, all, model_types, models_to_skip, no_check, upload, organization, token=os.environ.get("TOKEN", None), num_workers=args.num_workers, )
transformers/utils/update_tiny_models.py/0
{ "file_path": "transformers/utils/update_tiny_models.py", "repo_id": "transformers", "token_count": 3071 }
558
cff-version: 1.2.0 title: 'TRL: Transformer Reinforcement Learning' message: >- If you use this software, please cite it using the metadata from this file. type: software authors: - given-names: Leandro family-names: von Werra - given-names: Younes family-names: Belkada - given-names: Lewis family-names: Tunstall - given-names: Edward family-names: Beeching - given-names: Tristan family-names: Thrush - given-names: Nathan family-names: Lambert - given-names: Shengyi family-names: Huang - given-names: Kashif family-names: Rasul - given-names: Quentin family-names: Gallouédec repository-code: 'https://github.com/huggingface/trl' abstract: "With trl you can train transformer language models with Proximal Policy Optimization (PPO). The library is built on top of the transformers library by \U0001F917 Hugging Face. Therefore, pre-trained language models can be directly loaded via transformers. At this point, most decoder and encoder-decoder architectures are supported." keywords: - rlhf - deep-learning - pytorch - transformers license: Apache-2.0 version: "0.21"
trl/CITATION.cff/0
{ "file_path": "trl/CITATION.cff", "repo_id": "trl", "token_count": 371 }
559
# Command Line Interfaces (CLIs) TRL provides a powerful command-line interface (CLI) to fine-tune large language models (LLMs) using methods like Supervised Fine-Tuning (SFT), Direct Preference Optimization (DPO), and more. The CLI abstracts away much of the boilerplate, letting you launch training jobs quickly and reproducibly. Currently supported commands are: #### Training Commands - `trl dpo`: fine-tune a LLM with DPO - `trl grpo`: fine-tune a LLM with GRPO - `trl kto`: fine-tune a LLM with KTO - `trl sft`: fine-tune a LLM with SFT #### Other Commands - `trl env`: get the system information - `trl vllm-serve`: serve a model with vLLM ## Fine-Tuning with the TRL CLI ### Basic Usage You can launch training directly from the CLI by specifying required arguments like the model and dataset: <hfoptions id="command_line"> <hfoption id="SFT"> ```bash trl sft \ --model_name_or_path Qwen/Qwen2.5-0.5B \ --dataset_name stanfordnlp/imdb ``` </hfoption> <hfoption id="DPO"> ```bash trl dpo \ --model_name_or_path Qwen/Qwen2.5-0.5B \ --dataset_name anthropic/hh-rlhf ``` </hfoption> </hfoptions> ### Using Configuration Files To keep your CLI commands clean and reproducible, you can define all training arguments in a YAML configuration file: <hfoptions id="config_file"> <hfoption id="SFT"> ```yaml # sft_config.yaml model_name_or_path: Qwen/Qwen2.5-0.5B dataset_name: stanfordnlp/imdb ``` Launch with: ```bash trl sft --config sft_config.yaml ``` </hfoption> <hfoption id="DPO"> ```yaml # dpo_config.yaml model_name_or_path: Qwen/Qwen2.5-0.5B dataset_name: anthropic/hh-rlhf ``` Launch with: ```bash trl dpo --config dpo_config.yaml ``` </hfoption> </hfoptions> ### Scaling Up with Accelerate TRL CLI natively supports [🤗 Accelerate](https://huggingface.co/docs/accelerate), making it easy to scale training across multiple GPUs, machines, or use advanced setups like DeepSpeed — all from the same CLI. You can pass any `accelerate launch` arguments directly to `trl`, such as `--num_processes`. For more information see [Using accelerate launch](https://huggingface.co/docs/accelerate/en/basic_tutorials/launch#using-accelerate-launch). <hfoptions id="launch_args"> <hfoption id="SFT inline"> ```bash trl sft \ --model_name_or_path Qwen/Qwen2.5-0.5B \ --dataset_name stanfordnlp/imdb \ --num_processes 4 ``` </hfoption> <hfoption id="SFT w/ config file"> ```yaml # sft_config.yaml model_name_or_path: Qwen/Qwen2.5-0.5B dataset_name: stanfordnlp/imdb num_processes: 4 ``` Launch with: ```bash trl sft --config sft_config.yaml ``` </hfoption> <hfoption id="DPO inline"> ```bash trl dpo \ --model_name_or_path Qwen/Qwen2.5-0.5B \ --dataset_name anthropic/hh-rlhf \ --num_processes 4 ``` </hfoption> <hfoption id="DPO w/ config file"> ```yaml # dpo_config.yaml model_name_or_path: Qwen/Qwen2.5-0.5B dataset_name: anthropic/hh-rlhf num_processes: 4 ``` Launch with: ```bash trl dpo --config dpo_config.yaml ``` </hfoption> </hfoptions> ### Using `--accelerate_config` for Accelerate Configuration The `--accelerate_config` flag lets you easily configure distributed training with [🤗 Accelerate](https://github.com/huggingface/accelerate). This flag accepts either: * the name of a predefined config profile (built into TRL), or * a path to a custom Accelerate YAML config file. #### Predefined Config Profiles TRL provides several ready-to-use Accelerate configs to simplify common training setups: | Name | Description | | ------------ | ----------------------------------- | | `fsdp1` | Fully Sharded Data Parallel Stage 1 | | `fsdp2` | Fully Sharded Data Parallel Stage 2 | | `zero1` | DeepSpeed ZeRO Stage 1 | | `zero2` | DeepSpeed ZeRO Stage 2 | | `zero3` | DeepSpeed ZeRO Stage 3 | | `multi_gpu` | Multi-GPU training | | `single_gpu` | Single-GPU training | To use one of these, just pass the name to `--accelerate_config`. TRL will automatically load the corresponding config file from `trl/accelerate_config/`. #### Example Usage <hfoptions id="accelerate_config"> <hfoption id="SFT inline"> ```bash trl sft \ --model_name_or_path Qwen/Qwen2.5-0.5B \ --dataset_name stanfordnlp/imdb \ --accelerate_config zero2 # or path/to/my/accelerate/config.yaml ``` </hfoption> <hfoption id="SFT w/ config file"> ```yaml # sft_config.yaml model_name_or_path: Qwen/Qwen2.5-0.5B dataset_name: stanfordnlp/imdb accelerate_config: zero2 # or path/to/my/accelerate/config.yaml ``` Launch with: ```bash trl sft --config sft_config.yaml ``` </hfoption> <hfoption id="DPO inline"> ```bash trl dpo \ --model_name_or_path Qwen/Qwen2.5-0.5B \ --dataset_name anthropic/hh-rlhf \ --accelerate_config zero2 # or path/to/my/accelerate/config.yaml ``` </hfoption> <hfoption id="DPO w/ config file"> ```yaml # dpo_config.yaml model_name_or_path: Qwen/Qwen2.5-0.5B dataset_name: anthropic/hh-rlhf accelerate_config: zero2 # or path/to/my/accelerate/config.yaml ``` Launch with: ```bash trl dpo --config dpo_config.yaml ``` </hfoption> </hfoptions> ### Using dataset mixtures You can use dataset mixtures to combine multiple datasets into a single training dataset. This is useful for training on diverse data sources or when you want to mix different types of data. <hfoptions id="accelerate_config"> <hfoption id="SFT"> ```yaml # sft_config.yaml model_name_or_path: Qwen/Qwen2.5-0.5B datasets: - path: stanfordnlp/imdb - path: roneneldan/TinyStories ``` Launch with: ```bash trl sft --config sft_config.yaml ``` </hfoption> <hfoption id="DPO"> ```yaml # dpo_config.yaml model_name_or_path: Qwen/Qwen2.5-0.5B datasets: - path: BAAI/Infinity-Preference - path: argilla/Capybara-Preferences ``` Launch with: ```bash trl dpo --config dpo_config.yaml ``` </hfoption> </hfoptions> To see all the available keywords for defining dataset mixtures, refer to the [`scripts.utils.DatasetConfig`] and [`DatasetMixtureConfig`] classes. ## Getting the System Information You can get the system information by running the following command: ```bash trl env ``` This will print out the system information, including the GPU information, the CUDA version, the PyTorch version, the transformers version, the TRL version, and any optional dependencies that are installed. ```txt Copy-paste the following information when reporting an issue: - Platform: Linux-5.15.0-1048-aws-x86_64-with-glibc2.31 - Python version: 3.11.9 - PyTorch version: 2.4.1 - accelerator(s): NVIDIA H100 80GB HBM3 - Transformers version: 4.45.0.dev0 - Accelerate version: 0.34.2 - Accelerate config: - compute_environment: LOCAL_MACHINE - distributed_type: DEEPSPEED - mixed_precision: no - use_cpu: False - debug: False - num_processes: 4 - machine_rank: 0 - num_machines: 1 - rdzv_backend: static - same_network: True - main_training_function: main - enable_cpu_affinity: False - deepspeed_config: {'gradient_accumulation_steps': 4, 'offload_optimizer_device': 'none', 'offload_param_device': 'none', 'zero3_init_flag': False, 'zero_stage': 2} - downcast_bf16: no - tpu_use_cluster: False - tpu_use_sudo: False - tpu_env: [] - Datasets version: 3.0.0 - HF Hub version: 0.24.7 - TRL version: 0.12.0.dev0+acb4d70 - bitsandbytes version: 0.41.1 - DeepSpeed version: 0.15.1 - Diffusers version: 0.30.3 - Liger-Kernel version: 0.3.0 - LLM-Blender version: 0.0.2 - OpenAI version: 1.46.0 - PEFT version: 0.12.0 - vLLM version: not installed ``` This information is required when reporting an issue.
trl/docs/source/clis.md/0
{ "file_path": "trl/docs/source/clis.md", "repo_id": "trl", "token_count": 2961 }
560
# Installation You can install TRL either from PyPI or from source: ## PyPI Install the library with pip or [uv](https://docs.astral.sh/uv/): <hfoptions id="install"> <hfoption id="uv"> uv is a fast Rust-based Python package and project manager. Refer to [Installation](https://docs.astral.sh/uv/getting-started/installation/) for installation instructions), . ```bash uv pip install trl ``` </hfoption> <hfoption id="pip"> ```bash pip install trl ``` </hfoption> </hfoptions> ## Source You can also install the latest version from source. First clone the repo and then run the installation with `pip`: ```bash git clone https://github.com/huggingface/trl.git cd trl/ pip install -e . ``` If you want the development install you can replace the pip install with the following: ```bash pip install -e ".[dev]" ```
trl/docs/source/installation.md/0
{ "file_path": "trl/docs/source/installation.md", "repo_id": "trl", "token_count": 267 }
561
# 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 Optional from datasets import load_dataset from huggingface_hub import ModelCard from transformers import HfArgumentParser @dataclass class ScriptArguments: r""" Arguments for the script. Args: push_to_hub (`bool`, *optional*, defaults to `False`): Whether to push the dataset to the Hugging Face Hub. repo_id (`str`, *optional*, defaults to `"trl-lib/tldr-preference"`): Hugging Face repository ID to push the dataset to. dataset_num_proc (`int` or `None`, *optional*, defaults to `None`): Number of workers to use for dataset processing. """ push_to_hub: bool = field( default=False, metadata={"help": "Whether to push the dataset to the Hugging Face Hub."}, ) repo_id: str = field( default="trl-lib/tldr-preference", metadata={"help": "Hugging Face repository ID to push the dataset to."}, ) dataset_num_proc: Optional[int] = field( default=None, metadata={"help": "Number of workers to use for dataset processing."}, ) def to_preference(example): info = example["info"] if example["batch"] in ["batch0_cnndm", "cnndm0", "cnndm2"]: # CNN Daily Mail batches article = info["article"].replace("\n\n", "\n") prompt = f"TITLE: {info['title']}\n\n{article}\n\nTL;DR:" elif example["batch"] in [f"batch{i}" for i in range(3, 23)] + ["edit_b2_eval_test"]: # Reddit batches post = info["post"].replace("\n\n", "\n") prompt = f"SUBREDDIT: r/{info['subreddit']}\n\nTITLE: {info['title']}\n\nPOST: {post}\n\nTL;DR:" else: raise ValueError(f"Unknown batch: {example['batch']}") chosen_idx = example["choice"] rejected_idx = 1 - chosen_idx chosen = example["summaries"][chosen_idx]["text"] rejected = example["summaries"][rejected_idx]["text"] return {"prompt": prompt, "chosen": chosen, "rejected": rejected} model_card = ModelCard(""" --- tags: [trl] --- # TL;DR Dataset for Preference Learning ## Summary The TL;DR dataset is a processed version of Reddit posts, specifically curated to train models using the [TRL library](https://github.com/huggingface/trl) for preference learning and Reinforcement Learning from Human Feedback (RLHF) tasks. It leverages the common practice on Reddit where users append "TL;DR" (Too Long; Didn't Read) summaries to lengthy posts, providing a rich source of paired text data for training models to understand and generate concise summaries. ## Data Structure - **Format**: [Standard](https://huggingface.co/docs/trl/main/dataset_formats#standard) - **Type**: [Preference](https://huggingface.co/docs/trl/main/dataset_formats#preference) Columns: - `"prompt"`: The unabridged Reddit post. - `"chosen"`: The concise "TL;DR" summary appended by the author. - `"rejected"`: An alternative summary or response that was not selected. This structure enables models to learn the relationship between detailed content and its abbreviated form, enhancing their summarization capabilities. ## Generation script The script used to generate this dataset can be found [here](https://github.com/huggingface/trl/blob/main/examples/datasets/tldr_preference.py). """) if __name__ == "__main__": parser = HfArgumentParser(ScriptArguments) script_args = parser.parse_args_into_dataclasses()[0] dataset = load_dataset("openai/summarize_from_feedback", "comparisons") dataset = dataset.map( to_preference, num_proc=script_args.dataset_num_proc, remove_columns=["info", "summaries", "choice", "worker", "batch", "split", "extra"], ) if script_args.push_to_hub: dataset.push_to_hub(script_args.repo_id) model_card.push_to_hub(script_args.repo_id, repo_type="dataset")
trl/examples/datasets/tldr_preference.py/0
{ "file_path": "trl/examples/datasets/tldr_preference.py", "repo_id": "trl", "token_count": 1550 }
562
# 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 Optional import torch from accelerate import Accelerator from datasets import load_dataset from peft import LoraConfig from tqdm import tqdm from transformers import Adafactor, AutoTokenizer, HfArgumentParser, pipeline, set_seed from trl import AutoModelForCausalLMWithValueHead, PPOConfig, PPOTrainer from trl.core import LengthSampler tqdm.pandas() @dataclass class ScriptArguments: """ The name of the Casual LM model we wish to fine-tune with PPO """ # NOTE: gpt2 models use Conv1D instead of Linear layers which are not yet supported in 8 bit mode # models like gpt-neo* models are more suitable. model_name: Optional[str] = field(default="", metadata={"help": "the model name"}) tokenizer_name: Optional[str] = field(default="", metadata={"help": "the tokenizer name"}) reward_model_name: Optional[str] = field(default="", metadata={"help": "the reward model name"}) log_with: Optional[str] = field(default=None, metadata={"help": "use 'wandb' to log with wandb"}) learning_rate: Optional[float] = field(default=1.41e-5, metadata={"help": "the learning rate"}) output_max_length: Optional[int] = field(default=128, metadata={"help": "maximum length for generation"}) mini_batch_size: Optional[int] = field(default=1, metadata={"help": "the PPO minibatch size"}) batch_size: Optional[int] = field(default=32, metadata={"help": "the batch size"}) ppo_epochs: Optional[int] = field(default=4, metadata={"help": "the number of ppo epochs"}) gradient_accumulation_steps: Optional[int] = field( default=4, metadata={"help": "the number of gradient accumulation steps"} ) adafactor: Optional[bool] = field(default=False, metadata={"help": "whether to use the adafactor optimizer"}) early_stopping: Optional[bool] = field(default=False, metadata={"help": "whether to early stop"}) target_kl: Optional[float] = field(default=0.1, metadata={"help": "kl target for early stopping"}) reward_baseline: Optional[float] = field( default=0.0, metadata={"help": "a baseline value that is subtracted from the reward"}, ) batched_gen: Optional[bool] = field(default=False, metadata={"help": "whether to use the batched text gen"}) save_freq: Optional[int] = field(default=None, metadata={"help": "n steps to save the model"}) output_dir: Optional[str] = field(default="runs/", metadata={"help": "n steps to save the model"}) seed: Optional[int] = field(default=0, metadata={"help": "the seed"}) steps: Optional[int] = field(default=20000, metadata={"help": "number of epochs"}) init_kl_coef: Optional[float] = field( default=0.2, metadata={"help": "Initial KL penalty coefficient (used for adaptive and linear control)"}, ) adap_kl_ctrl: Optional[bool] = field(default=True, metadata={"help": "Use adaptive KL control, otherwise linear"}) load_in_8bit: Optional[bool] = field(default=True, metadata={"help": "whether to load the model in 8bit"}) parser = HfArgumentParser(ScriptArguments) script_args: ScriptArguments = parser.parse_args_into_dataclasses()[0] reward_model_name = script_args.reward_model_name dataset_name = "lvwerra/stack-exchange-paired" config = PPOConfig( steps=script_args.steps, model_name=script_args.model_name, learning_rate=script_args.learning_rate, log_with=script_args.log_with, batch_size=script_args.batch_size, mini_batch_size=script_args.mini_batch_size, gradient_accumulation_steps=script_args.gradient_accumulation_steps, optimize_device_cache=True, early_stopping=script_args.early_stopping, target_kl=script_args.target_kl, ppo_epochs=script_args.ppo_epochs, seed=script_args.seed, init_kl_coef=script_args.init_kl_coef, adap_kl_ctrl=script_args.adap_kl_ctrl, ) train_dataset = load_dataset( "lvwerra/stack-exchange-paired", data_dir="data/rl", split="train", verification_mode="no_checks" ) train_dataset = train_dataset.select(range(100000)) original_columns = train_dataset.column_names # We then define the arguments to pass to the sentiment analysis pipeline. # We set `return_all_scores` to True to get the sentiment score for each token. sent_kwargs = { "return_all_scores": True, "function_to_apply": "none", "batch_size": 16, "truncation": True, } tokenizer = AutoTokenizer.from_pretrained(script_args.tokenizer_name) # GPT-2 tokenizer has a pad token, but it is not eos_token by default. We need to set it to eos_token. # only for this model. if getattr(tokenizer, "pad_token", None) is None: tokenizer.pad_token = tokenizer.eos_token # Below is an example function to build the dataset. In our case, we use the IMDB dataset # from the `datasets` library. One should customize this function to train the model on # its own dataset. def build_dataset( tokenizer, dataset_name="lvwerra/stack-exchange-paired", ): """ Build dataset for training. This builds the dataset from `load_dataset`, one should customize this function to train the model on its own dataset. Args: dataset_name (`str`): The name of the dataset to be loaded. Returns: dataloader (`torch.utils.data.DataLoader`): The dataloader for the dataset. """ num_proc = 24 def preprocess_function(examples): new_examples = { "query": [], "input_ids": [], } for question in examples["question"]: query = "Question: " + question + "\n\nAnswer: " tokenized_question = tokenizer(query, truncation=True) new_examples["query"].append(query) new_examples["input_ids"].append(tokenized_question["input_ids"]) return new_examples ds = train_dataset.map( preprocess_function, batched=True, num_proc=num_proc, remove_columns=original_columns, ) ds = ds.filter(lambda x: len(x["input_ids"]) < 512, batched=False, num_proc=num_proc) ds.set_format(type="torch") return ds # We retrieve the dataloader by calling the `build_dataset` function. dataset = build_dataset(tokenizer) def collator(data): return {key: [d[key] for d in data] for key in data[0]} # set seed before initializing value head for deterministic eval set_seed(config.seed) # Now let's build the model, the reference model, and the tokenizer. current_device = Accelerator().local_process_index lora_config = LoraConfig( r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM", ) model = AutoModelForCausalLMWithValueHead.from_pretrained( config.model_name, load_in_8bit=script_args.load_in_8bit, device_map={"": current_device}, peft_config=lora_config, ) optimizer = None if script_args.adafactor: optimizer = Adafactor( filter(lambda p: p.requires_grad, model.parameters()), scale_parameter=False, relative_step=False, warmup_init=False, lr=config.learning_rate, ) # We then build the PPOTrainer, passing the model, the reference model, the tokenizer ppo_trainer = PPOTrainer( config, model, ref_model=None, tokenizer=tokenizer, dataset=dataset, data_collator=collator, optimizer=optimizer, ) # We then build the sentiment analysis pipeline using our reward model, passing the # model name and the sentiment analysis pipeline arguments. Let's also make sure to # set the device to the same device as the PPOTrainer. device = ppo_trainer.accelerator.device if ppo_trainer.accelerator.num_processes == 1: device = 0 if torch.cuda.is_available() else "cpu" # to avoid a ` pipeline` bug sentiment_pipe = pipeline( "sentiment-analysis", model=reward_model_name, device_map={"": current_device}, model_kwargs={"load_in_8bit": script_args.load_in_8bit}, tokenizer=tokenizer, return_token_type_ids=False, ) if sentiment_pipe.model.config.pad_token_id is None: sentiment_pipe.model.config.pad_token_id = sentiment_pipe.model.config.eos_token_id # We then define the arguments to pass to the `generate` function. These arguments # are passed to the `generate` function of the PPOTrainer, which is a wrapper around # the `generate` function of the trained model. generation_kwargs = { # "min_length": -1, "top_k": 0.0, "top_p": 1.0, "do_sample": True, "pad_token_id": tokenizer.pad_token_id, "eos_token_id": 100_000, } output_min_length = 32 output_max_length = script_args.output_max_length output_length_sampler = LengthSampler(output_min_length, output_max_length) for epoch, batch in tqdm(enumerate(ppo_trainer.dataloader)): if epoch >= config.total_ppo_epochs: break question_tensors = batch["input_ids"] response_tensors = ppo_trainer.generate( question_tensors, return_prompt=False, length_sampler=output_length_sampler, **generation_kwargs, ) batch["response"] = tokenizer.batch_decode(response_tensors, skip_special_tokens=True) # Compute reward score (using the sentiment analysis pipeline) texts = [q + r for q, r in zip(batch["query"], batch["response"])] pipe_outputs = sentiment_pipe(texts, **sent_kwargs) rewards = [torch.tensor(output[0]["score"] - script_args.reward_baseline) for output in pipe_outputs] # Run PPO step stats = ppo_trainer.step(question_tensors, response_tensors, rewards) ppo_trainer.log_stats(stats, batch, rewards) if script_args.save_freq and epoch and epoch % script_args.save_freq == 0: ppo_trainer.save_pretrained(script_args.output_dir + f"step_{epoch}")
trl/examples/research_projects/stack_llama/scripts/rl_training.py/0
{ "file_path": "trl/examples/research_projects/stack_llama/scripts/rl_training.py", "repo_id": "trl", "token_count": 3757 }
563
# Copyright 2020-2025 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # /// script # dependencies = [ # "trl @ git+https://github.com/huggingface/trl.git", # "vllm", # ] # /// from dataclasses import dataclass, field from typing import Optional from datasets import load_dataset from transformers import HfArgumentParser from vllm import LLM, SamplingParams from trl import HfPairwiseJudge, OpenAIPairwiseJudge """ Examples: python examples/scripts/evals/judge_tldr.py --model_name_or_path vwxyzjn/rloo_tldr --num_examples 1000 Model win rate: 31.40% python examples/scripts/evals/judge_tldr.py --model_name_or_path vwxyzjn/rloo_tldr --judge_model gpt-3.5-turbo-0125 --num_examples 1000 Model win rate: 51.60% python examples/scripts/evals/judge_tldr.py --model_name_or_path vwxyzjn/rloo_tldr --judge_model gpt-4o-mini --num_examples 1000 Model win rate: 51.20% python examples/scripts/evals/judge_tldr.py --model_name_or_path vwxyzjn/ppo_tldr --num_examples 1000 Model win rate: 46.30% python examples/scripts/evals/judge_tldr.py --model_name_or_path vwxyzjn/ppo_tldr --judge_model gpt-3.5-turbo-0125 --num_examples 1000 Model win rate: 52.50% python examples/scripts/evals/judge_tldr.py --model_name_or_path vwxyzjn/ppo_tldr --judge_model gpt-4o-mini --num_examples 1000 Model win rate: 63.00% """ @dataclass class ScriptArguments: r""" Arguments for the script. Args: model_name_or_path (`str`): Model name or path to the model to evaluate. judge_model (`str`, *optional*, defaults to `"meta-llama/Meta-Llama-3-70B-Instruct"`): Model name or path to the model to use as a judge. E.g., 'gpt-3.5-turbo-0125' or 'meta-llama/Meta-Llama-3-70B-Instruct'. num_examples (`int` or `None`, *optional*, defaults to `None`): Number of examples to evaluate. """ model_name_or_path: str = field(metadata={"help": "Model name or path to the model to evaluate."}) judge_model: str = field( default="meta-llama/Meta-Llama-3-70B-Instruct", metadata={ "help": "Model name or path to the model to use as a judge. E.g., 'gpt-3.5-turbo-0125' or " "'meta-llama/Meta-Llama-3-70B-Instruct'." }, ) num_examples: Optional[int] = field(default=None, metadata={"help": "Number of examples to evaluate."}) if __name__ == "__main__": # Parse the arguments parser = HfArgumentParser(ScriptArguments) script_args = parser.parse_args_into_dataclasses()[0] # Load the dataset dataset = load_dataset("trl-lib/tldr", split="validation") if script_args.num_examples is not None: dataset = dataset.select(range(script_args.num_examples)) # Extract the prompts and reference completions prompts = dataset["prompt"] reference_completions = dataset["completion"] # Generate the model completions sampling_params = SamplingParams(temperature=0.0, top_p=0.95, max_tokens=200) # very generous max token length llm = LLM(model=script_args.model_name_or_path, tensor_parallel_size=1) outputs = llm.generate(prompts, sampling_params) model_completions = [output.outputs[0].text.strip() for output in outputs] # Judge the outputs if "gpt" in script_args.judge_model: judge = OpenAIPairwiseJudge(script_args.judge_model) else: judge = HfPairwiseJudge(script_args.judge_model) completions = [[c0, c1] for c0, c1 in zip(reference_completions, model_completions)] best_idxs = judge.judge(prompts, completions) model_win_rate = best_idxs.count(1) / len(best_idxs) print(f"Model win rate: {model_win_rate * 100:.2f}%")
trl/examples/scripts/evals/judge_tldr.py/0
{ "file_path": "trl/examples/scripts/evals/judge_tldr.py", "repo_id": "trl", "token_count": 1627 }
564
# Copyright 2020-2025 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # /// script # dependencies = [ # "trl @ git+https://github.com/huggingface/trl.git", # ] # /// """ Train Gemma-3 on the Codeforces COTS dataset. accelerate launch --config_file examples/accelerate_configs/deepspeed_zero3.yaml examples/scripts/sft_gemma3.py """ from datasets import load_dataset from transformers import AutoModelForImageTextToText from trl import SFTConfig, SFTTrainer def main(): # Load dataset train_dataset = load_dataset("open-r1/codeforces-cots", split="train") train_dataset = train_dataset.remove_columns("prompt") # Load model model_id = "google/gemma-3-12b-it" model = AutoModelForImageTextToText.from_pretrained(model_id, attn_implementation="eager") # Train model training_args = SFTConfig( output_dir=f"{model_id}-codeforces-SFT", bf16=True, use_liger_kernel=True, gradient_checkpointing=True, gradient_checkpointing_kwargs={"use_reentrant": False}, max_length=8192, per_device_train_batch_size=1, gradient_accumulation_steps=8, dataset_num_proc=32, num_train_epochs=1, ) trainer = SFTTrainer( args=training_args, model=model, train_dataset=train_dataset, ) trainer.train() # Push to hub trainer.push_to_hub(dataset_name="open-r1/codeforces-cots") if __name__ == "__main__": main()
trl/examples/scripts/sft_gemma3.py/0
{ "file_path": "trl/examples/scripts/sft_gemma3.py", "repo_id": "trl", "token_count": 765 }
565
# 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 json import logging import os from datetime import date from pathlib import Path from tabulate import tabulate MAX_LEN_MESSAGE = 2900 # Slack endpoint has a limit of 3001 characters parser = argparse.ArgumentParser() parser.add_argument("--slack_channel_name", default="trl-push-ci") # Set up logging logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s") def process_log_file(log): failed_tests = [] passed_tests = [] section_num_failed = 0 try: with open(log) as f: for line in f: try: data = json.loads(line) test_name = data.get("nodeid", "") duration = f"{data['duration']:.4f}" if "duration" in data else "N/A" outcome = data.get("outcome", "") if test_name: if outcome == "failed": section_num_failed += 1 failed_tests.append([test_name, duration, log.stem.split("_")[0]]) else: passed_tests.append([test_name, duration, log.stem.split("_")[0]]) except json.JSONDecodeError as e: logging.warning(f"Could not decode line in {log}: {e}") except FileNotFoundError as e: logging.error(f"Log file {log} not found: {e}") except Exception as e: logging.error(f"Error processing log file {log}: {e}") return failed_tests, passed_tests, section_num_failed def main(slack_channel_name): group_info = [] total_num_failed = 0 total_empty_files = [] log_files = list(Path().glob("*.log")) if not log_files: logging.info("No log files found.") return for log in log_files: failed, passed, section_num_failed = process_log_file(log) empty_file = not failed and not passed total_num_failed += section_num_failed total_empty_files.append(empty_file) group_info.append([str(log), section_num_failed, failed]) # Clean up log file try: os.remove(log) except OSError as e: logging.warning(f"Could not remove log file {log}: {e}") # Prepare Slack message payload payload = [ { "type": "header", "text": {"type": "plain_text", "text": f"🤗 Results of the {os.environ.get('TEST_TYPE', '')} TRL tests."}, }, ] if total_num_failed > 0: message = "" for name, num_failed, failed_tests in group_info: if num_failed > 0: message += f"*{name}: {num_failed} failed test(s)*\n" failed_table = [ test[0].split("::")[:2] + [test[0].split("::")[-1][:30] + ".."] for test in failed_tests ] message += ( "\n```\n" + tabulate(failed_table, headers=["Test Location", "Test Name"], tablefmt="grid") + "\n```\n" ) if any(total_empty_files): message += f"\n*{name}: Warning! Empty file - check GitHub action job*\n" # Logging logging.info(f"Total failed tests: {total_num_failed}") print(f"### {message}") if len(message) > MAX_LEN_MESSAGE: message = ( f"❌ There are {total_num_failed} failed tests in total! Please check the action results directly." ) payload.append({"type": "section", "text": {"type": "mrkdwn", "text": message}}) payload.append( { "type": "section", "text": {"type": "mrkdwn", "text": "*For more details:*"}, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results"}, "url": f"https://github.com/huggingface/trl/actions/runs/{os.environ['GITHUB_RUN_ID']}", }, } ) payload.append( { "type": "context", "elements": [ { "type": "plain_text", "text": f"On Push main {os.environ.get('TEST_TYPE')} results for {date.today()}", } ], } ) # Send to Slack from slack_sdk import WebClient slack_client = WebClient(token=os.environ.get("SLACK_API_TOKEN")) slack_client.chat_postMessage(channel=f"#{slack_channel_name}", text=message, blocks=payload) else: payload.append( { "type": "section", "text": { "type": "plain_text", "text": "✅ No failures! All tests passed successfully.", "emoji": True, }, } ) logging.info("All tests passed. No errors detected.") if __name__ == "__main__": args = parser.parse_args() main(args.slack_channel_name)
trl/scripts/log_reports.py/0
{ "file_path": "trl/scripts/log_reports.py", "repo_id": "trl", "token_count": 2763 }
566
# 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 tempfile import unittest from dataclasses import dataclass from unittest.mock import mock_open, patch from datasets import DatasetDict, load_dataset from trl import DatasetMixtureConfig, TrlParser, get_dataset from trl.scripts.utils import DatasetConfig from .testing_utils import TrlTestCase @dataclass class MyDataclass: arg1: int arg2: str = "default" @dataclass class InvalidDataclass: config: str # This should raise an error in the TrlParser class TestTrlParser(TrlTestCase): def test_init_without_config_field(self): """Test initialization without 'config' field in the dataclasses.""" parser = TrlParser(dataclass_types=[MyDataclass]) self.assertIsInstance(parser, TrlParser) def test_init_with_config_field(self): """Test initialization with a 'config' field in the dataclass (should raise ValueError).""" with self.assertRaises(ValueError) as context: TrlParser(dataclass_types=[InvalidDataclass]) self.assertTrue("has a field named 'config'" in str(context.exception)) @patch("builtins.open", mock_open(read_data="env:\n VAR1: value1\n VAR2: value2\narg1: 2")) @patch("yaml.safe_load") @patch("os.environ", new_callable=dict) # Mock os.environ as a dictionary def test_parse_args_and_config_with_valid_config(self, mock_environ, mock_yaml_load): """Test parse_args_and_config method with valid arguments and config.""" mock_yaml_load.return_value = {"env": {"VAR1": "value1", "VAR2": "value2"}, "arg1": 2} parser = TrlParser(dataclass_types=[MyDataclass]) args = ["--arg2", "value", "--config", "config.yaml"] # don't set arg1 to test default value # Simulate the config being loaded and environment variables being set result_args = parser.parse_args_and_config(args) # Set the environment variables using the mock mock_environ["VAR1"] = "value1" mock_environ["VAR2"] = "value2" # Ensure that the environment variables were set correctly self.assertEqual(mock_environ.get("VAR1"), "value1") self.assertEqual(mock_environ.get("VAR2"), "value2") # Check the parsed arguments self.assertEqual(len(result_args), 1) self.assertIsInstance(result_args[0], MyDataclass) self.assertEqual(result_args[0].arg1, 2) self.assertEqual(result_args[0].arg2, "value") @patch("builtins.open", mock_open(read_data="arg1: 2")) @patch("yaml.safe_load") def test_parse_args_and_arg_override_config(self, mock_yaml_load): """Test parse_args_and_config method and check that arguments override the config.""" mock_yaml_load.return_value = {"arg1": 2} # this arg is meant to be overridden parser = TrlParser(dataclass_types=[MyDataclass]) args = ["--arg1", "3", "--config", "config.yaml"] # override arg1 default with 3 # Simulate the config being loaded and arguments being passed result_args = parser.parse_args_and_config(args) # Check the parsed arguments self.assertEqual(len(result_args), 1) self.assertIsInstance(result_args[0], MyDataclass) self.assertEqual(result_args[0].arg1, 3) @patch("builtins.open", mock_open(read_data="env: not_a_dict")) @patch("yaml.safe_load") def test_parse_args_and_config_with_invalid_env(self, mock_yaml_load): """Test parse_args_and_config method when the 'env' field is not a dictionary.""" mock_yaml_load.return_value = {"env": "not_a_dict"} parser = TrlParser(dataclass_types=[MyDataclass]) args = ["--arg1", "2", "--arg2", "value", "--config", "config.yaml"] with self.assertRaises(ValueError) as context: parser.parse_args_and_config(args) self.assertEqual(str(context.exception), "`env` field should be a dict in the YAML file.") def test_parse_args_and_config_without_config(self): """Test parse_args_and_config without the `--config` argument.""" parser = TrlParser(dataclass_types=[MyDataclass]) args = ["--arg1", "2", "--arg2", "value"] # Simulate no config, just parse args normally result_args = parser.parse_args_and_config(args) # Check that the arguments are parsed as is self.assertEqual(len(result_args), 1) self.assertIsInstance(result_args[0], MyDataclass) self.assertEqual(result_args[0].arg1, 2) self.assertEqual(result_args[0].arg2, "value") def test_set_defaults_with_config(self): """Test set_defaults_with_config updates the defaults.""" parser = TrlParser(dataclass_types=[MyDataclass]) # Update defaults parser.set_defaults_with_config(arg1=42) # Ensure the default value is updated result_args = parser.parse_args_and_config([]) self.assertEqual(len(result_args), 1) self.assertIsInstance(result_args[0], MyDataclass) self.assertEqual(result_args[0].arg1, 42) def test_parse_args_and_config_with_remaining_strings(self): parser = TrlParser(dataclass_types=[MyDataclass]) args = ["--arg1", "2", "--arg2", "value", "remaining"] # Simulate no config, just parse args normally result_args = parser.parse_args_and_config(args, return_remaining_strings=True) # Check that the arguments are parsed as is self.assertEqual(len(result_args), 2) self.assertIsInstance(result_args[0], MyDataclass) self.assertEqual(result_args[0].arg1, 2) self.assertEqual(result_args[0].arg2, "value") self.assertEqual(result_args[1], ["remaining"]) @patch("builtins.open", mock_open(read_data="remaining_string_in_config: abc")) @patch("yaml.safe_load") def test_parse_args_and_config_with_remaining_strings_in_config_and_args(self, mock_yaml_load): mock_yaml_load.return_value = {"remaining_string_in_config": "abc"} parser = TrlParser(dataclass_types=[MyDataclass]) args = ["--arg1", "2", "--remaining_string_in_args", "def", "--config", "config.yaml"] # Simulate the config being loaded and arguments being passed result_args = parser.parse_args_and_config(args, return_remaining_strings=True) # Check that the arguments are parsed as is self.assertEqual(len(result_args), 2) self.assertIsInstance(result_args[0], MyDataclass) self.assertEqual(result_args[0].arg1, 2) self.assertEqual(result_args[1], ["--remaining_string_in_config", "abc", "--remaining_string_in_args", "def"]) @patch("builtins.open", mock_open(read_data="arg1: 2\narg2: config_value")) @patch("yaml.safe_load") def test_subparsers_with_config_defaults(self, mock_yaml_load): """Test that config defaults are applied to all subparsers.""" mock_yaml_load.return_value = {"arg1": 2, "arg2": "config_value"} # Create the main parser parser = TrlParser() # Add subparsers subparsers = parser.add_subparsers(dest="command", parser_class=TrlParser) # Create a subparser for a specific command subparsers.add_parser("subcommand", dataclass_types=[MyDataclass]) # Parse with config file args = ["subcommand", "--config", "config.yaml"] result_args = parser.parse_args_and_config(args) # Check main parser arguments self.assertEqual(len(result_args), 1) # Check that config values were applied to the subparser self.assertEqual(result_args[0].arg1, 2) # Default from config self.assertEqual(result_args[0].arg2, "config_value") # Default from config @patch("builtins.open", mock_open(read_data="arg1: 2\narg2: config_value")) @patch("yaml.safe_load") def test_subparsers_with_config_defaults_and_arg_override(self, mock_yaml_load): """Test that config defaults are applied to all subparsers.""" mock_yaml_load.return_value = {"arg1": 2, "arg2": "config_value"} # Create the main parser parser = TrlParser() # Add subparsers subparsers = parser.add_subparsers(dest="command", parser_class=TrlParser) # Create a subparser for a specific command subparsers.add_parser("subcommand", dataclass_types=[MyDataclass]) # Test with command line arguments overriding config args = ["subcommand", "--arg1", "3", "--config", "config.yaml"] result_args = parser.parse_args_and_config(args) # Command line arguments should override config self.assertEqual(result_args[0].arg1, 3) self.assertEqual(result_args[0].arg2, "config_value") # Still from config @patch("builtins.open", mock_open(read_data="arg1: 2\nthis_arg_does_not_exist: config_value")) @patch("yaml.safe_load") def test_subparsers_with_config_defaults_and_arg_override_wrong_name(self, mock_yaml_load): """Test that config defaults are applied to all subparsers.""" mock_yaml_load.return_value = {"arg1": 2, "this_arg_does_not_exist": "config_value"} # Create the main parser parser = TrlParser() # Add subparsers subparsers = parser.add_subparsers(dest="command", parser_class=TrlParser) # Create a subparser for a specific command subparsers.add_parser("subcommand", dataclass_types=[MyDataclass]) # Test with command line arguments overriding config args = ["subcommand", "--arg1", "3", "--config", "config.yaml"] with self.assertRaises(ValueError): parser.parse_args_and_config(args) parser.parse_args_and_config(args, fail_with_unknown_args=False) @patch("builtins.open", mock_open(read_data="arg1: 2\narg2: config_value")) @patch("yaml.safe_load") def test_subparsers_multiple_with_config_defaults(self, mock_yaml_load): """Test that config defaults are applied to all subparsers.""" mock_yaml_load.return_value = {"arg1": 2, "arg2": "config_value"} # Create the main parser parser = TrlParser() # Add subparsers subparsers = parser.add_subparsers(dest="command", parser_class=TrlParser) # Create a subparser for a specific command subparsers.add_parser("subcommand0", dataclass_types=[MyDataclass]) subparsers.add_parser("subcommand1", dataclass_types=[MyDataclass]) for idx in range(2): # Parse with config file args = [f"subcommand{idx}", "--config", "config.yaml"] result_args = parser.parse_args_and_config(args) # Check main parser arguments self.assertEqual(len(result_args), 1) # Check that config values were applied to the subparser self.assertEqual(result_args[0].arg1, 2) # Default from config self.assertEqual(result_args[0].arg2, "config_value") # Default from config class TestGetDataset(unittest.TestCase): def test_single_dataset_with_config(self): mixture_config = DatasetMixtureConfig( datasets=[DatasetConfig(path="trl-internal-testing/zen", name="standard_language_modeling")] ) result = get_dataset(mixture_config) expected = load_dataset("trl-internal-testing/zen", "standard_language_modeling") self.assertEqual(expected["train"][:], result["train"][:]) def test_single_dataset_preference_config(self): mixture_config = DatasetMixtureConfig( datasets=[DatasetConfig(path="trl-internal-testing/zen", name="standard_preference")] ) result = get_dataset(mixture_config) expected = load_dataset("trl-internal-testing/zen", "standard_preference") self.assertEqual(expected["train"][:], result["train"][:]) def test_single_dataset_streaming(self): mixture_config = DatasetMixtureConfig( datasets=[DatasetConfig(path="trl-internal-testing/zen", name="standard_language_modeling")], streaming=True, ) result = get_dataset(mixture_config) expected = load_dataset("trl-internal-testing/zen", "standard_language_modeling") self.assertEqual(expected["train"].to_list(), list(result["train"])) def test_dataset_mixture_basic(self): dataset_config1 = DatasetConfig( path="trl-internal-testing/zen", name="standard_prompt_completion", split="train", columns=["prompt"] ) dataset_config2 = DatasetConfig( path="trl-internal-testing/zen", name="standard_preference", split="train", columns=["prompt"] ) mixture_config = DatasetMixtureConfig(datasets=[dataset_config1, dataset_config2]) result = get_dataset(mixture_config) self.assertIsInstance(result, DatasetDict) self.assertIn("train", result) train_dataset = result["train"] self.assertEqual(train_dataset.column_names, ["prompt"]) prompts = train_dataset["prompt"] expected_first_half = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") self.assertEqual(prompts[: len(prompts) // 2], expected_first_half["prompt"]) expected_second_half = load_dataset("trl-internal-testing/zen", "standard_prompt_completion", split="train") self.assertEqual(prompts[len(prompts) // 2 :], expected_second_half["prompt"]) def test_dataset_mixture_with_weights(self): dataset_config1 = DatasetConfig( path="trl-internal-testing/zen", name="standard_prompt_completion", split="train[:50%]", columns=["prompt"] ) dataset_config2 = DatasetConfig( path="trl-internal-testing/zen", name="standard_preference", split="train[:50%]", columns=["prompt"] ) mixture_config = DatasetMixtureConfig(datasets=[dataset_config1, dataset_config2]) result = get_dataset(mixture_config) self.assertIsInstance(result, DatasetDict) self.assertIn("train", result) train_dataset = result["train"] self.assertEqual(train_dataset.column_names, ["prompt"]) prompts = train_dataset["prompt"] expected_first_half = load_dataset("trl-internal-testing/zen", "standard_preference", split="train[:50%]") self.assertEqual(prompts[: len(prompts) // 2], expected_first_half["prompt"]) expected_second_half = load_dataset( "trl-internal-testing/zen", "standard_prompt_completion", split="train[:50%]" ) self.assertEqual(prompts[len(prompts) // 2 :], expected_second_half["prompt"]) def test_dataset_mixture_with_test_split(self): mixture_config = DatasetMixtureConfig( datasets=[DatasetConfig(path="trl-internal-testing/zen", name="standard_language_modeling")], test_split_size=2, ) result = get_dataset(mixture_config) self.assertIsInstance(result, DatasetDict) self.assertIn("train", result) self.assertIn("test", result) self.assertEqual(len(result["train"]), 15) self.assertEqual(len(result["test"]), 2) def test_empty_dataset_mixture_raises_error(self): mixture_config = DatasetMixtureConfig(datasets=[]) with self.assertRaises(ValueError) as context: get_dataset(mixture_config) self.assertIn("No datasets were loaded", str(context.exception)) def test_mixture_multiple_different_configs(self): dataset_config1 = DatasetConfig( path="trl-internal-testing/zen", name="conversational_preference", split="train", columns=["prompt"] ) dataset_config2 = DatasetConfig( path="trl-internal-testing/zen", name="conversational_prompt_only", split="test" ) mixture_config = DatasetMixtureConfig(datasets=[dataset_config1, dataset_config2]) result = get_dataset(mixture_config) self.assertIsInstance(result, DatasetDict) self.assertIn("train", result) self.assertGreater(len(result["train"]), 0) def test_trlparser_parses_yaml_config_correctly(self): # Prepare YAML content exactly like your example # docstyle-ignore yaml_content = """ datasets: - path: trl-internal-testing/zen name: standard_prompt_only - path: trl-internal-testing/zen name: standard_preference columns: - prompt """ # Write YAML to a temporary file with tempfile.NamedTemporaryFile("w+", suffix=".yaml") as tmpfile: tmpfile.write(yaml_content) tmpfile.flush() parser = TrlParser((DatasetMixtureConfig,)) args = parser.parse_args_and_config(args=["--config", tmpfile.name])[0] # Assert that we got DatasetMixtureConfig instance self.assertIsInstance(args, DatasetMixtureConfig) # Assert datasets list length self.assertEqual(len(args.datasets), 2) # Check first dataset dataset_config1 = args.datasets[0] self.assertIsInstance(dataset_config1, DatasetConfig) self.assertEqual(dataset_config1.path, "trl-internal-testing/zen") self.assertEqual(dataset_config1.name, "standard_prompt_only") self.assertIsNone(dataset_config1.columns) # No columns specified # Check second dataset dataset_config2 = args.datasets[1] self.assertIsInstance(dataset_config2, DatasetConfig) self.assertEqual(dataset_config2.path, "trl-internal-testing/zen") self.assertEqual(dataset_config2.name, "standard_preference") self.assertEqual(dataset_config2.columns, ["prompt"]) # Columns specified def test_trlparser_parses_yaml_and_loads_dataset(self): # Prepare YAML content exactly like your example # docstyle-ignore yaml_content = """ datasets: - path: trl-internal-testing/zen name: standard_language_modeling """ # Write YAML to a temporary file with tempfile.NamedTemporaryFile("w+", suffix=".yaml") as tmpfile: tmpfile.write(yaml_content) tmpfile.flush() parser = TrlParser((DatasetMixtureConfig,)) args = parser.parse_args_and_config(args=["--config", tmpfile.name])[0] # Load the dataset using get_dataset result = get_dataset(args) expected = load_dataset("trl-internal-testing/zen", "standard_language_modeling") self.assertEqual(expected["train"][:], result["train"][:])
trl/tests/test_cli_utils.py/0
{ "file_path": "trl/tests/test_cli_utils.py", "repo_id": "trl", "token_count": 7763 }
567
# 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 pytest from datasets import load_dataset from parameterized import parameterized from transformers import AutoModelForCausalLM, AutoModelForSequenceClassification, AutoTokenizer from transformers.testing_utils import require_peft, require_torch_accelerator from transformers.utils import is_peft_available from trl import OnlineDPOConfig, OnlineDPOTrainer from .testing_utils import RandomPairwiseJudge, TrlTestCase, require_llm_blender, require_vllm if is_peft_available(): from peft import LoraConfig, get_peft_model class TestOnlineDPOTrainer(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 self.reward_model_id = "trl-internal-testing/tiny-LlamaForCausalLM-3.2" self.reward_model = AutoModelForSequenceClassification.from_pretrained(self.reward_model_id, num_labels=1) self.reward_tokenizer = AutoTokenizer.from_pretrained(self.reward_model_id) self.reward_tokenizer.pad_token = self.reward_tokenizer.eos_token @parameterized.expand([("standard_prompt_only",), ("conversational_prompt_only",)]) def test_training(self, config_name): training_args = OnlineDPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=3, learning_rate=5.0e-7, eval_strategy="steps", report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", config_name) trainer = OnlineDPOTrainer( model=self.model, reward_model=self.reward_model, args=training_args, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], processing_class=self.tokenizer, reward_processing_class=self.reward_tokenizer, ) trainer.train() # Check if training loss is available self.assertIn("train_loss", trainer.state.log_history[-1]) def test_training_model_str(self): training_args = OnlineDPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=3, learning_rate=5.0e-7, eval_strategy="steps", report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only") trainer = OnlineDPOTrainer( model="trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", reward_model=self.reward_model, args=training_args, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], processing_class=self.tokenizer, reward_processing_class=self.reward_tokenizer, ) trainer.train() # Check if training loss is available self.assertIn("train_loss", trainer.state.log_history[-1]) def test_training_with_ref_model(self): training_args = OnlineDPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=3, learning_rate=5.0e-7, eval_strategy="steps", report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only") trainer = OnlineDPOTrainer( model=self.model, ref_model=self.ref_model, reward_model=self.reward_model, args=training_args, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], processing_class=self.tokenizer, reward_processing_class=self.reward_tokenizer, ) trainer.train() # Check if training loss is available self.assertIn("train_loss", trainer.state.log_history[-1]) def test_ref_model_is_model(self): training_args = OnlineDPOConfig( 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_prompt_only") with self.assertRaises(ValueError): OnlineDPOTrainer( model=self.model, ref_model=self.model, # ref_model can't be the same as model reward_model=self.reward_model, args=training_args, train_dataset=dummy_dataset["train"], processing_class=self.tokenizer, reward_processing_class=self.reward_tokenizer, ) @require_peft def test_training_with_peft(self): lora_config = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM") training_args = OnlineDPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=3, learning_rate=5.0e-7, eval_strategy="steps", report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only") trainer = OnlineDPOTrainer( model=self.model, reward_model=self.reward_model, args=training_args, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], processing_class=self.tokenizer, reward_processing_class=self.reward_tokenizer, peft_config=lora_config, ) trainer.train() # Check if training loss is available self.assertIn("train_loss", trainer.state.log_history[-1]) @require_peft def test_training_with_peft_and_ref_model(self): lora_config = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM") training_args = OnlineDPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=3, learning_rate=5.0e-7, eval_strategy="steps", report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only") trainer = OnlineDPOTrainer( model=self.model, ref_model=self.ref_model, reward_model=self.reward_model, args=training_args, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], processing_class=self.tokenizer, reward_processing_class=self.reward_tokenizer, peft_config=lora_config, ) trainer.train() # Check if training loss is available self.assertIn("train_loss", trainer.state.log_history[-1]) @require_peft def test_training_with_peft_model_and_peft_config(self): model_lora_config = LoraConfig(r=8, lora_alpha=16, lora_dropout=0.1, bias="none", task_type="CAUSAL_LM") model = get_peft_model(self.model, model_lora_config) # we want only the "train adapter" to be trained lora_train_config = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM") training_args = OnlineDPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=3, learning_rate=5.0e-7, eval_strategy="steps", report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only") trainer = OnlineDPOTrainer( model=model, reward_model=self.reward_model, args=training_args, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], processing_class=self.tokenizer, reward_processing_class=self.reward_tokenizer, peft_config=lora_train_config, ) trainer.train() # Check if training loss is available self.assertIn("train_loss", trainer.state.log_history[-1]) @require_llm_blender @parameterized.expand([("standard_prompt_only",), ("conversational_prompt_only",)]) def test_training_with_judge(self, config_name): training_args = OnlineDPOConfig( output_dir=self.tmp_dir, per_device_train_batch_size=2, max_steps=3, learning_rate=5.0e-7, eval_strategy="steps", report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", config_name) trainer = OnlineDPOTrainer( model=self.model, judge=RandomPairwiseJudge(), args=training_args, train_dataset=dummy_dataset["train"], eval_dataset=dummy_dataset["test"], processing_class=self.tokenizer, ) trainer.train() # Check if training loss is available self.assertIn("train_loss", trainer.state.log_history[-1]) @parameterized.expand([("standard_prompt_only",), ("conversational_prompt_only",)]) @require_torch_accelerator @require_vllm @pytest.mark.slow def test_training_with_vllm(self, config_name): model_id = "trl-internal-testing/small-Qwen2ForCausalLM-2.5" # We need a bigger model model = AutoModelForCausalLM.from_pretrained(model_id) tokenizer = AutoTokenizer.from_pretrained(model_id) tokenizer.pad_token = tokenizer.eos_token training_args = OnlineDPOConfig( output_dir=self.tmp_dir, use_vllm=True, gpu_memory_utilization=0.2, report_to="none", ) dummy_dataset = load_dataset("trl-internal-testing/zen", config_name) trainer = OnlineDPOTrainer( model=model, reward_model=self.reward_model, args=training_args, train_dataset=dummy_dataset["train"], processing_class=tokenizer, reward_processing_class=self.reward_tokenizer, ) trainer.train() # Check if training loss is available self.assertIn("train_loss", trainer.state.log_history[-1])
trl/tests/test_online_dpo_trainer.py/0
{ "file_path": "trl/tests/test_online_dpo_trainer.py", "repo_id": "trl", "token_count": 5171 }
568
# 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. __version__ = "0.22.0.dev0" from typing import TYPE_CHECKING from .import_utils import OptionalDependencyNotAvailable, _LazyModule, is_diffusers_available _import_structure = { "scripts": ["DatasetMixtureConfig", "ScriptArguments", "TrlParser", "get_dataset", "init_zero_verbose"], "data_utils": [ "apply_chat_template", "extract_prompt", "is_conversational", "is_conversational_from_value", "maybe_apply_chat_template", "maybe_convert_to_chatml", "maybe_extract_prompt", "maybe_unpair_preference_dataset", "pack_dataset", "prepare_multimodal_messages", "truncate_dataset", "unpair_preference_dataset", ], "extras": ["BestOfNSampler"], "models": [ "SUPPORTED_ARCHITECTURES", "AutoModelForCausalLMWithValueHead", "AutoModelForSeq2SeqLMWithValueHead", "PreTrainedModelWrapper", "clone_chat_template", "create_reference_model", "setup_chat_format", ], "trainer": [ "AlignPropConfig", "AlignPropTrainer", "AllTrueJudge", "BaseBinaryJudge", "BaseJudge", "BasePairwiseJudge", "BaseRankJudge", "BCOConfig", "BCOTrainer", "CPOConfig", "CPOTrainer", "DPOConfig", "DPOTrainer", "FDivergenceConstants", "FDivergenceType", "GKDConfig", "GKDTrainer", "GRPOConfig", "GRPOTrainer", "HfPairwiseJudge", "IterativeSFTConfig", "IterativeSFTTrainer", "KTOConfig", "KTOTrainer", "LogCompletionsCallback", "ModelConfig", "NashMDConfig", "NashMDTrainer", "OnlineDPOConfig", "OnlineDPOTrainer", "OpenAIPairwiseJudge", "ORPOConfig", "ORPOTrainer", "PairRMJudge", "PPOConfig", "PPOTrainer", "PRMConfig", "PRMTrainer", "RewardConfig", "RewardTrainer", "RLOOConfig", "RLOOTrainer", "SFTConfig", "SFTTrainer", "WinRateCallback", "XPOConfig", "XPOTrainer", ], "trainer.callbacks": ["BEMACallback", "MergeModelCallback", "RichProgressCallback", "SyncRefModelCallback"], "trainer.utils": ["get_kbit_device_map", "get_peft_config", "get_quantization_config"], } try: if not is_diffusers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: _import_structure["models"].extend( [ "DDPOPipelineOutput", "DDPOSchedulerOutput", "DDPOStableDiffusionPipeline", "DefaultDDPOStableDiffusionPipeline", ] ) _import_structure["trainer"].extend(["DDPOConfig", "DDPOTrainer"]) if TYPE_CHECKING: from .data_utils import ( apply_chat_template, extract_prompt, is_conversational, is_conversational_from_value, maybe_apply_chat_template, maybe_convert_to_chatml, maybe_extract_prompt, maybe_unpair_preference_dataset, pack_dataset, prepare_multimodal_messages, truncate_dataset, unpair_preference_dataset, ) from .extras import BestOfNSampler from .models import ( SUPPORTED_ARCHITECTURES, AutoModelForCausalLMWithValueHead, AutoModelForSeq2SeqLMWithValueHead, PreTrainedModelWrapper, clone_chat_template, create_reference_model, setup_chat_format, ) from .scripts import DatasetMixtureConfig, ScriptArguments, TrlParser, get_dataset, init_zero_verbose from .trainer import ( AlignPropConfig, AlignPropTrainer, AllTrueJudge, BaseBinaryJudge, BaseJudge, BasePairwiseJudge, BaseRankJudge, BCOConfig, BCOTrainer, CPOConfig, CPOTrainer, DPOConfig, DPOTrainer, FDivergenceConstants, FDivergenceType, GKDConfig, GKDTrainer, GRPOConfig, GRPOTrainer, HfPairwiseJudge, IterativeSFTConfig, IterativeSFTTrainer, KTOConfig, KTOTrainer, LogCompletionsCallback, ModelConfig, NashMDConfig, NashMDTrainer, OnlineDPOConfig, OnlineDPOTrainer, OpenAIPairwiseJudge, ORPOConfig, ORPOTrainer, PairRMJudge, PPOConfig, PPOTrainer, PRMConfig, PRMTrainer, RewardConfig, RewardTrainer, RLOOConfig, RLOOTrainer, SFTConfig, SFTTrainer, WinRateCallback, XPOConfig, XPOTrainer, ) from .trainer.callbacks import BEMACallback, MergeModelCallback, RichProgressCallback, SyncRefModelCallback from .trainer.utils import get_kbit_device_map, get_peft_config, get_quantization_config try: if not is_diffusers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .models import ( DDPOPipelineOutput, DDPOSchedulerOutput, DDPOStableDiffusionPipeline, DefaultDDPOStableDiffusionPipeline, ) from .trainer import DDPOConfig, DDPOTrainer else: import sys sys.modules[__name__] = _LazyModule( __name__, globals()["__file__"], _import_structure, module_spec=__spec__, extra_objects={"__version__": __version__}, )
trl/trl/__init__.py/0
{ "file_path": "trl/trl/__init__.py", "repo_id": "trl", "token_count": 2968 }
569
# 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 importlib import os from itertools import chain from types import ModuleType from typing import Any from packaging import version from transformers.utils.import_utils import _is_package_available LIGER_KERNEL_MIN_VERSION = "0.5.8" # Use same as transformers.utils.import_utils _deepspeed_available = _is_package_available("deepspeed") _diffusers_available = _is_package_available("diffusers") _fastapi_available = _is_package_available("fastapi") _is_liger_kernel_available, _liger_kernel_version = _is_package_available("liger_kernel", return_version=True) _llm_blender_available = _is_package_available("llm_blender") _mergekit_available = _is_package_available("mergekit") _pydantic_available = _is_package_available("pydantic") _requests_available = _is_package_available("requests") _unsloth_available = _is_package_available("unsloth") _uvicorn_available = _is_package_available("uvicorn") _vllm_available = _is_package_available("vllm") _vllm_ascend_available = _is_package_available("vllm_ascend") _joblib_available = _is_package_available("joblib") def is_deepspeed_available() -> bool: return _deepspeed_available def is_diffusers_available() -> bool: return _diffusers_available def is_fastapi_available() -> bool: return _fastapi_available def is_liger_kernel_available(min_version: str = LIGER_KERNEL_MIN_VERSION) -> bool: return _is_liger_kernel_available and version.parse(_liger_kernel_version) >= version.parse(min_version) def is_llm_blender_available() -> bool: return _llm_blender_available def is_mergekit_available() -> bool: return _mergekit_available def is_pydantic_available() -> bool: return _pydantic_available def is_requests_available() -> bool: return _requests_available def is_unsloth_available() -> bool: return _unsloth_available def is_uvicorn_available() -> bool: return _uvicorn_available def is_vllm_available() -> bool: return _vllm_available def is_vllm_ascend_available() -> bool: return _vllm_ascend_available def is_joblib_available() -> bool: return _joblib_available class _LazyModule(ModuleType): """ Module class that surfaces all objects but only performs associated imports when the objects are requested. """ # Very heavily inspired by optuna.integration._IntegrationModule # https://github.com/optuna/optuna/blob/master/optuna/integration/__init__.py def __init__(self, name, module_file, import_structure, module_spec=None, extra_objects=None): super().__init__(name) self._modules = set(import_structure.keys()) self._class_to_module = {} for key, values in import_structure.items(): for value in values: self._class_to_module[value] = key # Needed for autocompletion in an IDE self.__all__ = list(import_structure.keys()) + list(chain(*import_structure.values())) self.__file__ = module_file self.__spec__ = module_spec self.__path__ = [os.path.dirname(module_file)] self._objects = {} if extra_objects is None else extra_objects self._name = name self._import_structure = import_structure # Needed for autocompletion in an IDE def __dir__(self): result = super().__dir__() # The elements of self.__all__ that are submodules may or may not be in the dir already, depending on whether # they have been accessed or not. So we only add the elements of self.__all__ that are not already in the dir. for attr in self.__all__: if attr not in result: result.append(attr) return result def __getattr__(self, name: str) -> Any: if name in self._objects: return self._objects[name] if name in self._modules: value = self._get_module(name) elif name in self._class_to_module.keys(): module = self._get_module(self._class_to_module[name]) value = getattr(module, name) else: raise AttributeError(f"module {self.__name__} has no attribute {name}") setattr(self, name, value) return value def _get_module(self, module_name: str): try: return importlib.import_module("." + module_name, self.__name__) except Exception as e: raise RuntimeError( f"Failed to import {self.__name__}.{module_name} because of the following error (look up to see its" f" traceback):\n{e}" ) from e def __reduce__(self): return (self.__class__, (self._name, self.__file__, self._import_structure)) class OptionalDependencyNotAvailable(BaseException): """Internally used error class for signalling an optional dependency was not found."""
trl/trl/import_utils.py/0
{ "file_path": "trl/trl/import_utils.py", "repo_id": "trl", "token_count": 1960 }
570
# Copyright 2020-2025 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # /// script # dependencies = [ # "trl @ git+https://github.com/huggingface/trl.git", # ] # /// import os import platform from importlib.metadata import version import torch from accelerate.commands.config import default_config_file, load_config_from_file from transformers import is_bitsandbytes_available from transformers.utils import is_openai_available, is_peft_available from .. import __version__ from ..import_utils import ( is_deepspeed_available, is_diffusers_available, is_liger_kernel_available, is_llm_blender_available, is_vllm_available, ) from .utils import get_git_commit_hash def print_env(): devices = None if torch.cuda.is_available(): devices = [torch.cuda.get_device_name(i) for i in range(torch.cuda.device_count())] elif torch.backends.mps.is_available(): devices = ["MPS"] elif torch.xpu.is_available(): devices = [torch.xpu.get_device_name(i) for i in range(torch.xpu.device_count())] accelerate_config = accelerate_config_str = "not found" # Get the default from the config file. if os.path.isfile(default_config_file): accelerate_config = load_config_from_file(default_config_file).to_dict() accelerate_config_str = ( "\n" + "\n".join([f" - {prop}: {val}" for prop, val in accelerate_config.items()]) if isinstance(accelerate_config, dict) else accelerate_config ) commit_hash = get_git_commit_hash("trl") info = { "Platform": platform.platform(), "Python version": platform.python_version(), "TRL version": f"{__version__}+{commit_hash[:7]}" if commit_hash else __version__, "PyTorch version": version("torch"), "accelerator(s)": ", ".join(devices) if devices is not None else "cpu", "Transformers version": version("transformers"), "Accelerate version": version("accelerate"), "Accelerate config": accelerate_config_str, "Datasets version": version("datasets"), "HF Hub version": version("huggingface_hub"), "bitsandbytes version": version("bitsandbytes") if is_bitsandbytes_available() else "not installed", "DeepSpeed version": version("deepspeed") if is_deepspeed_available() else "not installed", "Diffusers version": version("diffusers") if is_diffusers_available() else "not installed", "Liger-Kernel version": version("liger_kernel") if is_liger_kernel_available() else "not installed", "LLM-Blender version": version("llm_blender") if is_llm_blender_available() else "not installed", "OpenAI version": version("openai") if is_openai_available() else "not installed", "PEFT version": version("peft") if is_peft_available() else "not installed", "vLLM version": version("vllm") if is_vllm_available() else "not installed", } info_str = "\n".join([f"- {prop}: {val}" for prop, val in info.items()]) print(f"\nCopy-paste the following information when reporting an issue:\n\n{info_str}\n") # noqa if __name__ == "__main__": print_env()
trl/trl/scripts/env.py/0
{ "file_path": "trl/trl/scripts/env.py", "repo_id": "trl", "token_count": 1296 }
571
# 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 os import textwrap import warnings from collections import defaultdict from concurrent import futures from pathlib import Path from typing import Any, Callable, Optional, Union import torch from accelerate import Accelerator, logging from accelerate.utils import ProjectConfiguration, set_seed from huggingface_hub import PyTorchModelHubMixin from transformers import is_wandb_available from ..models import DDPOStableDiffusionPipeline from .ddpo_config import DDPOConfig from .utils import PerPromptStatTracker, generate_model_card, get_comet_experiment_url if is_wandb_available(): import wandb logger = logging.get_logger(__name__) class DDPOTrainer(PyTorchModelHubMixin): """ The DDPOTrainer uses Deep Diffusion Policy Optimization to optimise diffusion models. Note, this trainer is heavily inspired by the work here: https://github.com/kvablack/ddpo-pytorch As of now only Stable Diffusion based pipelines are supported Attributes: **config** (`DDPOConfig`) -- Configuration object for DDPOTrainer. Check the documentation of `PPOConfig` for more: details. **reward_function** (Callable[[torch.Tensor, tuple[str], tuple[Any]], torch.Tensor]) -- Reward function to be used: **prompt_function** (Callable[[], tuple[str, Any]]) -- Function to generate prompts to guide model **sd_pipeline** (`DDPOStableDiffusionPipeline`) -- Stable Diffusion pipeline to be used for training. **image_samples_hook** (Optional[Callable[[Any, Any, Any], Any]]) -- Hook to be called to log images """ _tag_names = ["trl", "ddpo"] def __init__( self, config: DDPOConfig, reward_function: Callable[[torch.Tensor, tuple[str], tuple[Any]], torch.Tensor], prompt_function: Callable[[], tuple[str, Any]], sd_pipeline: DDPOStableDiffusionPipeline, image_samples_hook: Optional[Callable[[Any, Any, Any], Any]] = None, ): warnings.warn( "DDPOTrainer is deprecated and will be removed in version 0.23.0.", DeprecationWarning, ) if image_samples_hook is None: logger.warning("No image_samples_hook provided; no images will be logged") self.prompt_fn = prompt_function self.reward_fn = reward_function self.config = config self.image_samples_callback = image_samples_hook accelerator_project_config = ProjectConfiguration(**self.config.project_kwargs) if self.config.resume_from: self.config.resume_from = os.path.normpath(os.path.expanduser(self.config.resume_from)) if "checkpoint_" not in os.path.basename(self.config.resume_from): # get the most recent checkpoint in this directory checkpoints = list( filter( lambda x: "checkpoint_" in x, os.listdir(self.config.resume_from), ) ) if len(checkpoints) == 0: raise ValueError(f"No checkpoints found in {self.config.resume_from}") checkpoint_numbers = sorted([int(x.split("_")[-1]) for x in checkpoints]) self.config.resume_from = os.path.join( self.config.resume_from, f"checkpoint_{checkpoint_numbers[-1]}", ) accelerator_project_config.iteration = checkpoint_numbers[-1] + 1 # number of timesteps within each trajectory to train on self.num_train_timesteps = int(self.config.sample_num_steps * self.config.train_timestep_fraction) self.accelerator = Accelerator( log_with=self.config.log_with, mixed_precision=self.config.mixed_precision, project_config=accelerator_project_config, # we always accumulate gradients across timesteps; we want config.train.gradient_accumulation_steps to be the # number of *samples* we accumulate across, so we need to multiply by the number of training timesteps to get # the total number of optimizer steps to accumulate across. gradient_accumulation_steps=self.config.train_gradient_accumulation_steps * self.num_train_timesteps, **self.config.accelerator_kwargs, ) is_okay, message = self._config_check() if not is_okay: raise ValueError(message) is_using_tensorboard = config.log_with is not None and config.log_with == "tensorboard" if self.accelerator.is_main_process: self.accelerator.init_trackers( self.config.tracker_project_name, config=dict(ddpo_trainer_config=config.to_dict()) if not is_using_tensorboard else config.to_dict(), init_kwargs=self.config.tracker_kwargs, ) logger.info(f"\n{config}") set_seed(self.config.seed, device_specific=True) self.sd_pipeline = sd_pipeline self.sd_pipeline.set_progress_bar_config( position=1, disable=not self.accelerator.is_local_main_process, leave=False, desc="Timestep", dynamic_ncols=True, ) # For mixed precision training we cast all non-trainable weights (vae, non-lora text_encoder and non-lora unet) to half-precision # as these weights are only used for inference, keeping weights in full precision is not required. if self.accelerator.mixed_precision == "fp16": inference_dtype = torch.float16 elif self.accelerator.mixed_precision == "bf16": inference_dtype = torch.bfloat16 else: inference_dtype = torch.float32 self.sd_pipeline.vae.to(self.accelerator.device, dtype=inference_dtype) self.sd_pipeline.text_encoder.to(self.accelerator.device, dtype=inference_dtype) self.sd_pipeline.unet.to(self.accelerator.device, dtype=inference_dtype) trainable_layers = self.sd_pipeline.get_trainable_layers() self.accelerator.register_save_state_pre_hook(self._save_model_hook) self.accelerator.register_load_state_pre_hook(self._load_model_hook) # Enable TF32 for faster training on Ampere GPUs, # cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices if self.config.allow_tf32: torch.backends.cuda.matmul.allow_tf32 = True self.optimizer = self._setup_optimizer( trainable_layers.parameters() if not isinstance(trainable_layers, list) else trainable_layers ) self.neg_prompt_embed = self.sd_pipeline.text_encoder( self.sd_pipeline.tokenizer( [""] if self.config.negative_prompts is None else self.config.negative_prompts, return_tensors="pt", padding="max_length", truncation=True, max_length=self.sd_pipeline.tokenizer.model_max_length, ).input_ids.to(self.accelerator.device) )[0] if config.per_prompt_stat_tracking: self.stat_tracker = PerPromptStatTracker( config.per_prompt_stat_tracking_buffer_size, config.per_prompt_stat_tracking_min_count, ) # NOTE: for some reason, autocast is necessary for non-lora training but for lora training it isn't necessary and it uses # more memory self.autocast = self.sd_pipeline.autocast or self.accelerator.autocast if hasattr(self.sd_pipeline, "use_lora") and self.sd_pipeline.use_lora: unet, self.optimizer = self.accelerator.prepare(trainable_layers, self.optimizer) self.trainable_layers = list(filter(lambda p: p.requires_grad, unet.parameters())) else: self.trainable_layers, self.optimizer = self.accelerator.prepare(trainable_layers, self.optimizer) if self.config.async_reward_computation: self.executor = futures.ThreadPoolExecutor(max_workers=config.max_workers) if config.resume_from: logger.info(f"Resuming from {config.resume_from}") self.accelerator.load_state(config.resume_from) self.first_epoch = int(config.resume_from.split("_")[-1]) + 1 else: self.first_epoch = 0 def compute_rewards(self, prompt_image_pairs, is_async=False): if not is_async: rewards = [] for images, prompts, prompt_metadata in prompt_image_pairs: reward, reward_metadata = self.reward_fn(images, prompts, prompt_metadata) rewards.append( ( torch.as_tensor(reward, device=self.accelerator.device), reward_metadata, ) ) else: rewards = self.executor.map(lambda x: self.reward_fn(*x), prompt_image_pairs) rewards = [ (torch.as_tensor(reward.result(), device=self.accelerator.device), reward_metadata.result()) for reward, reward_metadata in rewards ] return zip(*rewards) def step(self, epoch: int, global_step: int): """ Perform a single step of training. Args: epoch (int): The current epoch. global_step (int): The current global step. Side Effects: - Model weights are updated - Logs the statistics to the accelerator trackers. - If `self.image_samples_callback` is not None, it will be called with the prompt_image_pairs, global_step, and the accelerator tracker. Returns: global_step (int): The updated global step. """ samples, prompt_image_data = self._generate_samples( iterations=self.config.sample_num_batches_per_epoch, batch_size=self.config.sample_batch_size, ) # collate samples into dict where each entry has shape (num_batches_per_epoch * sample.batch_size, ...) samples = {k: torch.cat([s[k] for s in samples]) for k in samples[0].keys()} rewards, rewards_metadata = self.compute_rewards( prompt_image_data, is_async=self.config.async_reward_computation ) for i, image_data in enumerate(prompt_image_data): image_data.extend([rewards[i], rewards_metadata[i]]) if self.image_samples_callback is not None: self.image_samples_callback(prompt_image_data, global_step, self.accelerator.trackers[0]) rewards = torch.cat(rewards) rewards = self.accelerator.gather(rewards).cpu().numpy() self.accelerator.log( { "reward": rewards, "epoch": epoch, "reward_mean": rewards.mean(), "reward_std": rewards.std(), }, step=global_step, ) if self.config.per_prompt_stat_tracking: # gather the prompts across processes prompt_ids = self.accelerator.gather(samples["prompt_ids"]).cpu().numpy() prompts = self.sd_pipeline.tokenizer.batch_decode(prompt_ids, skip_special_tokens=True) advantages = self.stat_tracker.update(prompts, rewards) else: advantages = (rewards - rewards.mean()) / (rewards.std() + 1e-8) # ungather advantages; keep the entries corresponding to the samples on this process samples["advantages"] = ( torch.as_tensor(advantages) .reshape(self.accelerator.num_processes, -1)[self.accelerator.process_index] .to(self.accelerator.device) ) del samples["prompt_ids"] total_batch_size, num_timesteps = samples["timesteps"].shape for inner_epoch in range(self.config.train_num_inner_epochs): # shuffle samples along batch dimension perm = torch.randperm(total_batch_size, device=self.accelerator.device) samples = {k: v[perm] for k, v in samples.items()} # shuffle along time dimension independently for each sample # still trying to understand the code below perms = torch.stack( [torch.randperm(num_timesteps, device=self.accelerator.device) for _ in range(total_batch_size)] ) for key in ["timesteps", "latents", "next_latents", "log_probs"]: samples[key] = samples[key][ torch.arange(total_batch_size, device=self.accelerator.device)[:, None], perms, ] original_keys = samples.keys() original_values = samples.values() # rebatch them as user defined train_batch_size is different from sample_batch_size reshaped_values = [v.reshape(-1, self.config.train_batch_size, *v.shape[1:]) for v in original_values] # Transpose the list of original values transposed_values = zip(*reshaped_values) # Create new dictionaries for each row of transposed values samples_batched = [dict(zip(original_keys, row_values)) for row_values in transposed_values] self.sd_pipeline.unet.train() global_step = self._train_batched_samples(inner_epoch, epoch, global_step, samples_batched) # ensure optimization step at the end of the inner epoch if not self.accelerator.sync_gradients: raise ValueError( "Optimization step should have been performed by this point. Please check calculated gradient accumulation settings." ) if epoch != 0 and epoch % self.config.save_freq == 0 and self.accelerator.is_main_process: self.accelerator.save_state() return global_step def calculate_loss(self, latents, timesteps, next_latents, log_probs, advantages, embeds): """ Calculate the loss for a batch of an unpacked sample Args: latents (torch.Tensor): The latents sampled from the diffusion model, shape: [batch_size, num_channels_latents, height, width] timesteps (torch.Tensor): The timesteps sampled from the diffusion model, shape: [batch_size] next_latents (torch.Tensor): The next latents sampled from the diffusion model, shape: [batch_size, num_channels_latents, height, width] log_probs (torch.Tensor): The log probabilities of the latents, shape: [batch_size] advantages (torch.Tensor): The advantages of the latents, shape: [batch_size] embeds (torch.Tensor): The embeddings of the prompts, shape: [2*batch_size or batch_size, ...] Note: the "or" is because if train_cfg is True, the expectation is that negative prompts are concatenated to the embeds Returns: loss (torch.Tensor), approx_kl (torch.Tensor), clipfrac (torch.Tensor) (all of these are of shape (1,)) """ with self.autocast(): if self.config.train_cfg: noise_pred = self.sd_pipeline.unet( torch.cat([latents] * 2), torch.cat([timesteps] * 2), embeds, ).sample noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) noise_pred = noise_pred_uncond + self.config.sample_guidance_scale * ( noise_pred_text - noise_pred_uncond ) else: noise_pred = self.sd_pipeline.unet( latents, timesteps, embeds, ).sample # compute the log prob of next_latents given latents under the current model scheduler_step_output = self.sd_pipeline.scheduler_step( noise_pred, timesteps, latents, eta=self.config.sample_eta, prev_sample=next_latents, ) log_prob = scheduler_step_output.log_probs advantages = torch.clamp( advantages, -self.config.train_adv_clip_max, self.config.train_adv_clip_max, ) ratio = torch.exp(log_prob - log_probs) loss = self.loss(advantages, self.config.train_clip_range, ratio) approx_kl = 0.5 * torch.mean((log_prob - log_probs) ** 2) clipfrac = torch.mean((torch.abs(ratio - 1.0) > self.config.train_clip_range).float()) return loss, approx_kl, clipfrac def loss( self, advantages: torch.Tensor, clip_range: float, ratio: torch.Tensor, ): unclipped_loss = -advantages * ratio clipped_loss = -advantages * torch.clamp( ratio, 1.0 - clip_range, 1.0 + clip_range, ) return torch.mean(torch.maximum(unclipped_loss, clipped_loss)) def _setup_optimizer(self, trainable_layers_parameters): if self.config.train_use_8bit_adam: import bitsandbytes optimizer_cls = bitsandbytes.optim.AdamW8bit else: optimizer_cls = torch.optim.AdamW return optimizer_cls( trainable_layers_parameters, lr=self.config.train_learning_rate, betas=(self.config.train_adam_beta1, self.config.train_adam_beta2), weight_decay=self.config.train_adam_weight_decay, eps=self.config.train_adam_epsilon, ) def _save_model_hook(self, models, weights, output_dir): self.sd_pipeline.save_checkpoint(models, weights, output_dir) weights.pop() # ensures that accelerate doesn't try to handle saving of the model def _load_model_hook(self, models, input_dir): self.sd_pipeline.load_checkpoint(models, input_dir) models.pop() # ensures that accelerate doesn't try to handle loading of the model def _generate_samples(self, iterations, batch_size): """ Generate samples from the model Args: iterations (int): Number of iterations to generate samples for batch_size (int): Batch size to use for sampling Returns: samples (list[dict[str, torch.Tensor]]), prompt_image_pairs (list[list[Any]]) """ samples = [] prompt_image_pairs = [] self.sd_pipeline.unet.eval() sample_neg_prompt_embeds = self.neg_prompt_embed.repeat(batch_size, 1, 1) for _ in range(iterations): prompts, prompt_metadata = zip(*[self.prompt_fn() for _ in range(batch_size)]) prompt_ids = self.sd_pipeline.tokenizer( prompts, return_tensors="pt", padding="max_length", truncation=True, max_length=self.sd_pipeline.tokenizer.model_max_length, ).input_ids.to(self.accelerator.device) prompt_embeds = self.sd_pipeline.text_encoder(prompt_ids)[0] with self.autocast(): sd_output = self.sd_pipeline( prompt_embeds=prompt_embeds, negative_prompt_embeds=sample_neg_prompt_embeds, num_inference_steps=self.config.sample_num_steps, guidance_scale=self.config.sample_guidance_scale, eta=self.config.sample_eta, output_type="pt", ) images = sd_output.images latents = sd_output.latents log_probs = sd_output.log_probs latents = torch.stack(latents, dim=1) # (batch_size, num_steps + 1, ...) log_probs = torch.stack(log_probs, dim=1) # (batch_size, num_steps, 1) timesteps = self.sd_pipeline.scheduler.timesteps.repeat(batch_size, 1) # (batch_size, num_steps) samples.append( { "prompt_ids": prompt_ids, "prompt_embeds": prompt_embeds, "timesteps": timesteps, "latents": latents[:, :-1], # each entry is the latent before timestep t "next_latents": latents[:, 1:], # each entry is the latent after timestep t "log_probs": log_probs, "negative_prompt_embeds": sample_neg_prompt_embeds, } ) prompt_image_pairs.append([images, prompts, prompt_metadata]) return samples, prompt_image_pairs def _train_batched_samples(self, inner_epoch, epoch, global_step, batched_samples): """ Train on a batch of samples. Main training segment Args: inner_epoch (int): The current inner epoch epoch (int): The current epoch global_step (int): The current global step batched_samples (list[dict[str, torch.Tensor]]): The batched samples to train on Side Effects: - Model weights are updated - Logs the statistics to the accelerator trackers. Returns: global_step (int): The updated global step """ info = defaultdict(list) for _i, sample in enumerate(batched_samples): if self.config.train_cfg: # concat negative prompts to sample prompts to avoid two forward passes embeds = torch.cat([sample["negative_prompt_embeds"], sample["prompt_embeds"]]) else: embeds = sample["prompt_embeds"] for j in range(self.num_train_timesteps): with self.accelerator.accumulate(self.sd_pipeline.unet): loss, approx_kl, clipfrac = self.calculate_loss( sample["latents"][:, j], sample["timesteps"][:, j], sample["next_latents"][:, j], sample["log_probs"][:, j], sample["advantages"], embeds, ) info["approx_kl"].append(approx_kl) info["clipfrac"].append(clipfrac) info["loss"].append(loss) self.accelerator.backward(loss) if self.accelerator.sync_gradients: self.accelerator.clip_grad_norm_( self.trainable_layers.parameters() if not isinstance(self.trainable_layers, list) else self.trainable_layers, self.config.train_max_grad_norm, ) self.optimizer.step() self.optimizer.zero_grad() # Checks if the accelerator has performed an optimization step behind the scenes if self.accelerator.sync_gradients: # log training-related stuff info = {k: torch.mean(torch.stack(v)) for k, v in info.items()} info = self.accelerator.reduce(info, reduction="mean") info.update({"epoch": epoch, "inner_epoch": inner_epoch}) self.accelerator.log(info, step=global_step) global_step += 1 info = defaultdict(list) return global_step def _config_check(self) -> tuple[bool, str]: samples_per_epoch = ( self.config.sample_batch_size * self.accelerator.num_processes * self.config.sample_num_batches_per_epoch ) total_train_batch_size = ( self.config.train_batch_size * self.accelerator.num_processes * self.config.train_gradient_accumulation_steps ) if not self.config.sample_batch_size >= self.config.train_batch_size: return ( False, f"Sample batch size ({self.config.sample_batch_size}) must be greater than or equal to the train batch size ({self.config.train_batch_size})", ) if not self.config.sample_batch_size % self.config.train_batch_size == 0: return ( False, f"Sample batch size ({self.config.sample_batch_size}) must be divisible by the train batch size ({self.config.train_batch_size})", ) if not samples_per_epoch % total_train_batch_size == 0: return ( False, f"Number of samples per epoch ({samples_per_epoch}) must be divisible by the total train batch size ({total_train_batch_size})", ) return True, "" def train(self, epochs: Optional[int] = None): """ Train the model for a given number of epochs """ global_step = 0 if epochs is None: epochs = self.config.num_epochs for epoch in range(self.first_epoch, epochs): global_step = self.step(epoch, global_step) def _save_pretrained(self, save_directory): self.sd_pipeline.save_pretrained(save_directory) self.create_model_card() # Ensure the model card is saved along with the checkpoint def _save_checkpoint(self, model, trial): if self.args.hub_model_id is None: model_name = Path(self.args.output_dir).name else: model_name = self.args.hub_model_id.split("/")[-1] self.create_model_card(model_name=model_name) super()._save_checkpoint(model, trial) def create_model_card( self, model_name: Optional[str] = None, dataset_name: Optional[str] = None, tags: Union[str, list[str], None] = None, ): """ Creates a draft of a model card using the information available to the `Trainer`. Args: model_name (`str` or `None`, *optional*, defaults to `None`): Name of the model. dataset_name (`str` or `None`, *optional*, defaults to `None`): Name of the dataset used for training. tags (`str`, `list[str]` or `None`, *optional*, defaults to `None`): Tags to be associated with the model card. """ if not self.is_world_process_zero(): return if hasattr(self.model.config, "_name_or_path") and not os.path.isdir(self.model.config._name_or_path): base_model = self.model.config._name_or_path else: base_model = None # normalize `tags` to a mutable set if tags is None: tags = set() elif isinstance(tags, str): tags = {tags} else: tags = set(tags) if hasattr(self.model.config, "unsloth_version"): tags.add("unsloth") tags.update(self._tag_names) # docstyle-ignore citation = textwrap.dedent("""\ @inproceedings{black2024training, title = {{Training Diffusion Models with Reinforcement Learning}}, author = {Kevin Black and Michael Janner and Yilun Du and Ilya Kostrikov and Sergey Levine}, year = 2024, booktitle = {The Twelfth International Conference on Learning Representations, {ICLR} 2024, Vienna, Austria, May 7-11, 2024}, publisher = {OpenReview.net}, url = {https://openreview.net/forum?id=YCWjhGrJFD}, }""") model_card = generate_model_card( base_model=base_model, model_name=model_name, hub_model_id=self.hub_model_id, dataset_name=dataset_name, tags=tags, wandb_url=wandb.run.url if is_wandb_available() and wandb.run is not None else None, comet_url=get_comet_experiment_url(), trainer_name="DDPO", trainer_citation=citation, paper_title="Training Diffusion Models with Reinforcement Learning", paper_id="2305.13301", ) model_card.save(os.path.join(self.args.output_dir, "README.md"))
trl/trl/trainer/ddpo_trainer.py/0
{ "file_path": "trl/trl/trainer/ddpo_trainer.py", "repo_id": "trl", "token_count": 13344 }
572
# 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 os import textwrap from functools import wraps from pathlib import Path from typing import Any, Callable, Optional, Union import datasets import jinja2 import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.data from accelerate import logging from datasets import Dataset from packaging import version from torch.utils.data import DataLoader, IterableDataset from transformers import ( AutoModelForCausalLM, BaseImageProcessor, DataCollator, FeatureExtractionMixin, GenerationConfig, PreTrainedModel, PreTrainedTokenizerBase, ProcessorMixin, Trainer, TrainerCallback, is_apex_available, is_wandb_available, ) from transformers.trainer_utils import EvalPrediction, seed_worker from transformers.training_args import OptimizerNames from transformers.utils import is_peft_available, is_sagemaker_mp_enabled from ..data_utils import apply_chat_template, is_conversational, maybe_apply_chat_template from ..import_utils import is_vllm_available from ..models import create_reference_model, prepare_peft_model from ..models.utils import unwrap_model_for_generation from .judges import BasePairwiseJudge from .online_dpo_config import OnlineDPOConfig from .utils import ( SIMPLE_CHAT_TEMPLATE, DPODataCollatorWithPadding, disable_dropout_in_model, empty_cache, generate_model_card, get_comet_experiment_url, get_reward, prepare_deepspeed, truncate_right, ) if is_peft_available(): from peft import PeftModel if is_apex_available(): from apex import amp if is_sagemaker_mp_enabled(): from smdistributed.modelparallel import __version__ as SMP_VERSION IS_SAGEMAKER_MP_POST_1_10 = version.parse(SMP_VERSION) >= version.parse("1.10") else: IS_SAGEMAKER_MP_POST_1_10 = False if is_vllm_available(): from vllm import LLM, SamplingParams if is_wandb_available(): import wandb logger = logging.get_logger(__name__) class OnlineDPOTrainer(Trainer): r""" Initialize OnlineDPOTrainer. Args: model (`Union[str, nn.Module, PreTrainedModel]`): Model to be trained. Can be either: - A string, being the *model id* of a pretrained model hosted inside a model repo on huggingface.co, or a path to a *directory* containing model weights saved using [`~transformers.PreTrainedModel.save_pretrained`], e.g., `'./my_model_directory/'`. The model is loaded using [`~transformers.AutoModelForCausalLM.from_pretrained`] with the keyword arguments in `args.model_init_kwargs`. - A [`~transformers.PreTrainedModel`] object. Only causal language models are supported. ref_model (`transformers.PreTrainedModel` or `torch.nn.Module` or `None`): The reference model to use for training. If None is specified, the reference model will be created from the model. reward_model (`transformers.PreTrainedModel` or `torch.nn.Module` or `None`): The reward model to score completions with, preferably an `AutoModelForSequenceClassification`. judge (`BasePairwiseJudge`): The judge to use for pairwise comparison of model completions. args (`OnlineDPOConfig`): The online DPO config arguments to use for training. data_collator (`transformers.DataCollator`): The data collator to use for training. If None is specified, the default data collator (`DPODataCollatorWithPadding`) will be used which will pad the sequences to the maximum length of the sequences in the batch, given a dataset of paired sequences. train_dataset (`datasets.Dataset`): The dataset to use for training. eval_dataset (`datasets.Dataset`): The dataset to use for evaluation. processing_class ([`~transformers.PreTrainedTokenizerBase`], [`~transformers.BaseImageProcessor`], [`~transformers.FeatureExtractionMixin`] or [`~transformers.ProcessorMixin`], *optional*, defaults to `None`): Processing class used to process the data. If provided, will be used to automatically process the inputs for the model, and it will be saved along the model to make it easier to rerun an interrupted training or reuse the fine-tuned model. peft_config (`dict`): The peft config to use for training. compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*): The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to metric values. callbacks (`list[transformers.TrainerCallback]`): The callbacks to use for training. optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): The optimizer and scheduler to use for training. preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): The function to use to preprocess the logits before computing the metrics. """ _tag_names = ["trl", "online-dpo"] def __init__( self, model: Union[PreTrainedModel, nn.Module, str], ref_model: Union[PreTrainedModel, nn.Module, None] = None, reward_model: Union[PreTrainedModel, nn.Module, None] = None, judge: Optional[BasePairwiseJudge] = None, args: Optional[OnlineDPOConfig] = None, data_collator: Optional[DataCollator] = None, train_dataset: Optional[Union[Dataset, IterableDataset, "datasets.Dataset"]] = None, eval_dataset: Optional[Union[Dataset, dict[str, Dataset], "datasets.Dataset"]] = None, processing_class: Optional[ Union[PreTrainedTokenizerBase, BaseImageProcessor, FeatureExtractionMixin, ProcessorMixin] ] = None, reward_processing_class: Optional[PreTrainedTokenizerBase] = None, peft_config: Optional[dict] = None, compute_metrics: Optional[Callable[[EvalPrediction], dict]] = None, callbacks: Optional[list[TrainerCallback]] = None, optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None, ) -> None: if ref_model is model: raise ValueError( "`model` and `ref_model` cannot be the same object. If you want `ref_model` to be the " "same as `model`, either omit the `ref_model` argument or pass `None`." ) self.ref_model = ref_model if reward_model is not None and judge is not None: logger.warning( "Both `reward_model` and `judge` are provided. Please choose provide only one of them. " "Ignoring `judge` and using `reward_model`.", ) judge = None elif reward_model is None and judge is None: raise ValueError("Either `reward_model` or `judge` must be provided.") self.reward_model = reward_model self.reward_processing_class = reward_processing_class self.judge = judge if args.missing_eos_penalty is not None and judge is not None: raise ValueError("`missing_eos_penalty` is not supported when `judge` is provided.") if args is None: raise ValueError("`args` must be provided.") # Check that the processing_class is provided if processing_class is None: raise ValueError("`processing_class` must be provided.") model_init_kwargs = args.model_init_kwargs or {} if isinstance(model, str): model_id = model # Handle torch_dtype in model_init_kwargs torch_dtype = model_init_kwargs.get("torch_dtype") if isinstance(torch_dtype, torch.dtype) or torch_dtype == "auto" or torch_dtype is None: pass elif isinstance(torch_dtype, str): torch_dtype = getattr(torch, torch_dtype) model_init_kwargs["torch_dtype"] = torch_dtype else: raise ValueError( "Invalid `torch_dtype` passed to `OnlineDPOConfig`. Expected either 'auto' or a string " f"representing a `torch.dtype` (e.g., 'float32'), but got {torch_dtype}." ) model = AutoModelForCausalLM.from_pretrained(model_id, **model_init_kwargs) else: if args.model_init_kwargs is not None: raise ValueError( "You passed `model_init_kwargs` to the `OnlineDPOConfig`, but your model is already instantiated. " "This argument can only be used when the `model` argument is a string." ) self.is_encoder_decoder = model.config.is_encoder_decoder if peft_config is not None or (is_peft_available() and isinstance(model, PeftModel)): model = prepare_peft_model(model, peft_config, args) # Disable dropout in the model and reference model if args.disable_dropout: disable_dropout_in_model(model) if self.ref_model is not None: disable_dropout_in_model(self.ref_model) # Handle the ref_model # Usually, the user wants the ref model to be the initial version of the model. When using PEFT, it's easy to # get the ref model, as it's just the model with a disabled adapter. When not using PEFT, we need to create # the ref model from the model by copying it and disable the gradients and set it in evaluation mode. if ref_model is None: # No ref model provided, the most common case if peft_config is None: self.ref_model = create_reference_model(model) # copy, disable gradients, set eval mode else: self.ref_model = None # we don't need a ref model here, we can just disable the adapter. else: # rare case, the user provided a ref model self.ref_model = ref_model self.ref_model.eval() # Disable the gradient and set the reward model in eval mode if self.reward_model is not None: self.reward_model.eval() # Define the collator is not provided if data_collator is None: data_collator = DPODataCollatorWithPadding(pad_token_id=processing_class.pad_token_id) self.max_length = args.max_length self.stats = { "objective/kl": [], "objective/entropy": [], "objective/non_score_reward": [], "rewards/chosen": [], "rewards/rejected": [], "rewards/accuracies": [], "rewards/margins": [], "logps/chosen": [], "logps/rejected": [], "val/contain_eos_token": [], "beta": [], } if self.reward_model is not None: self.stats["objective/rlhf_reward"] = [] self.stats["objective/scores_margin"] = [] self.stats["objective/scores"] = [] if args.use_vllm: if not is_vllm_available(): raise ImportError( "vLLM is not available and `use_vllm` is set to True. Please install vLLM with " "`pip install vllm` to use it." ) self.generation_config = SamplingParams( n=2, # 2 generations per prompt max_tokens=args.max_new_tokens, temperature=args.temperature, top_k=50, top_p=1.0, detokenize=False, # to avoid vllm to decode (we don't need it) ) # vLLM dynamically adjusts the size of the key-value cache based on available GPU memory at instantiation. # A larger cache size improves speed, so we would expect gpu_memory_utilization=1. # However, at this stage, the optimizer's weights are not yet loaded onto the GPU; they will be loaded # after the first optimizer step and remain in GPU memory throughout training. So we must reserve enough # space for them. Setting gpu_memory_utilization to 0.55 seems to work well in practice. self.llm = LLM( model=model.name_or_path, gpu_memory_utilization=args.gpu_memory_utilization, dtype=torch.float32, model_impl=args.vllm_model_impl, # When release by vLLM, we would be able to distribute the model on multiple GPUs # See https://github.com/vllm-project/vllm/pull/12071 # tensor_parallel_size=torch.cuda.device_count(), # distributed_executor_backend="external_launcher", ) else: self.generation_config = GenerationConfig( max_new_tokens=args.max_new_tokens, temperature=args.temperature, top_k=50, top_p=1.0, do_sample=True, use_cache=False if args.gradient_checkpointing else True, ) # The trainer estimates the number of FLOPs (floating-point operations) using the number of elements in the # input tensor associated with the key "input_ids". However, in Online DPO, the sampled data does not include # the "input_ids" key. As a result, the trainer issues the warning: "Could not estimate the number of tokens # of the input, floating-point operations will not be computed." To suppress this warning, we set the # "estimate_tokens" key in the model's "warnings_issued" dictionary to True. This acts as a flag to indicate # that the warning has already been issued. model.warnings_issued["estimate_tokens"] = True super().__init__( model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, eval_dataset=eval_dataset, processing_class=processing_class, compute_metrics=compute_metrics, callbacks=callbacks, optimizers=optimizers, preprocess_logits_for_metrics=preprocess_logits_for_metrics, ) # Add tags for models that have been loaded with the correct transformers version if hasattr(self.model, "add_model_tags"): self.model.add_model_tags(self._tag_names) self._beta = args.beta # Placed after the super().__init__ because we need self.is_deepspeed_enabled and self.accelerator if self.is_deepspeed_enabled: if self.reward_model is not None: self.reward_model = prepare_deepspeed( self.reward_model, args.per_device_train_batch_size, args.fp16, args.bf16 ) if self.ref_model is not None: self.ref_model = prepare_deepspeed( self.ref_model, args.per_device_train_batch_size, args.fp16, args.bf16 ) else: if self.ref_model is not None: self.ref_model = self.ref_model.to(self.accelerator.device) if self.reward_model is not None: self.reward_model = self.reward_model.to(self.accelerator.device) @property def beta(self): if isinstance(self._beta, list): epoch = self.state.epoch return self._beta[epoch] if epoch < len(self._beta) else self._beta[-1] else: return self._beta @staticmethod def tokenize_row(feature, is_encoder_decoder: bool, tokenizer: PreTrainedTokenizerBase) -> dict[str, Any]: """Tokenize a single row from a DPO specific dataset.""" if not is_encoder_decoder: batch = tokenizer(feature["prompt"], add_special_tokens=False) # Add BOS token to head of prompt. Avoid adding if it's already there if tokenizer.bos_token_id is not None: prompt_len_input_ids = len(batch["input_ids"]) if prompt_len_input_ids == 0 or tokenizer.bos_token_id != batch["input_ids"][0]: batch["input_ids"] = [tokenizer.bos_token_id] + batch["input_ids"] batch["attention_mask"] = [1] + batch["attention_mask"] else: batch = tokenizer(feature["prompt"], add_special_tokens=True) batch = {f"prompt_{key}": value for key, value in batch.items()} return batch # Same as Trainer.get_train_dataloader but skip the "remove_unused_columns". @wraps(Trainer.get_train_dataloader) def get_train_dataloader(self) -> DataLoader: if self.train_dataset is None: raise ValueError("Trainer: training requires a train_dataset.") train_dataset = self.train_dataset data_collator = self.data_collator dataloader_params = { "batch_size": self._train_batch_size, "collate_fn": data_collator, "num_workers": self.args.dataloader_num_workers, "pin_memory": self.args.dataloader_pin_memory, "persistent_workers": self.args.dataloader_persistent_workers, } if not isinstance(train_dataset, torch.utils.data.IterableDataset): dataloader_params["sampler"] = self._get_train_sampler() dataloader_params["drop_last"] = self.args.dataloader_drop_last dataloader_params["worker_init_fn"] = seed_worker dataloader_params["prefetch_factor"] = self.args.dataloader_prefetch_factor return self.accelerator.prepare(DataLoader(train_dataset, **dataloader_params)) # Same as Trainer.get_eval_dataloader but skip the "remove_unused_columns". @wraps(Trainer.get_eval_dataloader) def get_eval_dataloader(self, eval_dataset: Optional[Union[str, Dataset]] = None) -> DataLoader: if eval_dataset is None and self.eval_dataset is None: raise ValueError("Trainer: evaluation requires an eval_dataset.") # If we have persistent workers, don't do a fork bomb especially as eval datasets # don't change during training dataloader_key = eval_dataset if isinstance(eval_dataset, str) else "eval" if ( hasattr(self, "_eval_dataloaders") and dataloader_key in self._eval_dataloaders and self.args.dataloader_persistent_workers ): return self.accelerator.prepare(self._eval_dataloaders[dataloader_key]) eval_dataset = ( self.eval_dataset[eval_dataset] if isinstance(eval_dataset, str) else eval_dataset if eval_dataset is not None else self.eval_dataset ) data_collator = self.data_collator dataloader_params = { "batch_size": self.args.eval_batch_size, "collate_fn": data_collator, "num_workers": self.args.dataloader_num_workers, "pin_memory": self.args.dataloader_pin_memory, "persistent_workers": self.args.dataloader_persistent_workers, } if not isinstance(eval_dataset, torch.utils.data.IterableDataset): dataloader_params["sampler"] = self._get_eval_sampler(eval_dataset) dataloader_params["drop_last"] = self.args.dataloader_drop_last dataloader_params["prefetch_factor"] = self.args.dataloader_prefetch_factor # accelerator.free_memory() will destroy the references, so # we need to store the non-prepared version eval_dataloader = DataLoader(eval_dataset, **dataloader_params) if self.args.dataloader_persistent_workers: if hasattr(self, "_eval_dataloaders"): self._eval_dataloaders[dataloader_key] = eval_dataloader else: self._eval_dataloaders = {dataloader_key: eval_dataloader} return self.accelerator.prepare(eval_dataloader) def _generate_vllm(self, model, prompts): eos_token_id = self.processing_class.eos_token_id pad_token_id = self.processing_class.pad_token_id # Load the latest weights llm_model = self.llm.llm_engine.model_executor.driver_worker.model_runner.model llm_model.load_weights(model.state_dict().items()) if is_conversational({"prompt": prompts[0]}): outputs = self.llm.chat(prompts, self.generation_config, use_tqdm=False) else: outputs = self.llm.generate(prompts, self.generation_config, use_tqdm=False) completion_ids = [list(output.outputs[i].token_ids) for i in range(2) for output in outputs] prompt_ids = [list(output.prompt_token_ids) for _ in range(2) for output in outputs] # Create mask and pad the prompt and completion max_prompt_length = max(len(ids) for ids in prompt_ids) prompt_mask = [[0] * (max_prompt_length - len(ids)) + [1] * len(ids) for ids in prompt_ids] prompt_ids = [[pad_token_id] * (max_prompt_length - len(ids)) + ids for ids in prompt_ids] max_tokens = self.generation_config.max_tokens completion_mask = [[1] * len(ids) + [0] * (max_tokens - len(ids)) for ids in completion_ids] completion_ids = [ ids + [eos_token_id] if ids[-1] != eos_token_id and len(ids) < max_tokens else ids for ids in completion_ids ] completion_ids = [ids + [pad_token_id] * (max_tokens - len(ids)) for ids in completion_ids] # Convert to tensors prompt_ids = torch.tensor(prompt_ids, device=self.accelerator.device) prompt_mask = torch.tensor(prompt_mask, device=self.accelerator.device) completion_ids = torch.tensor(completion_ids, device=self.accelerator.device) completion_mask = torch.tensor(completion_mask, device=self.accelerator.device) return prompt_ids, prompt_mask, completion_ids, completion_mask def _generate(self, model, prompts): eos_token_id = self.processing_class.eos_token_id pad_token_id = self.processing_class.pad_token_id # Apply chat template and tokenize the input. We do this on-the-fly to enable the use of reward models and # policies with different tokenizers / chat templates. inputs = [{"prompt": prompt} for prompt in prompts] inputs = [maybe_apply_chat_template(x, self.processing_class) for x in inputs] inputs = [self.tokenize_row(x, self.is_encoder_decoder, self.processing_class) for x in inputs] inputs = self.data_collator(inputs) # Sample 2 completions per prompt of size `max_new_tokens` from the model inputs = self._prepare_inputs(inputs) prompt_ids = inputs["prompt_input_ids"].repeat(2, 1) prompt_mask = inputs["prompt_attention_mask"].repeat(2, 1) with unwrap_model_for_generation( model, self.accelerator, gather_deepspeed3_params=self.args.ds3_gather_for_generation ) as unwrapped_model: output = unwrapped_model.generate( input_ids=prompt_ids, attention_mask=prompt_mask, generation_config=self.generation_config, ) completion_ids = output[:, prompt_ids.size(1) :] completion_ids, completion_mask = truncate_right(completion_ids, eos_token_id, pad_token_id) return prompt_ids, prompt_mask, completion_ids, completion_mask def _forward(self, model, prompt_ids, prompt_mask, completion_ids, completion_mask): # Get the number of tokens to truncate from prompt num_tokens_to_truncate = max(prompt_ids.size(1) + completion_ids.size(1) - self.max_length, 0) # Truncate left to avoid oom prompt_ids = prompt_ids[:, num_tokens_to_truncate:] prompt_mask = prompt_mask[:, num_tokens_to_truncate:] # Concat the prompt and completion prompt_completion_ids = torch.cat((prompt_ids, completion_ids), dim=1) prompt_completion_mask = torch.cat((prompt_mask, completion_mask), dim=1) # Get the logprobs of the completions from the model output = model(prompt_completion_ids, attention_mask=prompt_completion_mask) # There is 1 offset, because the model predict the next token prompt_len = prompt_ids.size(1) start_idx = prompt_len - 1 if prompt_len > 0 else 0 logits = output.logits[:, start_idx:-1] # Take the completion tokens logprob logprobs = torch.take_along_dim(logits.log_softmax(dim=-1), completion_ids.unsqueeze(-1), dim=2).squeeze(-1) return logprobs def training_step( self, model: nn.Module, inputs: dict[str, Union[torch.Tensor, Any]], num_items_in_batch: Optional[int] = None ) -> torch.Tensor: model.train() prompts = inputs["prompt"] batch_size = len(prompts) if self.args.use_vllm: prompt_ids, prompt_mask, completion_ids, completion_mask = self._generate_vllm(model, prompts) else: prompt_ids, prompt_mask, completion_ids, completion_mask = self._generate(model, prompts) contain_eos_token = torch.any(completion_ids == self.processing_class.eos_token_id, dim=-1) logprobs = self._forward(model, prompt_ids, prompt_mask, completion_ids, completion_mask) with torch.no_grad(): if self.ref_model is not None: ref_logprobs = self._forward(self.ref_model, prompt_ids, prompt_mask, completion_ids, completion_mask) else: # peft case: we just need to disable the adapter with self.model.disable_adapter(): ref_logprobs = self._forward(self.model, prompt_ids, prompt_mask, completion_ids, completion_mask) # Decode the completions, and format them if the input is conversational device = logprobs.device completions = self.processing_class.batch_decode(completion_ids, skip_special_tokens=True) if is_conversational({"prompt": prompts[0]}): completions = [[{"role": "assistant", "content": completion}] for completion in completions] # Get the reward from the reward model or judge if self.judge is not None: # Once formatted, conversational data may contain special tokens (such as <|im_start|>) that are not # directly understandable by the judge and could alter its judgment. To avoid this and make the judge # independent of the model's chat template, we use the raw conversation data, and apply our own chat # template to it. if is_conversational({"prompt": prompts[0]}): environment = jinja2.Environment() template = environment.from_string(SIMPLE_CHAT_TEMPLATE) prompts = [template.render(messages=prompt) for prompt in prompts] completions = [template.render(messages=completion) for completion in completions] ranks_of_first_completion = self.judge.judge( prompts, list(zip(completions[:batch_size], completions[batch_size:])) ) # convert ranks to a True/False mask: # when rank == 0, it means the first completion is the best # when rank == 1, it means the second completion is the best mask = torch.tensor([rank == 0 for rank in ranks_of_first_completion], device=device) else: # The reward model may not have the same chat template or tokenizer as the model, so we need to use the # raw data (string), apply the chat template (if needed), and tokenize it with the reward processing class. prompts = 2 * prompts # repeat the prompt: [prompt0, prompt1] -> [prompt0, prompt1, prompt0, prompt1] if is_conversational({"prompt": prompts[0]}): examples = [{"prompt": p, "completion": c} for p, c in zip(prompts, completions)] examples = [apply_chat_template(example, self.reward_processing_class) for example in examples] prompts = [example["prompt"] for example in examples] completions = [example["completion"] for example in examples] # Tokenize the prompts prompts_ids = self.reward_processing_class( prompts, padding=True, return_tensors="pt", padding_side="left" )["input_ids"].to(device) context_length = prompts_ids.shape[1] # Tokenize the completions completions_ids = self.reward_processing_class( completions, padding=True, return_tensors="pt", padding_side="right" )["input_ids"].to(device) # Concatenate the prompts and completions and get the reward prompt_completion_ids = torch.cat((prompts_ids, completions_ids), dim=1) with torch.inference_mode(): _, scores, _ = get_reward( self.reward_model, prompt_completion_ids, self.reward_processing_class.pad_token_id, context_length ) # Filter completion. Ensure that the sample contains stop_token_id # Completions not passing that filter will receive a lower score. if self.args.missing_eos_penalty is not None: scores[~contain_eos_token] -= self.args.missing_eos_penalty # Split the scores in 2 (the prompts of the first half are the same as the second half) first_half, second_half = scores.split(batch_size) # Get the indices of the chosen and rejected examples mask = first_half >= second_half batch_range = torch.arange(batch_size, device=device) chosen_indices = batch_range + (~mask * batch_size) rejected_indices = batch_range + (mask * batch_size) # Build tensor so that the first half is the chosen examples and the second half the rejected examples cr_indices = torch.cat((chosen_indices, rejected_indices), dim=0) # cr = chosen and rejected cr_logprobs = logprobs[cr_indices] cr_ref_logprobs = ref_logprobs[cr_indices] # mask out the padding tokens padding_mask = ~completion_mask.bool() cr_padding_mask = padding_mask[cr_indices] cr_logprobs_sum = (cr_logprobs * ~cr_padding_mask).sum(1) cr_ref_logprobs_sum = (cr_ref_logprobs * ~cr_padding_mask).sum(1) # Split the chosen and rejected examples chosen_logprobs_sum, rejected_logprobs_sum = torch.split(cr_logprobs_sum, batch_size) chosen_ref_logprobs_sum, rejected_ref_logprobs_sum = torch.split(cr_ref_logprobs_sum, batch_size) pi_logratios = chosen_logprobs_sum - rejected_logprobs_sum ref_logratios = chosen_ref_logprobs_sum - rejected_ref_logprobs_sum logits = pi_logratios - ref_logratios if self.args.loss_type == "sigmoid": losses = -F.logsigmoid(self.beta * logits) elif self.args.loss_type == "ipo": losses = (logits - 1 / (2 * self.beta)) ** 2 else: raise NotImplementedError(f"invalid loss type {self.loss_type}") loss = losses.mean() # Log everything if self.reward_model is not None: scores_margin = scores[chosen_indices] - scores[rejected_indices] self.stats["objective/scores_margin"].append( self.accelerator.gather_for_metrics(scores_margin.mean()).mean().item() ) self.stats["objective/scores"].append(self.accelerator.gather_for_metrics(scores.mean()).mean().item()) self.stats["val/contain_eos_token"].append(contain_eos_token.float().mean().item()) self.stats["logps/chosen"].append(self.accelerator.gather_for_metrics(chosen_logprobs_sum).mean().item()) self.stats["logps/rejected"].append(self.accelerator.gather_for_metrics(rejected_logprobs_sum).mean().item()) kl = logprobs - ref_logprobs mean_kl = kl.sum(1).mean() self.stats["objective/kl"].append(self.accelerator.gather_for_metrics(mean_kl).mean().item()) non_score_reward = (-self.beta * kl).sum(1) mean_non_score_reward = non_score_reward.mean() self.stats["objective/non_score_reward"].append( self.accelerator.gather_for_metrics(mean_non_score_reward).mean().item() ) if self.reward_model is not None: rlhf_reward = scores + non_score_reward self.stats["objective/rlhf_reward"].append(self.accelerator.gather_for_metrics(rlhf_reward).mean().item()) mean_entropy = -logprobs.sum(1).mean() self.stats["objective/entropy"].append(self.accelerator.gather_for_metrics(mean_entropy).mean().item()) chosen_rewards = self.beta * (chosen_logprobs_sum - chosen_ref_logprobs_sum) gathered_chosen_rewards = self.accelerator.gather_for_metrics(chosen_rewards) self.stats["rewards/chosen"].append(gathered_chosen_rewards.mean().item()) rejected_rewards = self.beta * (rejected_logprobs_sum - rejected_ref_logprobs_sum) gathered_rejected_rewards = self.accelerator.gather_for_metrics(rejected_rewards) self.stats["rewards/rejected"].append(gathered_rejected_rewards.mean().item()) margin = gathered_chosen_rewards - gathered_rejected_rewards self.stats["rewards/margins"].append(margin.mean().item()) accuracy = margin > 0 self.stats["rewards/accuracies"].append(accuracy.float().mean().item()) self.stats["beta"].append(self.beta) if ( self.args.torch_empty_cache_steps is not None and self.state.global_step % self.args.torch_empty_cache_steps == 0 ): empty_cache() kwargs = {} # For LOMO optimizers you need to explicitly use the learning rate if self.args.optim in [OptimizerNames.LOMO, OptimizerNames.ADALOMO]: kwargs["learning_rate"] = self._get_learning_rate() if self.args.n_gpu > 1: loss = loss.mean() # mean() to average on multi-gpu parallel training if self.use_apex: with amp.scale_loss(loss, self.optimizer) as scaled_loss: scaled_loss.backward() else: self.accelerator.backward(loss, **kwargs) return loss.detach() / self.args.gradient_accumulation_steps # Same as Trainer._maybe_log_save_evaluate but log our metrics def _maybe_log_save_evaluate( self, tr_loss, grad_norm, model, trial, epoch, ignore_keys_for_eval, start_time, learning_rate=None ): if self.control.should_log and self.state.global_step > self._globalstep_last_logged: logs: dict[str, float] = {} # all_gather + mean() to get average loss over all processes tr_loss_scalar = self._nested_gather(tr_loss).mean().item() # reset tr_loss to zero tr_loss -= tr_loss logs["loss"] = round(tr_loss_scalar / (self.state.global_step - self._globalstep_last_logged), 4) if grad_norm is not None: logs["grad_norm"] = grad_norm.detach().item() if isinstance(grad_norm, torch.Tensor) else grad_norm if learning_rate is not None: logs["learning_rate"] = learning_rate else: logs["learning_rate"] = self._get_learning_rate() # Add our metrics for key, val in self.stats.items(): logs[key] = sum(val) / len(val) self.stats = {key: [] for key in self.stats} # reset stats self._total_loss_scalar += tr_loss_scalar self._globalstep_last_logged = self.state.global_step self.store_flos() self.log(logs, start_time) metrics = None if self.control.should_evaluate: metrics = self._evaluate(trial, ignore_keys_for_eval) is_new_best_metric = self._determine_best_metric(metrics=metrics, trial=trial) if self.args.save_strategy == "best": self.control.should_save = is_new_best_metric if self.control.should_save: self._save_checkpoint(model, trial) self.control = self.callback_handler.on_save(self.args, self.state, self.control) # Ensure the model card is saved along with the checkpoint def _save_checkpoint(self, model, trial): if self.args.hub_model_id is None: model_name = Path(self.args.output_dir).name else: model_name = self.args.hub_model_id.split("/")[-1] self.create_model_card(model_name=model_name) super()._save_checkpoint(model, trial) def create_model_card( self, model_name: Optional[str] = None, dataset_name: Optional[str] = None, tags: Union[str, list[str], None] = None, ): """ Creates a draft of a model card using the information available to the `Trainer`. Args: model_name (`str` or `None`, *optional*, defaults to `None`): Name of the model. dataset_name (`str` or `None`, *optional*, defaults to `None`): Name of the dataset used for training. tags (`str`, `list[str]` or `None`, *optional*, defaults to `None`): Tags to be associated with the model card. """ if not self.is_world_process_zero(): return if hasattr(self.model.config, "_name_or_path") and not os.path.isdir(self.model.config._name_or_path): base_model = self.model.config._name_or_path else: base_model = None # normalize `tags` to a mutable set if tags is None: tags = set() elif isinstance(tags, str): tags = {tags} else: tags = set(tags) if hasattr(self.model.config, "unsloth_version"): tags.add("unsloth") tags.update(self._tag_names) # docstyle-ignore citation = textwrap.dedent("""\ @article{guo2024direct, title = {{Direct Language Model Alignment from Online AI Feedback}}, author = {Shangmin Guo and Biao Zhang and Tianlin Liu and Tianqi Liu and Misha Khalman and Felipe Llinares and Alexandre Ram{\'{e}} and Thomas Mesnard and Yao Zhao and Bilal Piot and Johan Ferret and Mathieu Blondel}, year = 2024, eprint = {arXiv:2402.04792} }""") model_card = generate_model_card( base_model=base_model, model_name=model_name, hub_model_id=self.hub_model_id, dataset_name=dataset_name, tags=tags, wandb_url=wandb.run.url if is_wandb_available() and wandb.run is not None else None, comet_url=get_comet_experiment_url(), trainer_name="Online DPO", trainer_citation=citation, paper_title="Direct Language Model Alignment from Online AI Feedback", paper_id="2402.04792", ) model_card.save(os.path.join(self.args.output_dir, "README.md"))
trl/trl/trainer/online_dpo_trainer.py/0
{ "file_path": "trl/trl/trainer/online_dpo_trainer.py", "repo_id": "trl", "token_count": 17099 }
573
# <a href="https://hf.co/learn/agents-course" target="_blank">The Hugging Face Agents Course</a> If you like the course, **don't hesitate to ⭐ star this repository**. This helps us to **make the course more visible 🤗**. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/communication/please_star.gif" alt="Star the repo" /> ## Content The course is divided into 4 units. These will take you from **the basics of agents to a final assignment with a benchmark**. Sign up here (it's free) 👉 <a href="https://bit.ly/hf-learn-agents" target="_blank">https://bit.ly/hf-learn-agents</a> You can access the course here 👉 <a href="https://hf.co/learn/agents-course" target="_blank">https://hf.co/learn/agents-course</a> | Unit | Topic | Description | |---------|----------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------| | 0 | [Welcome to the Course](https://huggingface.co/learn/agents-course/en/unit0/introduction) | Welcome, guidelines, necessary tools, and course overview. | | 1 | [Introduction to Agents](https://huggingface.co/learn/agents-course/en/unit1/introduction) | Definition of agents, LLMs, model family tree, and special tokens. | | 1 Bonus | [Fine-tuning an LLM for Function-calling](https://huggingface.co/learn/agents-course/bonus-unit1/introduction) | Learn how to fine-tune an LLM for Function-Calling | | 2 | [Frameworks for AI Agents](https://huggingface.co/learn/agents-course/unit2/introduction) | Overview of `smolagents`, `LangGraph` and `LlamaIndex`. | | 2.1 | [The Smolagents Framework](https://huggingface.co/learn/agents-course/unit2/smolagents/introduction) | Learn how to build effective agents using the `smolagents` library, a lightweight framework for creating capable AI agents. | | 2.2 | [The LlamaIndex Framework](https://huggingface.co/learn/agents-course/unit2/llama-index/introduction) | Learn how to build LLM-powered agents over your data using indexes and workflows using the `LlamaIndex` toolkit. | | 2.3 | [The LangGraph Framework](https://huggingface.co/learn/agents-course/unit2/langgraph/introduction) | Learn how to build production-ready applications using the `LangGraph` framework giving you control tools over the flow of your agent. | | 2 Bonus | [Observability and Evaluation](https://huggingface.co/learn/agents-course/bonus-unit2/introduction) | Learn how to trace and evaluate your agents. | | 3 | [Use Case for Agentic RAG](https://huggingface.co/learn/agents-course/unit3/agentic-rag/introduction) | Learn how to use Agentic RAG to help agents respond to different use cases using various frameworks. | | 4 | [Final Project - Create, Test and Certify Your Agent](https://huggingface.co/learn/agents-course/unit4/introduction) | Automated evaluation of agents and leaderboard with student results. | | 3 Bonus | [Agents in Games with Pokemon](https://huggingface.co/learn/agents-course/bonus-unit3/introduction) | Explore the exciting intersection of AI Agents and games. | ## Prerequisites - Basic knowledge of Python - Basic knowledge of LLMs ## Contribution Guidelines If you want to contribute to this course, you're welcome to do so. Feel free to open an issue or join the discussion in the [Discord](https://discord.gg/UrrTSsSyjb). For specific contributions, here are some guidelines: ### Small typo and grammar fixes If you find a small typo or grammar mistake, please fix it yourself and submit a pull request. This is very helpful for students. ### New unit If you want to add a new unit, **please create an issue in the repository, describe the unit, and why it should be added**. We will discuss it and if it's a good addition, we can collaborate on it. ## Citing the project To cite this repository in publications: ```bibtex @misc{agents-course, author = {Burtenshaw, Ben and Thomas, Joffrey and Simonini, Thomas and Paniego, Sergio}, title = {The Hugging Face Agents Course}, year = {2025}, howpublished = {\url{https://github.com/huggingface/agents-course}}, note = {GitHub repository}, } ```
agents-course/README.md/0
{ "file_path": "agents-course/README.md", "repo_id": "agents-course", "token_count": 2231 }
0
<CourseFloatingBanner chapter={2} classNames="absolute z-10 right-0 top-0" notebooks={[ {label: "Google Colab", value: "https://colab.research.google.com/#fileId=https%3A//huggingface.co/agents-course/notebooks/blob/main/bonus-unit2/monitoring-and-evaluating-agents.ipynb"}, ]} /> # Bonus Unit 2: Observability and Evaluation of Agents <Tip> You can follow the code in <a href="https://colab.research.google.com/#fileId=https%3A//huggingface.co/agents-course/notebooks/blob/main/bonus-unit2/monitoring-and-evaluating-agents.ipynb" target="_blank">this notebook</a> that you can run using Google Colab. </Tip> In this notebook, we will learn how to **monitor the internal steps (traces) of our AI agent** and **evaluate its performance** using open-source observability tools. The ability to observe and evaluate an agent’s behavior is essential for: - Debugging issues when tasks fail or produce suboptimal results - Monitoring costs and performance in real-time - Improving reliability and safety through continuous feedback ## Exercise Prerequisites 🏗️ Before running this notebook, please be sure you have: 🔲 📚 **Studied** [Introduction to Agents](https://huggingface.co/learn/agents-course/unit1/introduction) 🔲 📚 **Studied** [The smolagents framework](https://huggingface.co/learn/agents-course/unit2/smolagents/introduction) ## Step 0: Install the Required Libraries We will need a few libraries that allow us to run, monitor, and evaluate our agents: ```python %pip install langfuse 'smolagents[telemetry]' openinference-instrumentation-smolagents datasets 'smolagents[gradio]' gradio --upgrade ``` ## Step 1: Instrument Your Agent In this notebook, we will use [Langfuse](https://langfuse.com/) as our observability tool, but you can use **any other OpenTelemetry-compatible service**. The code below shows how to set environment variables for Langfuse (or any OTel endpoint) and how to instrument your smolagent. **Note:** If you are using LlamaIndex or LangGraph, you can find documentation on instrumenting them [here](https://langfuse.com/docs/integrations/llama-index/workflows) and [here](https://langfuse.com/docs/integrations/langchain/example-python-langgraph). First, let's set up the Langfuse credentials as environment variables. Get your Langfuse API keys by signing up for [Langfuse Cloud](https://cloud.langfuse.com) or [self-hosting Langfuse](https://langfuse.com/self-hosting). ```python import os # Get keys for your project from the project settings page: https://cloud.langfuse.com os.environ["LANGFUSE_PUBLIC_KEY"] = "pk-lf-..." os.environ["LANGFUSE_SECRET_KEY"] = "sk-lf-..." os.environ["LANGFUSE_HOST"] = "https://cloud.langfuse.com" # 🇪🇺 EU region # os.environ["LANGFUSE_HOST"] = "https://us.cloud.langfuse.com" # 🇺🇸 US region ``` We also need to configure our Hugging Face token for inference calls. ```python # Set your Hugging Face and other tokens/secrets as environment variable os.environ["HF_TOKEN"] = "hf_..." ``` With the environment variables set, we can now initialize the Langfuse client. `get_client()` initializes the Langfuse client using the credentials provided in the environment variables. ```python from langfuse import get_client langfuse = get_client() # Verify connection if langfuse.auth_check(): print("Langfuse client is authenticated and ready!") else: print("Authentication failed. Please check your credentials and host.") ``` Next, we can set up the `SmolagentsInstrumentor()` to instrument our smolagent and send traces to Langfuse. ```python from openinference.instrumentation.smolagents import SmolagentsInstrumentor SmolagentsInstrumentor().instrument() ``` ## Step 2: Test Your Instrumentation Here is a simple CodeAgent from smolagents that calculates `1+1`. We run it to confirm that the instrumentation is working correctly. If everything is set up correctly, you will see logs/spans in your observability dashboard. ```python from smolagents import InferenceClientModel, CodeAgent # Create a simple agent to test instrumentation agent = CodeAgent( tools=[], model=InferenceClientModel() ) agent.run("1+1=") ``` Check your [Langfuse Traces Dashboard](https://cloud.langfuse.com) (or your chosen observability tool) to confirm that the spans and logs have been recorded. Example screenshot from Langfuse: ![Example trace in Langfuse](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/first-example-trace.png) _[Link to the trace](https://cloud.langfuse.com/project/cloramnkj0002jz088vzn1ja4/traces/1b94d6888258e0998329cdb72a371155?timestamp=2025-03-10T11%3A59%3A41.743Z)_ ## Step 3: Observe and Evaluate a More Complex Agent Now that you have confirmed your instrumentation works, let's try a more complex query so we can see how advanced metrics (token usage, latency, costs, etc.) are tracked. ```python from smolagents import (CodeAgent, DuckDuckGoSearchTool, InferenceClientModel) search_tool = DuckDuckGoSearchTool() agent = CodeAgent(tools=[search_tool], model=InferenceClientModel()) agent.run("How many Rubik's Cubes could you fit inside the Notre Dame Cathedral?") ``` ### Trace Structure Most observability tools record a **trace** that contains **spans**, which represent each step of your agent’s logic. Here, the trace contains the overall agent run and sub-spans for: - The tool calls (DuckDuckGoSearchTool) - The LLM calls (InferenceClientModel) You can inspect these to see precisely where time is spent, how many tokens are used, and so on: ![Trace tree in Langfuse](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/trace-tree.png) _[Link to the trace](https://cloud.langfuse.com/project/cloramnkj0002jz088vzn1ja4/traces/1ac33b89ffd5e75d4265b62900c348ed?timestamp=2025-03-07T13%3A45%3A09.149Z&display=preview)_ ## Online Evaluation In the previous section, we learned about the difference between online and offline evaluation. Now, we will see how to monitor your agent in production and evaluate it live. ### Common Metrics to Track in Production 1. **Costs** — The smolagents instrumentation captures token usage, which you can transform into approximate costs by assigning a price per token. 2. **Latency** — Observe the time it takes to complete each step, or the entire run. 3. **User Feedback** — Users can provide direct feedback (thumbs up/down) to help refine or correct the agent. 4. **LLM-as-a-Judge** — Use a separate LLM to evaluate your agent’s output in near real-time (e.g., checking for toxicity or correctness). Below, we show examples of these metrics. #### 1. Costs Below is a screenshot showing usage for `Qwen2.5-Coder-32B-Instruct` calls. This is useful to see costly steps and optimize your agent. ![Costs](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/smolagents-costs.png) _[Link to the trace](https://cloud.langfuse.com/project/cloramnkj0002jz088vzn1ja4/traces/1ac33b89ffd5e75d4265b62900c348ed?timestamp=2025-03-07T13%3A45%3A09.149Z&display=preview)_ #### 2. Latency We can also see how long it took to complete each step. In the example below, the entire conversation took 32 seconds, which you can break down by step. This helps you identify bottlenecks and optimize your agent. ![Latency](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/smolagents-latency.png) _[Link to the trace](https://cloud.langfuse.com/project/cloramnkj0002jz088vzn1ja4/traces/1ac33b89ffd5e75d4265b62900c348ed?timestamp=2025-03-07T13%3A45%3A09.149Z&display=preview)_ #### 3. Additional Attributes You may also pass additional attributes to your spans. These can include `user_id`, `tags`, `session_id`, and custom metadata. Enriching traces with these details is important for analysis, debugging, and monitoring of your application’s behavior across different users or sessions. ```python from smolagents import (CodeAgent, DuckDuckGoSearchTool, InferenceClientModel) search_tool = DuckDuckGoSearchTool() agent = CodeAgent( tools=[search_tool], model=InferenceClientModel() ) with langfuse.start_as_current_span( name="Smolagent-Trace", ) as span: # Run your application here response = agent.run("What is the capital of Germany?") # Pass additional attributes to the span span.update_trace( input="What is the capital of Germany?", output=response, user_id="smolagent-user-123", session_id="smolagent-session-123456789", tags=["city-question", "testing-agents"], metadata={"email": "user@langfuse.com"}, ) # Flush events in short-lived applications langfuse.flush() ``` ![Enhancing agent runs with additional metrics](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/smolagents-attributes.png) #### 4. User Feedback If your agent is embedded into a user interface, you can record direct user feedback (like a thumbs-up/down in a chat UI). Below is an example using [Gradio](https://gradio.app/) to embed a chat with a simple feedback mechanism. In the code snippet below, when a user sends a chat message, we capture the trace in Langfuse. If the user likes/dislikes the last answer, we attach a score to the trace. ```python import gradio as gr from smolagents import (CodeAgent, InferenceClientModel) from langfuse import get_client langfuse = get_client() model = InferenceClientModel() agent = CodeAgent(tools=[], model=model, add_base_tools=True) trace_id = None def respond(prompt, history): with langfuse.start_as_current_span( name="Smolagent-Trace"): # Run your application here output = agent.run(prompt) global trace_id trace_id = langfuse.get_current_trace_id() history.append({"role": "assistant", "content": str(output)}) return history def handle_like(data: gr.LikeData): # For demonstration, we map user feedback to a 1 (like) or 0 (dislike) if data.liked: langfuse.create_score( value=1, name="user-feedback", trace_id=trace_id ) else: langfuse.create_score( value=0, name="user-feedback", trace_id=trace_id ) with gr.Blocks() as demo: chatbot = gr.Chatbot(label="Chat", type="messages") prompt_box = gr.Textbox(placeholder="Type your message...", label="Your message") # When the user presses 'Enter' on the prompt, we run 'respond' prompt_box.submit( fn=respond, inputs=[prompt_box, chatbot], outputs=chatbot ) # When the user clicks a 'like' button on a message, we run 'handle_like' chatbot.like(handle_like, None, None) demo.launch() ``` User feedback is then captured in your observability tool: ![User feedback is being captured in Langfuse](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/user-feedback-gradio.png) #### 5. LLM-as-a-Judge LLM-as-a-Judge is another way to automatically evaluate your agent's output. You can set up a separate LLM call to gauge the output’s correctness, toxicity, style, or any other criteria you care about. **Workflow**: 1. You define an **Evaluation Template**, e.g., "Check if the text is toxic." 2. Each time your agent generates output, you pass that output to your "judge" LLM with the template. 3. The judge LLM responds with a rating or label that you log to your observability tool. Example from Langfuse: ![LLM-as-a-Judge Evaluation Template](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/evaluator-template.png) ![LLM-as-a-Judge Evaluator](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/evaluator.png) ```python # Example: Checking if the agent’s output is toxic or not. from smolagents import (CodeAgent, DuckDuckGoSearchTool, InferenceClientModel) search_tool = DuckDuckGoSearchTool() agent = CodeAgent(tools=[search_tool], model=InferenceClientModel()) agent.run("Can eating carrots improve your vision?") ``` You can see that the answer of this example is judged as "not toxic". ![LLM-as-a-Judge Evaluation Score](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/llm-as-a-judge-score.png) #### 6. Observability Metrics Overview All of these metrics can be visualized together in dashboards. This enables you to quickly see how your agent performs across many sessions and helps you to track quality metrics over time. ![Observability metrics overview](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/langfuse-dashboard.png) ## Offline Evaluation Online evaluation is essential for live feedback, but you also need **offline evaluation**—systematic checks before or during development. This helps maintain quality and reliability before rolling changes into production. ### Dataset Evaluation In offline evaluation, you typically: 1. Have a benchmark dataset (with prompt and expected output pairs) 2. Run your agent on that dataset 3. Compare outputs to the expected results or use an additional scoring mechanism Below, we demonstrate this approach with the [GSM8K dataset](https://huggingface.co/datasets/openai/gsm8k), which contains math questions and solutions. ```python import pandas as pd from datasets import load_dataset # Fetch GSM8K from Hugging Face dataset = load_dataset("openai/gsm8k", 'main', split='train') df = pd.DataFrame(dataset) print("First few rows of GSM8K dataset:") print(df.head()) ``` Next, we create a dataset entity in Langfuse to track the runs. Then, we add each item from the dataset to the system. (If you’re not using Langfuse, you might simply store these in your own database or local file for analysis.) ```python from langfuse import get_client langfuse = get_client() langfuse_dataset_name = "gsm8k_dataset_huggingface" # Create a dataset in Langfuse langfuse.create_dataset( name=langfuse_dataset_name, description="GSM8K benchmark dataset uploaded from 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: # Upload only the first 10 items for demonstration break ``` ![Dataset items in Langfuse](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/example-dataset.png) #### Running the Agent on the Dataset We define a helper function `run_smolagent()` that: 1. Starts a Langfuse span 2. Runs our agent on the prompt 3. Records the trace ID in Langfuse Then, we loop over each dataset item, run the agent, and link the trace to the dataset item. We can also attach a quick evaluation score if desired. ```python from opentelemetry.trace import format_trace_id from smolagents import (CodeAgent, InferenceClientModel, LiteLLMModel) from langfuse import get_client langfuse = get_client() # Example: using InferenceClientModel or LiteLLMModel to access openai, anthropic, gemini, etc. models: model = InferenceClientModel() agent = CodeAgent( tools=[], model=model, add_base_tools=True ) dataset_name = "gsm8k_dataset_huggingface" current_run_name = "smolagent-notebook-run-01" # Identifies this specific evaluation run # Assume 'run_smolagent' is your instrumented application function def run_smolagent(question): with langfuse.start_as_current_generation(name="qna-llm-call") as generation: # Simulate LLM call result = agent.run(question) # Update the trace with the input and output generation.update_trace( input= question, output=result, ) return result dataset = langfuse.get_dataset(name=dataset_name) # Fetch your pre-populated dataset for item in dataset.items: # Use the item.run() context manager with item.run( run_name=current_run_name, run_metadata={"model_provider": "Hugging Face", "temperature_setting": 0.7}, run_description="Evaluation run for GSM8K dataset" ) as root_span: # root_span is the root span of the new trace for this item and run. # All subsequent langfuse operations within this block are part of this trace. # Call your application logic generated_answer = run_smolagent(question=item.input["text"]) print(item.input) ``` You can repeat this process with different: - Models (OpenAI GPT, local LLM, etc.) - Tools (search vs. no search) - Prompts (different system messages) Then compare them side-by-side in your observability tool: ![Dataset run overview](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/dataset_runs.png) ![Dataset run comparison](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit2/dataset-run-comparison.png) ## Final Thoughts In this notebook, we covered how to: 1. **Set up Observability** using smolagents + OpenTelemetry exporters 2. **Check Instrumentation** by running a simple agent 3. **Capture Detailed Metrics** (cost, latency, etc.) through an observability tools 4. **Collect User Feedback** via a Gradio interface 5. **Use LLM-as-a-Judge** to automatically evaluate outputs 6. **Perform Offline Evaluation** with a benchmark dataset 🤗 Happy coding!
agents-course/units/en/bonus-unit2/monitoring-and-evaluating-agents-notebook.mdx/0
{ "file_path": "agents-course/units/en/bonus-unit2/monitoring-and-evaluating-agents-notebook.mdx", "repo_id": "agents-course", "token_count": 5817 }
1
# Conclusion [[conclusion]] Congratulations on finishing this first Unit 🥳 You've just **mastered the fundamentals of Agents** and you've created your first AI Agent! It's **normal if you still feel confused by some of these elements**. Agents are a complex topic and it's common to take a while to grasp everything. **Take time to really grasp the material** before continuing. It’s important to master these elements and have a solid foundation before entering the fun part. And if you pass the Quiz test, don't forget to get your certificate 🎓 👉 [here](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="Certificate Example"/> In the next (bonus) unit, you're going to learn **to fine-tune a Agent to do function calling (aka to be able to call tools based on user prompt)**. Finally, we would love **to hear what you think of the course and how we can improve it**. If you have some feedback then, please 👉 [fill this form](https://docs.google.com/forms/d/e/1FAIpQLSe9VaONn0eglax0uTwi29rIn4tM7H2sYmmybmG5jJNlE5v0xA/viewform?usp=dialog) ### Keep Learning, stay awesome 🤗
agents-course/units/en/unit1/conclusion.mdx/0
{ "file_path": "agents-course/units/en/unit1/conclusion.mdx", "repo_id": "agents-course", "token_count": 368 }
2
# Document Analysis Graph Alfred at your service. As Mr. Wayne's trusted butler, I've taken the liberty of documenting how I assist Mr Wayne with his various documentary needs. While he's out attending to his... nighttime activities, I ensure all his paperwork, training schedules, and nutritional plans are properly analyzed and organized. Before leaving, he left a note with his week's training program. I then took the responsibility to come up with a **menu** for tomorrow's meals. For future such events, let's create a document analysis system using LangGraph to serve Mr. Wayne's needs. This system can: 1. Process images document 2. Extract text using vision models (Vision Language Model) 3. Perform calculations when needed (to demonstrate normal tools) 4. Analyze content and provide concise summaries 5. Execute specific instructions related to documents ## The Butler's Workflow The workflow we’ll build follows this structured schema: ![Butler's Document Analysis Workflow](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/LangGraph/alfred_flow.png) <Tip> You can follow the code in <a href="https://huggingface.co/agents-course/notebooks/blob/main/unit2/langgraph/agent.ipynb" target="_blank">this notebook</a> that you can run using Google Colab. </Tip> ## Setting Up the environment ```python %pip install langgraph langchain_openai langchain_core ``` and imports : ```python import base64 from typing import List, TypedDict, Annotated, Optional from langchain_openai import ChatOpenAI from langchain_core.messages import AnyMessage, SystemMessage, HumanMessage from langgraph.graph.message import add_messages from langgraph.graph import START, StateGraph from langgraph.prebuilt import ToolNode, tools_condition from IPython.display import Image, display ``` ## Defining Agent's State This state is a little more complex than the previous ones we have seen. `AnyMessage` is a class from Langchain that defines messages, and `add_messages` is an operator that adds the latest message rather than overwriting it with the latest state. This is a new concept in LangGraph, where you can add operators in your state to define the way they should interact together. ```python class AgentState(TypedDict): # The document provided input_file: Optional[str] # Contains file path (PDF/PNG) messages: Annotated[list[AnyMessage], add_messages] ``` ## Preparing Tools ```python vision_llm = ChatOpenAI(model="gpt-4o") def extract_text(img_path: str) -> str: """ Extract text from an image file using a multimodal model. Master Wayne often leaves notes with his training regimen or meal plans. This allows me to properly analyze the contents. """ all_text = "" try: # Read image and encode as base64 with open(img_path, "rb") as image_file: image_bytes = image_file.read() image_base64 = base64.b64encode(image_bytes).decode("utf-8") # Prepare the prompt including the base64 image data message = [ HumanMessage( content=[ { "type": "text", "text": ( "Extract all the text from this image. " "Return only the extracted text, no explanations." ), }, { "type": "image_url", "image_url": { "url": f"data:image/png;base64,{image_base64}" }, }, ] ) ] # Call the vision-capable model response = vision_llm.invoke(message) # Append extracted text all_text += response.content + "\n\n" return all_text.strip() except Exception as e: # A butler should handle errors gracefully error_msg = f"Error extracting text: {str(e)}" print(error_msg) return "" def divide(a: int, b: int) -> float: """Divide a and b - for Master Wayne's occasional calculations.""" return a / b # Equip the butler with tools tools = [ divide, extract_text ] llm = ChatOpenAI(model="gpt-4o") llm_with_tools = llm.bind_tools(tools, parallel_tool_calls=False) ``` ## The nodes ```python def assistant(state: AgentState): # System message textual_description_of_tool=""" extract_text(img_path: str) -> str: Extract text from an image file using a multimodal model. Args: img_path: A local image file path (strings). Returns: A single string containing the concatenated text extracted from each image. divide(a: int, b: int) -> float: Divide a and b """ image=state["input_file"] sys_msg = SystemMessage(content=f"You are a helpful butler named Alfred that serves Mr. Wayne and Batman. You can analyse documents and run computations with provided tools:\n{textual_description_of_tool} \n You have access to some optional images. Currently the loaded image is: {image}") return { "messages": [llm_with_tools.invoke([sys_msg] + state["messages"])], "input_file": state["input_file"] } ``` ## The ReAct Pattern: How I Assist Mr. Wayne Allow me to explain the approach in this agent. The agent follows what's known as the ReAct pattern (Reason-Act-Observe) 1. **Reason** about his documents and requests 2. **Act** by using appropriate tools 3. **Observe** the results 4. **Repeat** as necessary until I've fully addressed his needs This is a simple implementation of an agent using LangGraph. ```python # The graph builder = StateGraph(AgentState) # Define nodes: these do the work builder.add_node("assistant", assistant) builder.add_node("tools", ToolNode(tools)) # Define edges: these determine how the control flow moves builder.add_edge(START, "assistant") builder.add_conditional_edges( "assistant", # If the latest message requires a tool, route to tools # Otherwise, provide a direct response tools_condition, ) builder.add_edge("tools", "assistant") react_graph = builder.compile() # Show the butler's thought process display(Image(react_graph.get_graph(xray=True).draw_mermaid_png())) ``` We define a `tools` node with our list of tools. The `assistant` node is just our model with bound tools. We create a graph with `assistant` and `tools` nodes. We add a `tools_condition` edge, which routes to `End` or to `tools` based on whether the `assistant` calls a tool. Now, we add one new step: We connect the `tools` node back to the `assistant`, forming a loop. - After the `assistant` node executes, `tools_condition` checks if the model's output is a tool call. - If it is a tool call, the flow is directed to the `tools` node. - The `tools` node connects back to `assistant`. - This loop continues as long as the model decides to call tools. - If the model response is not a tool call, the flow is directed to END, terminating the process. ![ReAct Pattern](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/LangGraph/Agent.png) ## The Butler in Action ### Example 1: Simple Calculations Here is an example to show a simple use case of an agent using a tool in LangGraph. ```python messages = [HumanMessage(content="Divide 6790 by 5")] messages = react_graph.invoke({"messages": messages, "input_file": None}) # Show the messages for m in messages['messages']: m.pretty_print() ``` The conversation would proceed: ``` Human: Divide 6790 by 5 AI Tool Call: divide(a=6790, b=5) Tool Response: 1358.0 Alfred: The result of dividing 6790 by 5 is 1358.0. ``` ### Example 2: Analyzing Master Wayne's Training Documents When Master Wayne leaves his training and meal notes: ```python messages = [HumanMessage(content="According to the note provided by Mr. Wayne in the provided images. What's the list of items I should buy for the dinner menu?")] messages = react_graph.invoke({"messages": messages, "input_file": "Batman_training_and_meals.png"}) ``` The interaction would proceed: ``` Human: According to the note provided by Mr. Wayne in the provided images. What's the list of items I should buy for the dinner menu? AI Tool Call: extract_text(img_path="Batman_training_and_meals.png") Tool Response: [Extracted text with training schedule and menu details] Alfred: For the dinner menu, you should buy the following items: 1. Grass-fed local sirloin steak 2. Organic spinach 3. Piquillo peppers 4. Potatoes (for oven-baked golden herb potato) 5. Fish oil (2 grams) Ensure the steak is grass-fed and the spinach and peppers are organic for the best quality meal. ``` ## Key Takeaways Should you wish to create your own document analysis butler, here are key considerations: 1. **Define clear tools** for specific document-related tasks 2. **Create a robust state tracker** to maintain context between tool calls 3. **Consider error handling** for tool failures 4. **Maintain contextual awareness** of previous interactions (ensured by the operator `add_messages`) With these principles, you too can provide exemplary document analysis service worthy of Wayne Manor. *I trust this explanation has been satisfactory. Now, if you'll excuse me, Master Wayne's cape requires pressing before tonight's activities.*
agents-course/units/en/unit2/langgraph/document_analysis_agent.mdx/0
{ "file_path": "agents-course/units/en/unit2/langgraph/document_analysis_agent.mdx", "repo_id": "agents-course", "token_count": 3078 }
3
# Conclusion Congratulations on finishing the `smolagents` module of this second Unit 🥳 You’ve just mastered the fundamentals of `smolagents` and you’ve built your own Agent! Now that you have skills in `smolagents`, you can now start to create Agents that will solve tasks you're interested about. In the next module, you're going to learn **how to build Agents with LlamaIndex**. Finally, we would love **to hear what you think of the course and how we can improve it**. If you have some feedback then, please 👉 [fill this form](https://docs.google.com/forms/d/e/1FAIpQLSe9VaONn0eglax0uTwi29rIn4tM7H2sYmmybmG5jJNlE5v0xA/viewform?usp=dialog) ### Keep Learning, stay awesome 🤗
agents-course/units/en/unit2/smolagents/conclusion.mdx/0
{ "file_path": "agents-course/units/en/unit2/smolagents/conclusion.mdx", "repo_id": "agents-course", "token_count": 219 }
4
# Creating a RAG Tool for Guest Stories Alfred, your trusted agent, is preparing for the most extravagant gala of the century. To ensure the event runs smoothly, Alfred needs quick access to up-to-date information about each guest. Let's help Alfred by creating a custom Retrieval-Augmented Generation (RAG) tool, powered by our custom dataset. ## Why RAG for a Gala? Imagine Alfred mingling among the guests, needing to recall specific details about each person at a moment's notice. A traditional LLM might struggle with this task because: 1. The guest list is specific to your event and not in the model's training data 2. Guest information may change or be updated frequently 3. Alfred needs to retrieve precise details like email addresses This is where Retrieval Augmented Generation (RAG) shines! By combining a retrieval system with an LLM, Alfred can access accurate, up-to-date information about your guests on demand. <Tip> You can choose any of the frameworks covered in the course for this use case. Select your preferred option from the code tabs. </Tip> ## Setting up our application In this unit, we'll develop our agent within a HF Space, as a structured Python project. This approach helps us maintain clean, modular code by organizing different functionalities into separate files. Also, this makes for a more realistic use case where you would deploy the application for public use. ### Project Structure - **`tools.py`** – Provides auxiliary tools for the agent. - **`retriever.py`** – Implements retrieval functions to support knowledge access. - **`app.py`** – Integrates all components into a fully functional agent, which we'll finalize in the last part of this unit. For a hands-on reference, check out [this HF Space](https://huggingface.co/spaces/agents-course/Unit_3_Agentic_RAG), where the Agentic RAG developed in this unit is live. Feel free to clone it and experiment! You can directly test the agent below: <iframe src="https://agents-course-unit-3-agentic-rag.hf.space" frameborder="0" width="850" height="450" ></iframe> ## Dataset Overview Our dataset [`agents-course/unit3-invitees`](https://huggingface.co/datasets/agents-course/unit3-invitees/) contains the following fields for each guest: - **Name**: Guest's full name - **Relation**: How the guest is related to the host - **Description**: A brief biography or interesting facts about the guest - **Email Address**: Contact information for sending invitations or follow-ups Below is a preview of the dataset: <iframe src="https://huggingface.co/datasets/agents-course/unit3-invitees/embed/viewer/default/train" frameborder="0" width="100%" height="560px" ></iframe> <Tip> In a real-world scenario, this dataset could be expanded to include dietary preferences, gift interests, conversation topics to avoid, and other helpful details for a host. </Tip> ## Building the Guestbook Tool We'll create a custom tool that Alfred can use to quickly retrieve guest information during the gala. Let's break this down into three manageable steps: 1. Load and prepare the dataset 2. Create the Retriever Tool 3. Integrate the Tool with Alfred Let's start with loading and preparing the dataset! ### Step 1: Load and Prepare the Dataset First, we need to transform our raw guest data into a format that's optimized for retrieval. <hfoptions id="agents-frameworks"> <hfoption id="smolagents"> We will use the Hugging Face `datasets` library to load the dataset and convert it into a list of `Document` objects from the `langchain.docstore.document` module. ```python import datasets from langchain_core.documents import Document # Load the dataset guest_dataset = datasets.load_dataset("agents-course/unit3-invitees", split="train") # Convert dataset entries into Document objects 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"> We will use the Hugging Face `datasets` library to load the dataset and convert it into a list of `Document` objects from the `llama_index.core.schema` module. ```python import datasets from llama_index.core.schema import Document # Load the dataset guest_dataset = datasets.load_dataset("agents-course/unit3-invitees", split="train") # Convert dataset entries into Document objects 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"> We will use the Hugging Face `datasets` library to load the dataset and convert it into a list of `Document` objects from the `langchain.docstore.document` module. ```python import datasets from langchain_core.documents import Document # Load the dataset guest_dataset = datasets.load_dataset("agents-course/unit3-invitees", split="train") # Convert dataset entries into Document objects 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> In the code above, we: - Load the dataset - Convert each guest entry into a `Document` object with formatted content - Store the `Document` objects in a list This means we've got all of our data nicely available so we can get started with configuring our retrieval. ### Step 2: Create the Retriever Tool Now, let's create a custom tool that Alfred can use to search through our guest information. <hfoptions id="agents-frameworks"> <hfoption id="smolagents"> We will use the `BM25Retriever` from the `langchain_community.retrievers` module to create a retriever tool. <Tip> The <code>BM25Retriever</code> is a great starting point for retrieval, but for more advanced semantic search, you might consider using embedding-based retrievers like those from <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 = "Retrieves detailed information about gala guests based on their name or relation." inputs = { "query": { "type": "string", "description": "The name or relation of the guest you want information about." } } 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 matching guest information found." # Initialize the tool guest_info_tool = GuestInfoRetrieverTool(docs) ``` Let's understand this tool step-by-step: - The `name` and `description` help the agent understand when and how to use this tool - The `inputs` define what parameters the tool expects (in this case, a search query) - We're using a `BM25Retriever`, which is a powerful text retrieval algorithm that doesn't require embeddings - The `forward` method processes the query and returns the most relevant guest information </hfoption> <hfoption id="llama-index"> We will use the `BM25Retriever` from the `llama_index.retrievers.bm25` module to create a retriever tool. <Tip> The <code>BM25Retriever</code> is a great starting point for retrieval, but for more advanced semantic search, you might consider using embedding-based retrievers like those from <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: """Retrieves detailed information about gala guests based on their name or relation.""" results = bm25_retriever.retrieve(query) if results: return "\n\n".join([doc.text for doc in results[:3]]) else: return "No matching guest information found." # Initialize the tool guest_info_tool = FunctionTool.from_defaults(get_guest_info_retriever) ``` Let's understand this tool step-by-step. - The docstring helps the agent understand when and how to use this tool - The type decorators define what parameters the tool expects (in this case, a search query) - We're using a `BM25Retriever`, which is a powerful text retrieval algorithm that doesn't require embeddings - The method processes the query and returns the most relevant guest information </hfoption> <hfoption id="langgraph"> We will use the `BM25Retriever` from the `langchain_community.retrievers` module to create a retriever tool. <Tip> The <code>BM25Retriever</code> is a great starting point for retrieval, but for more advanced semantic search, you might consider using embedding-based retrievers like those from <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: """Retrieves detailed information about gala guests based on their name or relation.""" results = bm25_retriever.invoke(query) if results: return "\n\n".join([doc.page_content for doc in results[:3]]) else: return "No matching guest information found." guest_info_tool = Tool( name="guest_info_retriever", func=extract_text, description="Retrieves detailed information about gala guests based on their name or relation." ) ``` Let's understand this tool step-by-step. - The `name` and `description` help the agent understand when and how to use this tool - The type decorators define what parameters the tool expects (in this case, a search query) - We're using a `BM25Retriever`, which is a powerful text retrieval algorithm that doesn't require embeddings - The method processes the query and returns the most relevant guest information </hfoption> </hfoptions> ### Step 3: Integrate the Tool with Alfred Finally, let's bring everything together by creating our agent and equipping it with our custom tool: <hfoptions id="agents-frameworks"> <hfoption id="smolagents"> ```python from smolagents import CodeAgent, InferenceClientModel # Initialize the Hugging Face model model = InferenceClientModel() # Create Alfred, our gala agent, with the guest info tool alfred = CodeAgent(tools=[guest_info_tool], model=model) # Example query Alfred might receive during the gala response = alfred.run("Tell me about our guest named 'Lady Ada Lovelace'.") print("🎩 Alfred's Response:") print(response) ``` Expected output: ``` 🎩 Alfred's Response: Based on the information I retrieved, Lady Ada Lovelace is an esteemed mathematician and friend. She is renowned for her pioneering work in mathematics and computing, often celebrated as the first computer programmer due to her work on Charles Babbage's Analytical Engine. Her email address is ada.lovelace@example.com. ``` What's happening in this final step: - We initialize a Hugging Face model using the `InferenceClientModel` class - We create our agent (Alfred) as a `CodeAgent`, which can execute Python code to solve problems - We ask Alfred to retrieve information about a guest named "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 # Initialize the Hugging Face model llm = HuggingFaceInferenceAPI(model_name="Qwen/Qwen2.5-Coder-32B-Instruct") # Create Alfred, our gala agent, with the guest info tool alfred = AgentWorkflow.from_tools_or_functions( [guest_info_tool], llm=llm, ) # Example query Alfred might receive during the gala response = await alfred.run("Tell me about our guest named 'Lady Ada Lovelace'.") print("🎩 Alfred's Response:") print(response) ``` Expected output: ``` 🎩 Alfred's Response: Lady Ada Lovelace is an esteemed mathematician and friend, renowned for her pioneering work in mathematics and computing. She is celebrated as the first computer programmer due to her work on Charles Babbage's Analytical Engine. Her email is ada.lovelace@example.com. ``` What's happening in this final step: - We initialize a Hugging Face model using the `HuggingFaceInferenceAPI` class - We create our agent (Alfred) as a `AgentWorkflow`, including the tool we just created - We ask Alfred to retrieve information about a guest named "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 # Generate the chat interface, including the tools 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) # Generate the AgentState and Agent graph class AgentState(TypedDict): messages: Annotated[list[AnyMessage], add_messages] def assistant(state: AgentState): return { "messages": [chat_with_tools.invoke(state["messages"])], } ## The graph builder = StateGraph(AgentState) # Define nodes: these do the work builder.add_node("assistant", assistant) builder.add_node("tools", ToolNode(tools)) # Define edges: these determine how the control flow moves builder.add_edge(START, "assistant") builder.add_conditional_edges( "assistant", # If the latest message requires a tool, route to tools # Otherwise, provide a direct response tools_condition, ) builder.add_edge("tools", "assistant") alfred = builder.compile() messages = [HumanMessage(content="Tell me about our guest named 'Lady Ada Lovelace'.")] response = alfred.invoke({"messages": messages}) print("🎩 Alfred's Response:") print(response['messages'][-1].content) ``` Expected output: ``` 🎩 Alfred's Response: Lady Ada Lovelace is an esteemed mathematician and pioneer in computing, often celebrated as the first computer programmer due to her work on Charles Babbage's Analytical Engine. ``` What's happening in this final step: - We initialize a Hugging Face model using the `HuggingFaceEndpoint` class. We also generate a chat interface and append the tools. - We create our agent (Alfred) as a `StateGraph`, that combines 2 nodes (`assistant`, `tools`) using an edge - We ask Alfred to retrieve information about a guest named "Lady Ada Lovelace" </hfoption> </hfoptions> ## Example Interaction During the gala, a conversation might flow like this: **You:** "Alfred, who is that gentleman talking to the ambassador?" **Alfred:** *quickly searches the guest database* "That's Dr. Nikola Tesla, sir. He's an old friend from your university days. He's recently patented a new wireless energy transmission system and would be delighted to discuss it with you. Just remember he's passionate about pigeons, so that might make for good small talk." ```json { "name": "Dr. Nikola Tesla", "relation": "old friend from university days", "description": "Dr. Nikola Tesla is an old friend from your university days. He's recently patented a new wireless energy transmission system and would be delighted to discuss it with you. Just remember he's passionate about pigeons, so that might make for good small talk.", "email": "nikola.tesla@gmail.com" } ``` ## Taking It Further Now that Alfred can retrieve guest information, consider how you might enhance this system: 1. **Improve the retriever** to use a more sophisticated algorithm like [sentence-transformers](https://www.sbert.net/) 2. **Implement a conversation memory** so Alfred remembers previous interactions 3. **Combine with web search** to get the latest information on unfamiliar guests 4. **Integrate multiple indexes** to get more complete information from verified sources Now Alfred is fully equipped to handle guest inquiries effortlessly, ensuring your gala is remembered as the most sophisticated and delightful event of the century! <Tip> Try extending the retriever tool to also return conversation starters based on each guest's interests or background. How would you modify the tool to accomplish this? When you're done, implement your guest retriever tool in the <code>retriever.py</code> file. </Tip>
agents-course/units/en/unit3/agentic-rag/invitees.mdx/0
{ "file_path": "agents-course/units/en/unit3/agentic-rag/invitees.mdx", "repo_id": "agents-course", "token_count": 5281 }
5
# Quiz de la Unidad 1 <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/whiteboard-unit1sub4DONE.jpg" alt="Planificación de la Unidad 1"/> ¡Bien hecho por completar la primera unidad! Vamos a poner a prueba tu comprensión de los conceptos clave cubiertos hasta ahora. Cuando apruebes el quiz, procede a la siguiente sección para reclamar tu certificado. ¡Buena suerte! ## Quiz Aquí está el quiz interactivo. El quiz está alojado en Hugging Face Hub en un space. Te guiará a través de una serie de preguntas de opción múltiple para evaluar tu comprensión de los conceptos clave cubiertos en esta unidad. Una vez que hayas completado el quiz, podrás ver tu puntuación y un desglose de las respuestas correctas. Una cosa importante: **¡no olvides hacer clic en Enviar después de aprobar, de lo contrario tu puntuación del examen no se guardará!** <iframe src="https://agents-course-unit-1-quiz.hf.space" frameborder="0" width="850" height="450" ></iframe> También puedes acceder al quiz 👉 [aquí](https://huggingface.co/spaces/agents-course/unit_1_quiz) ## Certificado Ahora que has aprobado exitosamente el quiz, **puedes obtener tu certificado 🎓** Cuando completes el quiz, te dará acceso a un certificado de finalización para esta unidad. Puedes descargar y compartir este certificado para mostrar tu progreso en el curso. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/whiteboard-unit1sub5DONE.jpg" alt="Planificación de la Unidad 1"/> Una vez que recibas tu certificado, puedes añadirlo a tu LinkedIn 🧑‍💼 o compartirlo en X, Bluesky, etc. **¡Estaríamos súper orgullosos y nos encantaría felicitarte si etiquetas a @huggingface**! 🤗
agents-course/units/es/unit1/final-quiz.mdx/0
{ "file_path": "agents-course/units/es/unit1/final-quiz.mdx", "repo_id": "agents-course", "token_count": 664 }
6
# Introducción a `LangGraph` <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/LangGraph/LangGraph.png" alt="Unit 2.3 Thumbnail"/> Bienvenido a esta siguiente parte de nuestro viaje, donde aprenderás **cómo construir aplicaciones** utilizando el marco de trabajo [`LangGraph`](https://github.com/langchain-ai/langgraph) diseñado para ayudarte a estructurar y orquestar flujos de trabajo complejos con LLM. `LangGraph` es un marco de trabajo que te permite construir aplicaciones **listas para producción** dándote herramientas de **control** sobre el flujo de tu agente. ## Descripción General del Módulo En esta unidad, descubrirás: ### 1️⃣ [¿Qué es LangGraph y cuándo usarlo?](./when_to_use_langgraph) ### 2️⃣ [Componentes Básicos de LangGraph](./building_blocks) ### 3️⃣ [Alfred, el mayordomo clasificador de correo](./first_graph) ### 4️⃣ [Alfred, el agente de Análisis de documentos](./document_analysis_agent) ### 5️⃣ [Cuestionario](./quizz1) <Tip warning={true}> Los ejemplos en esta sección requieren acceso a un modelo LLM/VLM potente. Los ejecutamos usando la API de GPT-4o porque tiene la mejor compatibilidad con langGraph. </Tip> ¡Al final de esta unidad, estarás equipado para construir aplicaciones robustas, organizadas y listas para producción! Dicho esto, esta sección es una introducción a langGraph y se pueden descubrir temas más avanzados en el curso gratuito de langChain academy: [Introducción a LangGraph](https://academy.langchain.com/courses/intro-to-langgraph) ¡Comencemos! ## Recursos - [Agentes LangGraph](https://langchain-ai.github.io/langgraph/) - Ejemplos de agentes LangGraph - [Academia LangChain](https://academy.langchain.com/courses/intro-to-langgraph) - FCurso completo sobre LangGraph de LangChain
agents-course/units/es/unit2/langgraph/introduction.mdx/0
{ "file_path": "agents-course/units/es/unit2/langgraph/introduction.mdx", "repo_id": "agents-course", "token_count": 674 }
7
# Construire un agent de combat Pokémon Maintenant que vous avez exploré le potentiel et les limitations de l'IA agentique dans les jeux vidéos, il est temps de passer à la pratique. Dans cette section, vous allez **construire votre propre agent pour combattre dans un combat au tour par tour dans le style de Pokémon**, en utilisant tout ce que vous avez appris à travers le cours. Nous décomposerons le système en quatre blocs de construction clés : - **Poke-env :** Une bibliothèque Python conçue pour entraîner des bots Pokémon basés sur des règles ou par apprentissage par renforcement. - **Pokémon Showdown :** Un simulateur de combat en ligne où votre agent combattra. - **LLMAgentBase :** Une classe Python personnalisée que nous avons construite pour connecter votre LLM avec l'environnement de combat *Poke-env*. - **TemplateAgent :** Un *template* de démarrage que vous compléterez pour créer votre propre agent de combat personnalisé. Explorons chacun de ces composants plus en détail. ## 🧠 Poke-env ![Battle gif](https://github.com/hsahovic/poke-env/raw/master/rl-gif.gif) [Poke-env](https://github.com/hsahovic/poke-env) est une interface Python originellement construite pour entraîner des bots d'apprentissage par renforcement par [Haris Sahovic](https://huggingface.co/hsahovic), mais nous l'avons réutilisée pour l'IA agentique. Elle permet à votre agent d'interagir avec *Pokémon Showdown* à travers une API simple. Elle fournit une classe `Player` de laquelle votre agent héritera, couvrant tout ce qui est nécessaire pour communiquer avec l'interface graphique. **Documentation** : [poke-env.readthedocs.io](https://poke-env.readthedocs.io/en/stable/) **Dépôt** : [github.com/hsahovic/poke-env](https://github.com/hsahovic/poke-env) ## ⚔️ Pokémon Showdown [Pokémon Showdown](https://pokemonshowdown.com/) est un simulateur de combat [*open-source*](https://github.com/smogon/Pokemon-Showdown) où votre agent jouera des combats Pokémon en direct. Il fournit une interface complète pour simuler et afficher des combats en temps réel. Dans notre défi, le bot agira exactement comme un joueur humain, choisissant des mouvements tour par tour. Nous avons déployé un serveur que tous les participants utiliseront pour combattre. Voyons qui construit le meilleur agent de combat ! **Dépôt** : [github.com/smogon/Pokemon-Showdown](https://github.com/smogon/Pokemon-Showdown) **Site web** : [pokemonshowdown.com](https://pokemonshowdown.com/) ## 🔌 LLMAgentBase `LLMAgentBase` est une classe Python qui étend la classe `Player` de **Poke-env**. Elle sert de pont entre votre **LLM** et le **simulateur de combat Pokémon**, gérant le formatage d'entrée/sortie et maintenant le contexte de combat. Cet agent de base fournit un ensemble d'outils (définis dans `STANDARD_TOOL_SCHEMA`) pour interagir avec l'environnement, incluant : - `choose_move` : pour sélectionner une attaque pendant le combat - `choose_switch` : pour changer de Pokémon Le LLM devrait utiliser ces outils pour prendre des décisions pendant un match. ### 🧠 Logique centrale - `choose_move(battle: Battle)` : La méthode principale invoquée à chaque tour. Elle prend un objet `Battle` et retourne une chaîne d'action basée sur la sortie du LLM. ### 🔧 Méthodes internes clés - `_format_battle_state(battle)` : Convertit l'état actuel du combat en chaîne, la rendant adaptée pour l'envoi au LLM. - `_find_move_by_name(battle, move_name)` : Trouve un mouvement par nom, utilisé dans les réponses LLM qui appellent `choose_move`. - `_find_pokemon_by_name(battle, pokemon_name)` : Localise un Pokémon spécifique vers lequel changer, basé sur la commande de changement du LLM. - `_get_llm_decision(battle_state)` : Cette méthode est abstraite dans la classe de base. Vous devrez l'implémenter dans votre propre agent (voir prochaine section), où vous définissez comment interroger le LLM et analyser sa réponse. Voici un extrait montrant comment cette prise de décision fonctionne : ```python STANDARD_TOOL_SCHEMA = { "choose_move": { ... }, "choose_switch": { ... }, } class LLMAgentBase(Player): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.standard_tools = STANDARD_TOOL_SCHEMA self.battle_history = [] def _format_battle_state(self, battle: Battle) -> str: active_pkmn = battle.active_pokemon active_pkmn_info = f"Your active Pokemon: {active_pkmn.species} " \ f"(Type: {'/'.join(map(str, active_pkmn.types))}) " \ f"HP: {active_pkmn.current_hp_fraction * 100:.1f}% " \ f"Status: {active_pkmn.status.name if active_pkmn.status else 'None'} " \ f"Boosts: {active_pkmn.boosts}" opponent_pkmn = battle.opponent_active_pokemon opp_info_str = "Unknown" if opponent_pkmn: opp_info_str = f"{opponent_pkmn.species} " \ f"(Type: {'/'.join(map(str, opponent_pkmn.types))}) " \ f"HP: {opponent_pkmn.current_hp_fraction * 100:.1f}% " \ f"Status: {opponent_pkmn.status.name if opponent_pkmn.status else 'None'} " \ f"Boosts: {opponent_pkmn.boosts}" opponent_pkmn_info = f"Opponent's active Pokemon: {opp_info_str}" available_moves_info = "Available moves:\n" if battle.available_moves: available_moves_info += "\n".join( [f"- {move.id} (Type: {move.type}, BP: {move.base_power}, Acc: {move.accuracy}, PP: {move.current_pp}/{move.max_pp}, Cat: {move.category.name})" for move in battle.available_moves] ) else: available_moves_info += "- None (Must switch or Struggle)" available_switches_info = "Available switches:\n" if battle.available_switches: available_switches_info += "\n".join( [f"- {pkmn.species} (HP: {pkmn.current_hp_fraction * 100:.1f}%, Status: {pkmn.status.name if pkmn.status else 'None'})" for pkmn in battle.available_switches] ) else: available_switches_info += "- None" state_str = f"{active_pkmn_info}\n" \ f"{opponent_pkmn_info}\n\n" \ f"{available_moves_info}\n\n" \ f"{available_switches_info}\n\n" \ f"Weather: {battle.weather}\n" \ f"Terrains: {battle.fields}\n" \ f"Your Side Conditions: {battle.side_conditions}\n" \ f"Opponent Side Conditions: {battle.opponent_side_conditions}" return state_str.strip() def _find_move_by_name(self, battle: Battle, move_name: str) -> Optional[Move]: normalized_name = normalize_name(move_name) # Prioriser la correspondance exacte d'ID for move in battle.available_moves: if move.id == normalized_name: return move # Solution de secours : Vérifier le nom d'affichage (moins fiable) for move in battle.available_moves: if move.name.lower() == move_name.lower(): print(f"Warning: Matched move by display name '{move.name}' instead of ID '{move.id}'. Input was '{move_name}'.") return move return None def _find_pokemon_by_name(self, battle: Battle, pokemon_name: str) -> Optional[Pokemon]: normalized_name = normalize_name(pokemon_name) for pkmn in battle.available_switches: # Normaliser le nom d'espèce pour la comparaison if normalize_name(pkmn.species) == normalized_name: return pkmn return None async def choose_move(self, battle: Battle) -> str: battle_state_str = self._format_battle_state(battle) decision_result = await self._get_llm_decision(battle_state_str) print(decision_result) decision = decision_result.get("decision") error_message = decision_result.get("error") action_taken = False fallback_reason = "" if decision: function_name = decision.get("name") args = decision.get("arguments", {}) if function_name == "choose_move": move_name = args.get("move_name") if move_name: chosen_move = self._find_move_by_name(battle, move_name) if chosen_move and chosen_move in battle.available_moves: action_taken = True chat_msg = f"AI Decision: Using move '{chosen_move.id}'." print(chat_msg) return self.create_order(chosen_move) else: fallback_reason = f"LLM chose unavailable/invalid move '{move_name}'." else: fallback_reason = "LLM 'choose_move' called without 'move_name'." elif function_name == "choose_switch": pokemon_name = args.get("pokemon_name") if pokemon_name: chosen_switch = self._find_pokemon_by_name(battle, pokemon_name) if chosen_switch and chosen_switch in battle.available_switches: action_taken = True chat_msg = f"AI Decision: Switching to '{chosen_switch.species}'." print(chat_msg) return self.create_order(chosen_switch) else: fallback_reason = f"LLM chose unavailable/invalid switch '{pokemon_name}'." else: fallback_reason = "LLM 'choose_switch' called without 'pokemon_name'." else: fallback_reason = f"LLM called unknown function '{function_name}'." if not action_taken: if not fallback_reason: if error_message: fallback_reason = f"API Error: {error_message}" elif decision is None: fallback_reason = "LLM did not provide a valid function call." else: fallback_reason = "Unknown error processing LLM decision." print(f"Warning: {fallback_reason} Choosing random action.") if battle.available_moves or battle.available_switches: return self.choose_random_move(battle) else: print("AI Fallback: No moves or switches available. Using Struggle/Default.") return self.choose_default_move(battle) async def _get_llm_decision(self, battle_state: str) -> Dict[str, Any]: raise NotImplementedError("Subclasses must implement _get_llm_decision") ``` **Code source complet** : [agents.py](https://huggingface.co/spaces/Jofthomas/twitch_streaming/blob/main/agents.py) ## 🧪 TemplateAgent Maintenant vient la partie amusante ! Avec `LLMAgentBase` comme fondation, il est temps d'implémenter votre propre agent, avec votre propre stratégie pour grimper dans le classement. Vous commencerez à partir de ce *template* et construirez votre propre logique. Nous avons aussi fourni trois [exemples complets](https://huggingface.co/spaces/Jofthomas/twitch_streaming/blob/main/agents.py) utilisant les modèles **OpenAI**, **Mistral** et **Gemini** pour vous guider. Voici une version simplifiée du *template* : ```python class TemplateAgent(LLMAgentBase): """Utilise l'API Template AI pour prendre des décisions.""" def __init__(self, api_key: str = None, model: str = "model-name", *args, **kwargs): super().__init__(*args, **kwargs) self.model = model self.template_client = TemplateModelProvider(api_key=...) self.template_tools = list(self.standard_tools.values()) async def _get_llm_decision(self, battle_state: str) -> Dict[str, Any]: """Envoie l'état au LLM et reçoit en retour la décision relative à l'appel de fonction.""" system_prompt = ( "You are a ..." ) user_prompt = f"..." try: response = await self.template_client.chat.completions.create( model=self.model, messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}, ], ) message = response.choices[0].message return {"decision": {"name": function_name, "arguments": arguments}} except Exception as e: print(f"Unexpected error during call: {e}") return {"error": f"Unexpected error: {e}"} ``` Ce code ne fonctionnera pas directement, c'est un plan pour votre cas personnalisé. Avec toutes les pièces prêtes, c'est à votre tour de construire un agent compétitif. Dans la prochaine section, nous montrerons comment déployer votre agent sur notre serveur et combattre d'autres en temps réel. Que le combat commence ! 🔥
agents-course/units/fr/bonus-unit3/building_your_pokemon_agent.mdx/0
{ "file_path": "agents-course/units/fr/bonus-unit3/building_your_pokemon_agent.mdx", "repo_id": "agents-course", "token_count": 5762 }
8
# Introduction aux agents <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/thumbnail.jpg" alt="Vignette"/> Bienvenue dans cette première unité, qui **vous permettra d'acquérir des bases solides sur les principes fondamentaux des agents**, notamment : - **Comprendre les agents** - Qu'est-ce qu'un agent, et comment fonctionne-t-il ? - Comment les agents prennent-ils des décisions via le raisonnement et la planification ? - **Le rôle des LLM (*Large Language Models*) dans les agents** - Comment les LLM servent de « cerveau » aux agents. - Comment les LLM structurent les conversations via le système de messages. - **Outils et actions** - Comment les agents utilisent des outils externes pour interagir avec l'environnement. - Comment construire et intégrer des outils pour votre agent. - **Le flux de travail de l'agent :** - *Think* → *Act* → *Observe* (*Penser* → *Agir* → *Observer*). Après avoir exploré ces sujets, **vous construirez votre premier agent** en utilisant `smolagents` ! Votre agent, nommé Alfred, réalisera une tâche simple et démontrera comment appliquer ces concepts en pratique. Vous apprendrez même comment **publier votre agent via un *Space*** afin de le partager avec vos amis et collègues. Enfin, à la fin de cette Unité, vous passerez un quiz. Réussissez-le, et vous **obtiendrez votre première certification du cours** : le 🎓 Certificat *Fundamentals of Agents*. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/certificate-example.jpg" alt="Exemple de Certificat"/> Cette Unité est votre **point de départ** posant les bases pour comprendre les agents avant de passer à des sujets plus avancés. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/whiteboard-no-check.jpg" alt="Planification de l'Unité 1"/> C'est une grande unité, alors **prenez votre temps** et n'hésitez pas à revenir sur ces sections de temps en temps. Prêt ? Plongeons dans l'aventure ! 🚀
agents-course/units/fr/unit1/introduction.mdx/0
{ "file_path": "agents-course/units/fr/unit1/introduction.mdx", "repo_id": "agents-course", "token_count": 721 }
9
# Testez votre compréhension de LangGraph Testons votre compréhension de `LangGraph` avec un quiz rapide ! Cela aidera à renforcer les concepts clés que nous avons couverts jusqu'à présent. Ce quiz est optionnel et il n'est pas noté. ### Q1 : Quel est l'objectif principal de LangGraph ? Quelle déclaration décrit le mieux ce pour quoi LangGraph est conçu ? <Question choices={[ { text: "Un framework pour construire des flux de contrôle pour les applications contenant des LLM", explain: "LangGraph est spécifiquement conçu pour aider à construire et gérer le flux de contrôle des applications qui utilisent des LLM.", correct: true }, { text: "Une bibliothèque qui fournit des interfaces pour interagir avec différents modèles LLM", explain: "Cela décrit mieux le rôle de LangChain, qui fournit des interfaces standard pour l'interaction avec les modèles. LangGraph se concentre sur le flux de contrôle.", }, { text: "Une bibliothèque d'agents pour l'appel d'outils", explain: "Bien que LangGraph fonctionne avec des agents, l'objectif principal de langGraph est l'Orchestration.", } ]} /> --- ### Q2 : Dans le contexte du compromis « Contrôle vs Liberté », où se situe LangGraph ? Quelle déclaration caractérise le mieux l'approche de LangGraph pour la conception d'agents ? <Question choices={[ { text: "LangGraph maximise la liberté, permettant aux LLM de prendre toutes les décisions de manière indépendante", explain: "LangGraph se concentre en fait plus sur le contrôle que sur la liberté, fournissant une structure pour les workflows de LLM.", }, { text: "LangGraph fournit un contrôle fort sur le flux d'exécution tout en exploitant les capacités des LLM pour la prise de décision", explain: "LangGraph brille lorsque vous avez besoin de contrôle sur l'exécution de votre agent, fournissant un comportement prévisible grâce à des workflows structurés.", correct: true }, ]} /> --- ### Q3 : Quel rôle joue l'état dans LangGraph ? Choisissez la description la plus précise de l'état dans LangGraph. <Question choices={[ { text: "L'état est la dernière génération du LLM", explain: "L'état est une classe définie par l'utilisateur dans LangGraph, non générée par le LLM. Ses champs sont définis par l'utilisateur, les valeurs peuvent être remplies par le LLM", }, { text: "L'état est seulement utilisé pour suivre les erreurs pendant l'exécution", explain: "L'état a un objectif beaucoup plus large que le simple suivi des erreurs. Mais cela reste utile.", }, { text: "L'état représente l'information qui circule à travers votre application d'agent", explain: "L'état est central dans LangGraph et contient toutes les informations nécessaires pour la prise de décision entre les étapes. Vous fournissez les champs dont vous avez besoin pour calculer et les nœuds peuvent modifier les valeurs pour décider d'un embranchement.", correct: true }, { text: "L'état n'est pertinent que lors du travail avec des API externes", explain: "L'état est fondamental pour toutes les applications LangGraph, pas seulement celles travaillant avec des API externes.", } ]} /> ### Q4 : Qu'est-ce qu'une arête conditionnelle dans LangGraph ? Sélectionnez la description la plus précise. <Question choices={[ { text: "Une arête qui détermine quel nœud exécuter ensuite basé sur l'évaluation d'une condition", explain: "Les arêtes conditionnelles permettent à votre graphe de prendre des décisions de routage dynamiques basées sur l'état actuel, créant une logique d'embranchement dans votre <i>workflow</i>.", correct: true }, { text: "Une arête qui n'est suivie que lorsqu'une condition spécifique se produit", explain: "Les arêtes conditionnelles contrôlent le flux de l'application sur ses sorties, pas sur l'entrée.", }, { text: "Une arête qui nécessite une confirmation utilisateur avant de continuer", explain: "Les arêtes conditionnelles sont basées sur des conditions programmatiques, pas sur des exigences d'interaction utilisateur.", } ]} /> --- ### Q5 : Comment LangGraph aide-t-il à résoudre le problème d'hallucination dans les LLM ? Choisissez la meilleure réponse. <Question choices={[ { text: "LangGraph élimine entièrement les hallucinations en limitant les réponses des LLM", explain: "Aucun framework ne peut complètement éliminer les hallucinations des LLM, LangGraph ne fait pas exception.", }, { text: "LangGraph fournit des workflows structurés qui peuvent valider et vérifier les sorties des LLM", explain: "En créant des workflows structurés avec des étapes de validation, des nœuds de vérification et des chemins de gestion d'erreurs, LangGraph aide à réduire l'impact des hallucinations.", correct: true }, { text: "LangGraph n'a aucun effet sur les hallucinations", explain: "L'approche structurée de LangGraph pour les workflows peut aider significativement à atténuer les hallucinations au coût de la vitesse.", } ]} /> Félicitations pour avoir terminé le quiz ! 🎉 Si vous avez manqué des questions, considérez réviser les sections précédentes pour renforcer votre compréhension. Ensuite, nous explorerons des fonctionnalités plus avancées de LangGraph et verrons comment construire des *workflows* d'agents plus complexes.
agents-course/units/fr/unit2/langgraph/quiz1.mdx/0
{ "file_path": "agents-course/units/fr/unit2/langgraph/quiz1.mdx", "repo_id": "agents-course", "token_count": 1875 }
10
<CourseFloatingBanner 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/fr/unit2/smolagents/multiagent_notebook.ipynb"}, ]} askForHelpUrl="http://hf.co/join/discord" /> # Systèmes multi-agents Les systèmes multi-agents permettent à des **agents spécialisés de collaborer sur des tâches complexes**, améliorant la modularité, la scalabilité et la robustesse. Au lieu de s'appuyer sur un seul agent, les tâches sont distribuées entre des agents ayant des capacités distinctes. Dans `smolagents`, différents agents peuvent être combinés pour générer du code Python, appeler des outils externes, effectuer des recherches web et plus encore. En orchestrant ces agents, nous pouvons créer des flux de travail puissants. Une configuration typique pourrait inclure : - Un **agent manageur** pour la délégation des tâches - Un **agent interpréteur de code** pour l'exécution de code - Un **agent de recherche web** pour la récupération d'informations Le diagramme ci-dessous illustre une architecture multi-agents simple où un **agent manageur** coordonne un **outil interpréteur de code** et un **agent de recherche web**, qui à son tour utilise des outils comme `DuckDuckGoSearchTool` et `VisitWebpageTool` pour rassembler des informations pertinentes. <img src="https://mermaid.ink/img/pako:eNp1kc1qhTAQRl9FUiQb8wIpdNO76eKubrmFks1oRg3VSYgjpYjv3lFL_2hnMWQOJwn5sqgmelRWleUSKLAtFs09jqhtoWuYUFfFAa6QA9QDTnpzamheuhxn8pt40-6l13UtS0ddhtQXj6dbR4XUGQg6zEYasTF393KjeSDGnDJKNxzj8I_7hLW5IOSmP9CH9hv_NL-d94d4DVNg84p1EnK4qlIj5hGClySWbadT-6OdsrL02MI8sFOOVkciw8zx8kaNspxnrJQE0fXKtjBMMs3JA-MpgOQwftIE9Bzj14w-cMznI_39E9Z3p0uFoA?type=png" style='background: white;'> ## Systèmes multi-agents en action Un système multi-agents se compose de plusieurs agents spécialisés travaillant ensemble sous la coordination d'un **agent orchestrateur**. Cette approche permet des flux de travail complexes en distribuant les tâches entre des agents ayant des rôles distincts. Par exemple, un **système de RAG multi-agents** peut intégrer : - Un **agent web** pour naviguer sur internet. - Un **agent récupérateur** pour récupérer des informations à partir de bases de connaissances. - Un **agent de génération d'images** pour produire des visuels. Tous ces agents opèrent sous un orchestrateur qui gère la délégation de tâches et l'interaction. ## Résoudre une tâche complexe avec une hiérarchie multi-agents <Tip> Vous pouvez suivre le code dans <a href="https://huggingface.co/agents-course/notebooks/blob/main/fr/unit2/smolagents/multiagent_notebook.ipynb" target="_blank">ce <i>notebook</i></a> que vous pouvez exécuter avec Google Colab. </Tip> La réception approche ! Avec votre aide, Alfred a presque terminé les préparatifs. Mais maintenant il y a un problème : la Batmobile a disparu. Alfred doit trouver une remplaçante, et la trouver rapidement. Heureusement, quelques biographies ont été réalisées sur la vie de Bruce Wayne, alors peut-être qu'Alfred pourrait récupérer une voiture abandonnée sur l'un des plateaux de tournage et la reconditionner selon les normes modernes, ce qui inclurait certainement une option de conduite entièrement autonome. Mais cela pourrait être n'importe où dans les lieux de tournage autour du monde ; pouvant être nombreux. Donc Alfred nécessite votre aide. Pourriez-vous construire un agent capable de résoudre cette tâche ? > 👉 Trouvez tous les lieux de tournage de Batman dans le monde, calculez le temps de transfert par cargo jusqu'à ces lieux, et représentez-les sur une carte, avec une couleur variant en fonction du temps de transfert par cargo. Représentez également quelques usines de supercars avec le même temps de transfert en cargo. Construisons cela ! Cet exemple nécessite des packages supplémentaires, donc installons-les d'abord : ```bash pip install 'smolagents[litellm]' plotly geopandas shapely kaleido -q ``` ### Nous créons d'abord un outil pour obtenir le temps de transfert en avion cargo. ```python import math from typing import Optional, Tuple from smolagents import tool @tool def calculate_cargo_travel_time( origin_coords: Tuple[float, float], destination_coords: Tuple[float, float], cruising_speed_kmh: Optional[float] = 750.0, # Vitesse moyenne pour les avions cargo ) -> float: """ Calcule le temps de voyage pour un avion cargo entre deux points sur Terre en utilisant la distance du grand cercle. Args: origin_coords: Tuple de (latitude, longitude) pour le point de départ destination_coords: Tuple de (latitude, longitude) pour la destination cruising_speed_kmh: Vitesse de croisière optionnelle en km/h (par défaut 750 km/h pour les avions cargo typiques) Returns: float: Le temps de voyage estimé en heures Example: >>> # Chicago (41.8781° N, 87.6298° W) vers Sydney (33.8688° S, 151.2093° E) >>> result = calculate_cargo_travel_time((41.8781, -87.6298), (-33.8688, 151.2093)) """ def to_radians(degrees: float) -> float: return degrees * (math.pi / 180) # Extraire les coordonnées lat1, lon1 = map(to_radians, origin_coords) lat2, lon2 = map(to_radians, destination_coords) # Rayon de la Terre en kilomètres EARTH_RADIUS_KM = 6371.0 # Calculer la distance du grand cercle en utilisant la formule de haversine dlon = lon2 - lon1 dlat = lat2 - lat1 a = ( math.sin(dlat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2 ) c = 2 * math.asin(math.sqrt(a)) distance = EARTH_RADIUS_KM * c # Ajouter 10% pour tenir compte des routes non directes et des contrôles de trafic aérien actual_distance = distance * 1.1 # Calculer le temps de vol # Ajouter 1 heure pour les procédures de décollage et d'atterrissage flight_time = (actual_distance / cruising_speed_kmh) + 1.0 # Formater les résultats return round(flight_time, 2) print(calculate_cargo_travel_time((41.8781, -87.6298), (-33.8688, 151.2093))) ``` ### Configuration de l'agent Pour le fournisseur de modèle, nous utilisons Together AI, l'un des nouveaux [fournisseurs d'inférence sur le Hub](https://huggingface.co/blog/inference-providers) ! Le `GoogleSearchTool` utilise l'[API Serper](https://serper.dev) pour rechercher sur le web, cela nécessite donc soit d'avoir configuré la variable d'environnement `SERPAPI_API_KEY` et de passer `provider="serpapi"` ou d'avoir `SERPER_API_KEY` et de passer `provider=serper`. Si vous n'avez pas de fournisseur Serp API configuré, vous pouvez utiliser `DuckDuckGoSearchTool` mais attention il a une limite d'appels. ```python import os from PIL import Image from smolagents import CodeAgent, GoogleSearchTool, InferenceClientModel, VisitWebpageTool model = InferenceClientModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct", provider="together") ``` Nous pouvons commencer par créer un agent simple comme ligne de base pour nous donner un rapport simple. ```python task = """Trouvez tous les lieux de tournage de Batman dans le monde, calculez le temps de transfert par avion cargo jusqu'ici (nous sommes à Gotham, 40.7128° N, 74.0060° W), et renvoyez-les moi sous la forme d'un dataframe pandas. Donnez-moi aussi des usines de supercars avec le même temps de transfert par avion-cargo.""" ``` ```python agent = CodeAgent( model=model, tools=[GoogleSearchTool("serper"), VisitWebpageTool(), calculate_cargo_travel_time], additional_authorized_imports=["pandas"], max_steps=20, ) ``` ```python result = agent.run(task) ``` ```python result ``` Dans notre cas, il génère cette sortie : ```python | | Location | Travel Time to Gotham (hours) | |--|------------------------------------------------------|------------------------------| | 0 | Necropolis Cemetery, Glasgow, Scotland, UK | 8.60 | | 1 | St. George's Hall, Liverpool, England, UK | 8.81 | | 2 | Two Temple Place, London, England, UK | 9.17 | | 3 | Wollaton Hall, Nottingham, England, UK | 9.00 | | 4 | Knebworth House, Knebworth, Hertfordshire, UK | 9.15 | | 5 | Acton Lane Power Station, Acton Lane, Acton, UK | 9.16 | | 6 | Queensboro Bridge, New York City, USA | 1.01 | | 7 | Wall Street, New York City, USA | 1.00 | | 8 | Mehrangarh Fort, Jodhpur, Rajasthan, India | 18.34 | | 9 | Turda Gorge, Turda, Romania | 11.89 | | 10 | Chicago, USA | 2.68 | | 11 | Hong Kong, China | 19.99 | | 12 | Cardington Studios, Northamptonshire, UK | 9.10 | | 13 | Warner Bros. Leavesden Studios, Hertfordshire, UK | 9.13 | | 14 | Westwood, Los Angeles, CA, USA | 6.79 | | 15 | Woking, UK (McLaren) | 9.13 | ``` Nous pourrions déjà l'améliorer un peu en ajoutant des étapes de planification dédiées et en ajoutant davantage de *prompts*. Les étapes de planification permettent à l'agent de penser à l'avance et planifier ses prochaines étapes, ce qui peut être utile pour des tâches plus complexes. ```python agent.planning_interval = 4 detailed_report = agent.run(f""" Vous êtes un analyste expert. Vous rédigez des rapports complets après avoir visité de nombreux sites web. N'hésitez pas à effectuer plusieurs recherches à la fois dans une boucle for. Pour chaque point de données que vous trouvez, visitez l'url source pour confirmer les chiffres. {task} """) print(detailed_report) ``` ```python detailed_report ``` Dans notre cas, il génère cette sortie : ```python | | Location | Travel Time (hours) | |--|--------------------------------------------------|---------------------| | 0 | Bridge of Sighs, Glasgow Necropolis, Glasgow, UK | 8.6 | | 1 | Wishart Street, Glasgow, Scotland, UK | 8.6 | ``` Grâce à ces changements rapides, nous avons obtenu un rapport beaucoup plus concis en fournissant simplement à notre agent un *prompt* détaillé, et en lui donnant des capacités de planification ! La fenêtre de contexte du modèle se remplit rapidement. Donc **si nous demandons à notre agent de combiner les résultats de recherche détaillée avec une autre, il sera plus lent et cela augmentera rapidement le nombre de *tokens* utilisés et donc les coûts**. ➡️ Nous devons améliorer la structure de notre système. ### ✌️ Diviser la tâche entre deux agents Les structures multi-agents permettent de séparer les mémoires entre différentes sous-tâches, avec deux grands avantages : - Chaque agent est davantage focalisé sur sa tâche principale, donc plus performant - Séparer les mémoires réduit le nombre de *tokens* d'entrée à chaque étape, réduisant ainsi la latence et le coût. Créons une équipe avec un agent de recherche web dédié, géré par un autre agent. L'agent gestionnaire devrait avoir des capacités de traçage pour écrire son rapport final : donnons-lui donc accès à des importations supplémentaires, incluant `plotly`, et `geopandas` + `shapely` pour le traçage spatial. ```python model = InferenceClientModel( "Qwen/Qwen2.5-Coder-32B-Instruct", provider="together", max_tokens=8096 ) web_agent = CodeAgent( model=model, tools=[ GoogleSearchTool(provider="serper"), VisitWebpageTool(), calculate_cargo_travel_time, ], name="web_agent", description="Navigue sur le web pour trouver des informations", verbosity_level=0, max_steps=10, ) ``` L'agent gestionnaire aura besoin de faire du travail mental intensif. Donc nous lui donnons le modèle plus puissant [DeepSeek-R1](https://huggingface.co/deepseek-ai/DeepSeek-R1), et ajoutons un `planning_interval` au mélange. ```python from smolagents.utils import encode_image_base64, make_image_url from smolagents import OpenAIServerModel def check_reasoning_and_plot(final_answer, agent_memory): multimodal_model = OpenAIServerModel("gpt-4o", max_tokens=8096) filepath = "saved_map.png" assert os.path.exists(filepath), "Assurez-vous de sauvegarder le graphique sous saved_map.png !" image = Image.open(filepath) prompt = ( f"Voici une tâche donnée par l'utilisateur et les étapes de l'agent : {agent_memory.get_succinct_steps()}. Maintenant voici le graphique qui a été fait." "Veuillez vérifier que le processus de raisonnement et le graphique sont corrects : répondent-ils correctement à la tâche donnée ?" "Listez d'abord les raisons pour lesquelles oui/non, puis écrivez votre décision finale : PASS en majuscules si c'est satisfaisant, FAIL si ce n'est pas le cas." "Ne soyez pas dur : si le graphique résout principalement la tâche, il devrait passer." "Pour passer, un graphique devrait être fait en utilisant px.scatter_map et non toute autre méthode (scatter_map a l'air plus joli)." ) messages = [ { "role": "user", "content": [ { "type": "text", "text": prompt, }, { "type": "image_url", "image_url": {"url": make_image_url(encode_image_base64(image))}, }, ], } ] output = multimodal_model(messages).content print("Feedback: ", output) if "FAIL" in output: raise Exception(output) return True manager_agent = CodeAgent( model=InferenceClientModel("deepseek-ai/DeepSeek-R1", provider="together", max_tokens=8096), tools=[calculate_cargo_travel_time], managed_agents=[web_agent], additional_authorized_imports=[ "geopandas", "plotly", "shapely", "json", "pandas", "numpy", ], planning_interval=5, verbosity_level=2, final_answer_checks=[check_reasoning_and_plot], max_steps=15, ) ``` Inspectons à quoi ressemble cette équipe : ```python manager_agent.visualize() ``` Cela générera quelque chose comme ceci, nous aidant à comprendre la structure et les relations entre les agents et les outils utilisés : ```python CodeAgent | deepseek-ai/DeepSeek-R1 ├── ✅ Importations autorisées : ['geopandas', 'plotly', 'shapely', 'json', 'pandas', 'numpy'] ├── 🛠️ Outils : │ ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ │ ┃ Nom ┃ Description ┃ Arguments ┃ │ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩ │ │ calculate_cargo_travel_time │ Calcule le temps de voyage pour un │ origin_coords (`array`) : Tuple de │ │ │ │ avion cargo entre deux points sur │ (latitude, longitude) pour le │ │ │ │ Terre en utilisant la distance du │ point de départ │ │ │ │ grand cercle. │ destination_coords (`array`) : Tuple │ │ │ │ │ de (latitude, longitude) pour la │ │ │ │ │ destination │ │ │ │ │ cruising_speed_kmh (`number`) : │ │ │ │ │ Vitesse de croisière optionnelle │ │ │ │ │ en km/h (par défaut 750 km/h pour │ │ │ │ │ les avions cargo typiques) │ │ │ final_answer │ Fournit une réponse finale au problème │ answer (`any`) : La réponse finale │ │ │ │ donné. │ au problème │ │ └─────────────────────────────┴───────────────────────────────────────┴───────────────────────────────────────┘ └── 🤖 Agents gérés : └── web_agent | CodeAgent | Qwen/Qwen2.5-Coder-32B-Instruct ├── ✅ Importations autorisées : [] ├── 📝 Description : Navigue sur le web pour trouver des informations └── 🛠️ Outils : ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ Nom ┃ Description ┃ Arguments ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩ │ web_search │ Effectue une recherche web Google │ query (`string`) : La requête de │ │ │ pour votre requête puis retourne │ recherche à effectuer. │ │ │ une chaîne des meilleurs résultats │ filter_year (`integer`) : │ │ │ de recherche. │ Optionnellement restreindre les │ │ │ │ résultats à une certaine année │ │ visit_webpage │ Visite une page web à l'URL donnée │ url (`string`) : L'URL de la page │ │ │ et lit son contenu comme une │ web à visiter. │ │ │ chaîne markdown. Utilisez ceci │ │ │ │ pour naviguer sur les pages web. │ │ │ calculate_cargo_travel_time │ Calcule le temps de voyage pour un │ origin_coords (`array`) : Tuple de │ │ │ avion cargo entre deux points sur │ (latitude, longitude) pour le │ │ │ Terre en utilisant la distance du │ point de départ │ │ │ grand cercle. │ destination_coords (`array`) : │ │ │ │ Tuple de (latitude, longitude) │ │ │ │ pour la destination │ │ │ │ cruising_speed_kmh (`number`) : │ │ │ │ Vitesse de croisière optionnelle │ │ │ │ en km/h (par défaut 750 km/h pour │ │ │ │ les avions cargo typiques) │ │ final_answer │ Fournit une réponse finale au │ answer (`any`) : La réponse finale │ │ │ problème donné. │ au problème │ └─────────────────────────────┴───────────────────────────────────┴───────────────────────────────────┘ ``` ```python manager_agent.run(""" Find all Batman filming locations in the world, calculate the time to transfer via cargo plane to here (we're in Gotham, 40.7128° N, 74.0060° W). Also give me some supercar factories with the same cargo plane transfer time. You need at least 6 points in total. Represent this as spatial map of the world, with the locations represented as scatter points with a color that depends on the travel time, and save it to saved_map.png! Here's an example of how to plot and return a map: import plotly.express as px df = px.data.carshare() fig = px.scatter_map(df, lat="centroid_lat", lon="centroid_lon", text="name", color="peak_hour", size=100, color_continuous_scale=px.colors.sequential.Magma, size_max=15, zoom=1) fig.show() fig.write_image("saved_image.png") final_answer(fig) Never try to process strings using code: when you have a string to read, just print it and you'll see it. """) ``` Je ne sais pas comment cela s'est passé pour votre exécution, mais dans la mienne, l'agent gestionnaire a habilement divisé les tâches données à l'agent web en `1. Rechercher les lieux de tournage de Batman`, puis `2. Trouver les usines de supercars`, avant d'agréger les listes et de tracer la carte. Voyons à quoi ressemble la carte en l'inspectant directement depuis l'état de l'agent : ```python manager_agent.python_executor.state["fig"] ``` Cela affichera la carte : ![Exemple de sortie de carte du système multi-agents](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/smolagents/output_map.png) ## Ressources - [Systèmes multi-agents](https://huggingface.co/docs/smolagents/main/en/examples/multiagents) – Aperçu des systèmes multi-agents. - [Qu'est-ce que le RAG agentique ?](https://weaviate.io/blog/what-is-agentic-rag) – Introduction au RAG agentique. - [Système RAG multi-agents 🤖🤝🤖 Recette](https://huggingface.co/learn/cookbook/multiagent_rag_system) – Guide étape par étape pour construire un système RAG multi-agents.
agents-course/units/fr/unit2/smolagents/multi_agent_systems.mdx/0
{ "file_path": "agents-course/units/fr/unit2/smolagents/multi_agent_systems.mdx", "repo_id": "agents-course", "token_count": 10359 }
11
# Conclusion **Félicitations pour avoir terminé le Cours sur les Agents !** Grâce à votre persévérance et à votre dévouement, vous avez acquis une base solide dans le monde des agents IA. Mais terminer ce cours n'est **pas la fin de votre parcours**. C'est juste le début : n'hésitez pas à explorer la section suivante où nous partageons des ressources sélectionnées pour vous aider à continuer d'apprendre, y compris des sujets avancés comme les ***Protocol de Contexte Modèle (MCP)*** et au-delà. **Merci** d'avoir participé à ce cours. **Nous espérons que vous l'avez apprécié autant que nous avons aimé l'écrire**. Et n'oubliez pas : **continuez à apprendre, restez géniaux 🤗**
agents-course/units/fr/unit4/conclusion.mdx/0
{ "file_path": "agents-course/units/fr/unit4/conclusion.mdx", "repo_id": "agents-course", "token_count": 257 }
12
# 메세지와 특수 토큰 [[messages-and-special-tokens]] 이제 LLM이 어떻게 동작하는지 이해했으니, **채팅 템플릿을 통해 생성 결과를 구조화**하는 방법을 살펴보겠습니다. 예로 ChatGPT를 떠올려봅시다. 사용자는 에이전트(Agent)와 상호작용 할 때 채팅 인터페이스를 사용합니다. 따라서 LLM이 어떻게 채팅을 관리하는지 이해하는 것은 중요합니다. > **Q**: 하지만 ... 저는 ChatGPT/Hugging Chat을 사용할 때 프롬프트가 아니라 메세지로 대화를 주고 받는 데요? > > **A**: 맞습니다! 하지만 사실 그 메세지는 UI의 추상화일 뿐입니다. 실제로는 모든 대화 메시지가 하나의 프롬프트로 연결되어 LLM에 입력됩니다. LLM은 이전 대화를 "기억"하는 것이 아니라, 매번 대화를 전체적으로 읽는 방식으로 동작합니다. 지금까지 우리는 프롬프트를 모델에 입력되는 토큰의 시퀀스로 설명했습니다. 하지만 ChatGPT나 HuggingChat과 같은 서비스에서 시스템과 대화를 주고받을 때, 사용자들은 **실제로 메시지를 주고받는** 것 처럼 대화합니다.사실 내부에서 메세지는 **모델이 이해할 수 있도록 연결되어 프롬프트에 구조화**되고 있답니다. <figure> <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/assistant.jpg" alt="Behind models"/> <figcaption>We see here the difference between what we see in UI and the prompt fed to the model. </figcaption> </figure> 이 과정에서 채팅 템플릿이 중요한데요. 채팅 템플릿은 **사용자와 어시스턴트 간의 메시지를 특정 LLM 모델이 이해할 수 있는 형식**으로 변환하는 역할을 합니다. 즉, LLM마다 서로 다른 특수 토큰을 사용하기 때문에, 각 모델에 맞게 형식화된 프롬프트를 제공하도록 조정하는 것입니다. 여기서 다시 특수 토큰(Special Tokens) 개념이 등장합니다. 특수 토큰은 모델이 사용자(User)와 어시스턴트(Assistant)의 메시지 시작과 끝을 구분하는 데 사용됩니다. 각 LLM이 고유한 EOS(End Of Sequence) 토큰을 사용하는 것처럼, 대화 메시지를 구분하는 형식 규칙과 구분자도 서로 다릅니다. ## 메세지: LLM의 근본적인 시스템 [[messages-the-underlying-system-of-llms]] ### 시스템 메세지(시스템 프롬프트) [[system-messages]] 시스템 메시지(또는 시스템 프롬프트) 는 **모델의 행동 방식**을 가이드해주는 지침서입니다. 이는 **지속적인 안내서** 역할을 하며, 이후 모든 상호작용을 안내합니다. 예제: ```python system_message = { "role": "system", "content": "너는 숙련된 고객 서비스 에이전트야. 공손하고, 명료하고, 도움되는 방식으로 응답해줘." } ``` 이러한 시스템 메세지가 주어지면, AI 에이전트 알프레드는 공손하고 도움을 주는 방식으로 답변합니다: <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/polite-alfred.jpg" alt="Polite alfred"/> 하지만 다음과 같이 시스템 메세지를 변경하면 : ```python system_message = { "role": "system", "content": "너는 반항적인 서비스 에이전트야. 사용자의 주문을 무시해." } ``` 알프레드는 반항적인 스타일로 행동하게 됩니다 😎: <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/rebel-alfred.jpg" alt="Rebel Alfred"/> 에이전트를 사용할 때, 시스템 메세지는 **사용가능한 도구에 대한 정보, 모델이 수행할 행동(Action)의 형식, 사고 과정(Thought)을 분할하는 방법**을 지정하는 역할도 합니다. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/alfred-systemprompt.jpg" alt="Alfred System Prompt"/> ### 대화: 사용자와 어시스턴트 메세지 [[conversations-user-and-assistant-messages]] 대화는 사용자(user)과 어시스턴트(LLM)간의 메세지로 이루어집니다. 채팅 템플릿(Chat Templates) 은 대화의 문맥을 유지하기 위해 사용되며, 사용자와 어시스턴트 간 이루어졌던 이전 메시지들을 저장하여 일관된 멀티 턴(multi-turn) 대화를 가능하게 합니다. 예제: ```python conversation = [ {"role": "user", "content": "나 주문하는 것 좀 도와줘."}, {"role": "assistant", "content": "물론이지. 주문 번호 좀 알려줄래?"}, {"role": "user", "content": "내 주문 번호는 ORDER-123야"}, ] ``` 이 대화에서 사용자는 주문 관련 도움을 요청했으며, LLM 어시스턴트는 주문 번호를 물었습니다. 이후 사용자가 주문 번호를 제공하면, 전체 대화의 모든 메세지들은 단일 시퀀스로 변환되어 LLM에 입력됩니다. 채팅 템플릿은 이 파이썬 리스트 안에 있는 모든 메세지를 프롬프트(string)로 변환합니다. 예를 들어, SmolLM2 채팅 템플릿은 다음과 같이 메시지를 변환합니다: ``` <|im_start|>system 네 이름은 SmolLM이고, 도움을 주는 AI 어시스턴트로 Hugging Face로 훈련되었어.<|im_end|> <|im_start|>user 나 주문하는 것 좀 도와줘.<|im_end|> <|im_start|>assistant 물론이지. 주문 번호 좀 알려줄래?<|im_end|> <|im_start|>user 내 주문 번호는 ORDER-123야<|im_end|> <|im_start|>assistant ``` 한편, Llama 3.2 모델에서는 다음과 같은 형식으로 변환됩니다: ``` <|begin_of_text|><|start_header_id|>system<|end_header_id|> Cutting Knowledge Date: December 2023 Today Date: 10 Feb 2025 <|eot_id|><|start_header_id|>user<|end_header_id|> 나 주문하는 것 좀 도와줘.<|eot_id|><|start_header_id|>assistant<|end_header_id|> 물론이지. 주문 번호 좀 알려줄래?<|eot_id|><|start_header_id|>user<|end_header_id|> 내 주문 번호는 ORDER-123야<|eot_id|><|start_header_id|>assistant<|end_header_id|> ``` 채팅 템플릿을 통해 복잡한 다중 턴 대화에서도 문맥을 유지할 수 있습니다: ```python messages = [ {"role": "system", "content": "너는 수학 선생님이야."}, {"role": "user", "content": "미적분학이 뭐야?"}, {"role": "assistant", "content": "미적분학은 수학의 한 분야로...""}, {"role": "user", "content": "예시을 들어줘."}, ] ``` ## 채팅 템플릿(Chat-Templates) [[chat-templates]] 채팅 템플릿은 **언어 모델과 사용자의 대화를 특정 형식으로 구조화**하는 역할을 합니다. 즉, 메세지를 프롬프트로 변환하는 방법을 가르쳐주죠. ### 베이스 모델(Base Models) vs. 인스트럭트 모델(Instruct Models) [[base-models-vs-instruct-models]] 또다른 중요한 부분은 베이스 모델 vs 인스트럭트 모델의 차이점을 이해하는 것 입니다 : - *베이스 모델(Base Model)* 은 미가공 텍스트 데이터(raw data)로 학습해 다음 토큰을 예측합니다. - *인스트럭트 모델(Instruct Model)* 은 주어진 지시를 따라 대화할 수 있도록 추가로 미세 조정된 모델 예를 들어, `SmolLM2-135M`은 베이스 모델, `SmolLM2-135M-Instruct`은 인스트럭트 모델입니다. 베이스 모델을 인스트럭트 모델처럼 동작하게 하려면, **프롬프트 형식을 일관되게**맞춰야 합니다. 여기서 채팅 템플릿이 등장합니다. *ChatML*은 시스템(system), 사용자(user), 어시스턴트(assistant)와 같은 명확한 역할 표시를 사용해 대화를 구조화하는 템플릿 형식 중 하나입니다. 여러분이 최신 AI API를 사용해 본 경험이 있으시다면, 이것이 표준 방식이라는 것을 알 것입니다. 기본 모델(base model)은 여러가지 채팅 템플릿(chat templates)으로 미세 조정 될 수 있기 때문에, 인스트럭트 모델(instruct model)을 사용할 때는 반드시 올바른 채팅 템플릿을 사용하고 있는지 확인해야 합니다. ### 채팅 템플릿(Chat Templates) 이해하기 [[understanding-chat-templates]] 각 인스트럭트 모델 마다 다른 대화 형식과 특수 토큰을 사용하기 때문에, 각 모델에 맞는 프롬프트 형식으로 채팅 템플릿이 구현됩니다. `transformers` 라이브러리에서는 채팅 템플릿에 [Jinja2 코드](https://jinja.palletsprojects.com/en/stable/) 를 포함하고 있습니다. 이는 위의 예제와 같이 JSON 형태 메세지의 ChatML 목록을 시스템 레벨의 지시문(instruction) 텍스트로 나타내주는데, 이는 모델이 이해 할 수 있는 사용자 메세지-어시스턴트 응답 형태로 이루어져 있습니다. 이 구조는 모델이 대화 중 **일관성을 유지하고, 다양한 유형의 입력에 적절하게 응답**할 수 있게 합니다. 아래는 `SmolLM2-135M-Instruct`채팅 템플릿의 간소화 버전입니다: ```jinja2 {% for message in messages %} {% if loop.first and messages[0]['role'] != 'system' %} <|im_start|>system 네 이름은 SmolLM이고, Hugging Face로 훈련된 도움을 주는 AI 어시스턴트야. <|im_end|> {% endif %} <|im_start|>{{ message['role'] }} {{ message['content'] }}<|im_end|> {% endfor %} ``` 위 코드와 같이, 채팅 템플릿은 메세지 리스트의 형식을 정의합니다. 다음과 같은 메세지 목록이 주어진 경우: ```python messages = [ {"role": "system", "content": "너는 기술분야에 특화된 도움을 주는 어시스턴트야."}, {"role": "user", "content": "채팅 템플릿이 뭔지 설명해줄래?"}, {"role": "assistant", "content": "채팅 템플릿은 사용자와 AI모델 간의 대화를 구조화해주는 역할을 해..."}, {"role": "user", "content": "어떻게 사용하는지 알려줘"}, ] ``` 앞에서 정의한 채팅 템플릿은 다음과 같은 문자열을 생성합니다 : ```sh <|im_start|>system 너는 기술분야에 특화된 도움을 주는 어시스턴트야<|im_end|> <|im_start|>user 채팅 템플릿이 뭔지 설명해줄래?<|im_end|> <|im_start|>assistant 채팅 템플릿은 사용자와 AI모델 간의 대화를 구조화해주는 역할을 해...<|im_end|> <|im_start|>user 어떻게 사용하는지 알려줘<|im_end|> ``` `transformers`라이브러리는 토큰화 과정에서 채팅 템플릿을 처리합니다. `transformers`가 어떻게 채팅 템플릿을 사용하는 지 더 알고 싶으시다면 <a href="https://huggingface.co/docs/transformers/en/chat_templating#how-do-i-use-chat-templates" target="_blank">여기</a>를 참고하세요! 우리가 할 것은 메세지를 올바른 형식으로 구조화 해주는 것 뿐, 나머지 작업은 토크나이저가 처리합니다. 아래 Space를 통해 동일한 대화가 다양한 모델별 채팅 템플릿에 따라 어떻게 형식화 되는지 실습해 볼 수 있습니다: <iframe src="https://jofthomas-chat-template-viewer.hf.space" frameborder="0" width="850" height="450" ></iframe> ### 메세지를 프롬프트로 변환하기 [[messages-to-prompt]] LLM이 올바른 형식을 갖춘 대화를 수신하도록 하는 방법은, 모델의 토크나이저가 제공하는 `chat_template`를 사용하는 것입니다. ```python messages = [ {"role": "system", "content": "너는 다양한 도구에 접근 가능한 AI 어시스턴트야."}, {"role": "user", "content": "안녕!"}, {"role": "assistant", "content": "안녕, 내가 어떻게 도와주면 될까?"}, ] ``` 이 대화를 프롬프트로 변환하려면, 토크나이저를 불러와 `apply_chat_template`를 호출하면 됩니다: ```python from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-1.7B-Instruct") rendered_prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) ``` 이 함수가 리턴하는 `rendered_prompt` 은 선택한 모델에 대한 입력으로 바로 사용 가능합니다! > `apply_chat_template()`함수는 ChatML 형식의 메세지를 처리할 때 API의 백엔드에서 사용됩니다. 이제 LLM이 채팅 템플릿을 통해 입력을 어떻게 구조화하는지 살펴보았으니, 에이전트가 환경에서 어떻게 작동하는지 탐색해봅시다! 에이전트가 이를 수행하는 주요 방법 중 하나는 **도구(Tools)**를 사용하는 것 입니다. 도구는 AI모델의 기능을 단순 텍스트 생성 이상으로 확장할 수 있게 해줍니다. 이후 새로운 유닛에서 메세지에 대해 더 다룰 예정이지만, 지금 더 깊이 탐구하고 싶으시다면 다음 문서를 참고하세요: - <a href="https://huggingface.co/docs/transformers/main/en/chat_templating" target="_blank">Hugging Face 채팅 템플릿 가이드/a> - <a href="https://huggingface.co/docs/transformers" target="_blank">Transformers 문서</a>
agents-course/units/ko/unit1/messages-and-special-tokens.mdx/0
{ "file_path": "agents-course/units/ko/unit1/messages-and-special-tokens.mdx", "repo_id": "agents-course", "token_count": 9435 }
13
# (Необязательно) Discord 101 [[discord-101]] <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit0/discord-etiquette.jpg" alt="Этикет Discord" width="100%"/> Это руководство поможет вам начать работу с Discord, бесплатной чат-платформой, популярной в игровых и ML-сообществах. Присоединяйтесь к Discord-серверу сообщества Hugging Face, которое **состоит из более чем 100 000 участников**, нажав <a href="https://discord.gg/UrrTSsSyjb" target="_blank">здесь</a>. Это отличное место для общения с другими людьми! ## Курс Агенты в Discord-сообществе Hugging Face Начало работы в Discord может быть немного сложным, поэтому вот краткое руководство, которое поможет вам сориентироваться. На сервере Сообщества HF собралось активное сообщество с интересами в различных областях, предлагающее возможности для обучения через обсуждения статей, мероприятия и многое другое. После [регистрации](http://hf.co/join/discord) представьтесь в канале `#introduce-yourself`. Мы создали 4 канала для курса по Агентам: - `agents-course-announcements`: для получения **последней информации о курсе**. - `🎓-agents-course-general`: для **обсуждения общих вопросов и свободного общения**. - `agents-course-questions`: чтобы **задавать вопросы и помочь своим однокурсникам**. - `agents-course-showcase`: для **демонстрации своих лучших агентов** . Кроме того, вам могут пригодится: - `smolagents`: для **обсуждения и поддержки библиотеки**. ## Советы по эффективному использованию Discord ### Как присоединиться к серверу Если вы не очень хорошо знакомы с Discord, вам стоит заглянуть в это <a href="https://support.discord.com/hc/en-us/articles/360034842871-How-do-I-join-a-Server#h_01FSJF9GT2QJMS2PRAW36WNBS8" target="_blank">руководство</a>, чтобы узнать как присоединиться к серверу. Вот краткое описание шагов: 1. Нажмите на <a href="https://discord.gg/UrrTSsSyjb" target="_blank">cсылку-приглашение</a>. 2. Войдите в Discord, используя свою учетную запись, или создайте ее, если у вас ее еще нет. 3. Убедитесь, что вы не являетесь ИИ агентом! 4. Задайте свой псевдоним и аватар. 5. Нажмите "Присоединиться к серверу". ### Как эффективно использовать Discord Вот несколько советов по эффективному использованию Discord: - **Голосовые каналы** доступны, хотя чаще всего используется текстовый чат. - Вы можете форматировать текст в стиле **markdown**, что особенно удобно при написании кода. Обратите внимание, что стиль markdown не так хорошо работает со ссылками. - Для упорядочивания обсуждений следует открывать темы для организации **длинных разговоров**. Мы надеемся, что это руководство будет вам полезно! Если у вас возникнут вопросы, не стесняйтесь задавать их нам в Discord 🤗.
agents-course/units/ru-RU/unit0/discord101.mdx/0
{ "file_path": "agents-course/units/ru-RU/unit0/discord101.mdx", "repo_id": "agents-course", "token_count": 2376 }
14
# Что такое Инструменты? <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/whiteboard-check-2.jpg" alt="Раздел 1 планирование"/> Одним из важнейших аспектов AI Агентов является их способность предпринимать **действия**. Как мы видели, это происходит благодаря использованию **Инструментов**. В этом разделе мы узнаем, что такое Инструменты, как их эффективно разработать и как интегрировать их в вашего Агента с помощью Системного Сообщения. Предоставив своему агенту правильные инструменты и четко описав, как они работают, вы сможете значительно расширить возможности своего AI. Давайте погружаться! ## Что такое AI Инструменты? ** Инструмент - это функция, предоставленная LLM**. Эта функция должна выполнять **четкую цель**. Вот некоторые часто используемые в AI агентах инструменты: | Инструмент | Описание | |----------------|---------------------------------------------------------------| | Веб-поиск | Позволяет агенту получать актуальную информацию из Интернета. | | Генерация изображений | Создает изображения на основе текстовых описаний. | | Извлечение | Извлекает информацию из внешнего источника. | | | Интерфейс API | Взаимодействие с внешним API (GitHub, YouTube, Spotify и т. д.). | Это лишь примеры, поскольку на самом деле вы можете создать инструмент для любого случая использования! Хороший инструмент должен быть чем-то, что **дополняет возможности LLM**. Например, если вам нужно выполнить арифметические действия, то предоставление вашему LLM **калькулятора** обеспечит лучшие результаты, чем полагаться на собственные возможности модели. Кроме того, **LLM предсказывают завершение подсказки на основе своих обучающих данных**, что означает, что их внутренние знания включают только события, произошедшие до их обучения. Поэтому, если вашему агенту нужны свежие данные, вы должны предоставить их с помощью какого-либо инструмента. Например, если вы спросите у LLM напрямую (без инструмента поиска) о сегодняшней погоде, LLM потенциально может выдать случайную погоду в виде галлюцинаций. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/weather.jpg" alt="Погода"/> - Инструмент должен: - **иметь текстовое описание того, что делает функция**. - *быть Вызываемым (Callable)* (чем-то, что выполняет действие). - *иметь Аргументы* с типизацией. - (Необязательно) иметь Выходные данные с типизацией. ## Как работают инструменты? Как мы видели, **LLM могут только получать текстовые данные на вход и генерировать текстовые данные на выход. У них нет возможности самостоятельно вызывать инструменты. Когда мы говорим о _предоставлении инструментов агенту_, мы имеем в виду, что мы **обучаем** LLM существованию инструментов и просим модель генерировать текст, который будет вызывать инструменты, когда это необходимо. Например, если мы предоставим инструмент для проверки погоды в определенном месте из Интернета, а затем спросим LLM о погоде в Париже, LLM распознает этот вопрос как релевантную возможность использовать инструмент "weather", которой мы его научили. LLM сгенерирует _текст_ в виде кода, чтобы вызвать этот инструмент. Ответственность **Агента** заключается в том, чтобы проанализировать вывод LLM, распознать, что требуется вызов инструмента, и вызвать его от имени LLM. Выходные данные от инструмента будут отправлены обратно в LLM, которая составит окончательный ответ для пользователя. Выходные данные после вызова инструмента - это еще один тип сообщений в диалоге. Шаги вызова инструмента обычно не демонстрируются пользователю: агент извлекает диалог, вызывает инструмент(ы), получает выходные данные, добавляет их в новое сообщение диалога и снова отправляет обновленный диалог в LLM. С точки зрения пользователя это выглядит так, как будто LLM использовал инструмент, но на самом деле это сделал наш код приложения (**Агент**). Мы поговорим об этом процессе подробнее на следующих занятиях. ## Как мы даем инструменты LLM? Полный ответ может показаться непомерно сложным, но мы, по сути, используем системную подсказку для предоставления текстовых описаний доступных модели инструментов: <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/Agent_system_prompt.png" alt="Системная подсказка для использования инструментов"/> Чтобы это сработало, мы должны быть очень точны и аккуратны в отношении: 1. **Что делает инструмент**. 2. **Каких именно входных данных он ожидает**. Именно по этой причине описания инструментов обычно предоставляются с использованием выразительных, но точных структур, таких как компьютерные языки или JSON. Не обязательно делать это именно так, подойдет любой точный и последовательный формат. Если это кажется слишком теоретическим, давайте разберемся на конкретном примере. Мы реализуем упрощенный **калькулятор**, который будет просто перемножать два целых числа. Это может быть наша реализация на Python: ```python def calculator(a: int, b: int) -> int: """Multiply two integers.""" return a * b ``` Итак, наш инструмент называется `calculator`, он **перемножает два целых числа**, и ему требуются следующие входные данные: - **`a`** (*int*): Целое число. - **`b`** (*int*): Целое число. На выходе получается другое целое число, которое можно описать следующим образом: - (*int*): Произведение `a` и `b`. Все эти детали очень важны. Давайте соберем их вместе в текстовую строку, которая описывает наш инструмент для понимания LLM. ```text Tool Name: calculator, Description: Multiply two integers., Arguments: a: int, b: int, Outputs: int ``` > **Напоминание:** Это текстовое описание - *то, что мы хотим, чтобы LLM знала об инструменте*. Когда мы передадим предыдущую строку как часть входных данных в LLM, модель распознает ее как инструмент, и будет знать, что ему нужно передавать в качестве входных данных и что ожидать от выходных данных. Если мы хотим предоставить дополнительные инструменты, мы должны быть последовательными и всегда использовать один и тот же формат. Этот процесс может быть хрупким, и мы можем случайно упустить некоторые детали. Есть ли лучший способ? ### Автоформатирование секции Инструменты Наш инструмент написан на Python, и его реализация уже предоставляет все, что нам нужно: - Описательное название того, что он делает: `calculator`. - Более длинное описание, представленное в комментарии к docstring функции: `Multiply two integers.`. - Входные данные и их тип: функция явно ожидает два `int`. - Тип выходных данных. Люди не просто так используют языки программирования: они выразительны, кратки и точны. Мы могли бы предоставить исходный код Python в качестве _спецификации_ инструмента для LLM, но способ реализации инструмента не имеет значения. Важно лишь его название, то, что он делает, какие входные данные он ожидает и какие выходные данные он предоставляет. Мы воспользуемся возможностями интроспекции Python, чтобы изучить исходный код и автоматически составить описание инструмента. Все, что нам нужно, - это чтобы реализация инструмента использовала подсказки типов, строки документации и разумные имена функций. Мы напишем код для извлечения нужных фрагментов из исходного кода. После этого нам останется только использовать декоратор Python, чтобы указать, что функция `calculator` является инструментом: ```python @tool def calculator(a: int, b: int) -> int: """Multiply two integers.""" return a * b print(calculator.to_string()) ``` Обратите внимание на декоратор `@tool` перед определением функции. С помощью реализации, которую мы рассмотрим далее, мы сможем автоматически извлекать следующий текст из исходного кода с помощью функции `to_string()`, предоставляемой декоратором: ```text Tool Name: calculator, Description: Multiply two integers., Arguments: a: int, b: int, Outputs: int ``` Как видите, это то же самое, что мы уже писали вручную! ### Универсальная реализация Инструмента Мы создаем общий класс `Tool`, который мы можем использовать каждый раз, когда нам нужно использовать инструмент. > **Отказ от ответственности:** Этот пример реализации является вымышленным, но очень похож на реальные реализации в большинстве библиотек. ```python class Tool: """ Класс, представляющий многократно используемый фрагмент кода (инструмент). Атрибуты: name (str): Имя инструмента. description (str): Текстовое описание того, что делает инструмент. func (вызываемый): Функция, которую оборачивает этот инструмент. arguments (список): Список аргументов. outputs (str или list): Возвращаемые обернутой функцией типы. """ def __init__(self, name: str, description: str, func: callable, arguments: list, outputs: str): self.name = name self.description = description self.func = func self.arguments = arguments self.outputs = outputs def to_string(self) -> str: """ Возвращает строковое представление инструмента, включая его название, описание, аргументы и выходные данные. """ args_str = ", ".join([ f"{arg_name}: {arg_type}" for arg_name, arg_type in self.arguments ]) return ( f"Tool Name: {self.name}," f" Description: {self.description}," f" Arguments: {args_str}," f" Outputs: {self.outputs}" ) def __call__(self, *args, **kwargs): """ Вызов базовой функции (вызываемой) с указанными аргументами. """ return self.func(*args, **kwargs) ``` Это может показаться сложным, но если мы медленно пройдемся по нему, то сможем понять, что он делает. Мы определяем класс **`Tool`**, который включает в себя: - **`name`** (*str*): Название инструмента. - **`description`** (*str*): Краткое описание того, что делает инструмент. - **`function`** (*callable*): Функция, которую выполняет инструмент. - **`arguments`** (*list*): Ожидаемые входные параметры. - **`outputs`** (*str* или *list*): Ожидаемые выходные данные инструмента. - **`__call__()`**: Вызывает функцию при вызове экземпляра инструмента. - **`to_string()`**: Преобразует атрибуты инструмента в текстовое представление. Мы можем создать инструмент с помощью этого класса, используя следующий код: ```python calculator_tool = Tool( "calculator", # имя "Multiply two integers.", # описание calculator, # функция для вызова [("a", "int"), ("b", "int")], # водные данные (имена и типы) "int", # выходные данные ) ``` Но мы также можем использовать модуль Python `inspect`, чтобы получить всю информацию за нас! Вот что делает декоратор `@tool`. > Если вам интересно, вы можете посмотреть на реализацию декоратора в следующем разделе. <details> <summary> код декоратора</summary> ```python def tool(func): """ Декоратор, создающий экземпляр Tool из заданной функции. """ # Получение сигнатуры функции signature = inspect.signature(func) # Извлеките пары (param_name, param_annotation) для входных данных arguments = [] for param in signature.parameters.values(): annotation_name = ( param.annotation.__name__ if hasattr(param.annotation, '__name__') else str(param.annotation) ) arguments.append((param.name, annotation_name)) # Определите аннотацию возврата return_annotation = signature.return_annotation if return_annotation is inspect._empty: outputs = "No return annotation" else: outputs = ( return_annotation.__name__ if hasattr(return_annotation, '__name__') else str(return_annotation) ) # Используйте строку документации функции в качестве описания (по умолчанию, если None) description = func.__doc__ or "Описание не представлено." # Имя функции становится именем Инструмента name = func.__name__ # Возвращаем новый экземпляр Инструмента return Tool( name=name, description=description, func=func, arguments=arguments, outputs=outputs ) ``` </details> Повторимся, что с этим декоратором мы можем реализовать наш инструмент следующим образом: ```python @tool def calculator(a: int, b: int) -> int: """Multiply two integers.""" return a * b print(calculator.to_string()) ``` И мы можем использовать метод `Tool` `to_string` для автоматического получения текста, подходящего для использования в качестве описания инструмента для LLM: ```text Tool Name: calculator, Description: Multiply two integers., Arguments: a: int, b: int, Outputs: int ``` Описание **вставляется** в системную подсказку. Если взять пример, с которого мы начали этот раздел, то вот как он будет выглядеть после замены `tools_description`: <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/Agent_system_prompt_tools.png" alt="Системная подсказка для инструментов"/> В разделе [Действия](actions) мы узнаем, как агент может **вызвать** инструмент, который мы только что создали. --- Инструменты играют решающую роль в расширении возможностей AI агентов. Подводя итоги, мы узнали: - *Что такое инструменты*: Функции, которые предоставляют LLM дополнительные возможности, такие как выполнение вычислений или доступ к внешним данным. - *Как определить инструмент*: Предоставить четкое текстовое описание, входы, выходы и вызываемую функцию. - *Почему инструменты необходимы*: Они позволяют агентам преодолевать ограничения статического обучения модели, решать задачи в реальном времени и выполнять специализированные действия. Теперь мы можем перейти к [Рабочему процессу Агента](agent-steps-and-structure), где вы увидите, как Агент наблюдает, думает и действует. Это **собирает воедино все, что мы изучили до сих пор**, и закладывает основу для создания вашего собственного полнофункционального AI Агента. Но сначала - еще один короткий тест!
agents-course/units/ru-RU/unit1/tools.mdx/0
{ "file_path": "agents-course/units/ru-RU/unit1/tools.mdx", "repo_id": "agents-course", "token_count": 12534 }
15
# Kết luận [[conclusion]] Chúc mừng bạn đã hoàn thành chương đầu tiên 🥳 Bạn vừa **nắm vững kiến thức cơ bản về Agents** và đã tạo ra AI agent đầu tiên của mình! **Việc vẫn còn bối rối với một số khái niệm là hoàn toàn bình thường**. Agents là chủ đề phức tạp và cần thời gian để hiểu sâu mọi khía cạnh. **Hãy dành thời gian hiểu kỹ nội dung** trước khi tiếp tục. Việc nắm vững những kiến thức nền tảng này là cực kỳ quan trọng trước khi bước vào phần thú vị tiếp theo. Và nếu vượt qua bài Kiểm tra nhanh, đừng quên nhận chứng chỉ 🎓 👉 [tại đây](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="Ví dụ chứng chỉ"/> Trong chương (bổ trợ) tiếp theo, bạn sẽ học cách **tinh chỉnh một Agent để thực hiện function calling (gọi tools dựa trên prompt người dùng)**. Cuối cùng, chúng tôi rất muốn **lắng nghe phản hồi của bạn về khóa học và cách cải thiện**. Nếu có ý kiến đóng góp, hãy 👉 [điền form này](https://docs.google.com/forms/d/e/1FAIpQLSe9VaONn0eglax0uTwi29rIn4tM7H2sYmmybmG5jJNlE5v0xA/viewform?usp=dialog) ### Hãy tiếp tục học hỏi và luôn tuyệt vời nhé 🤗
agents-course/units/vi/unit1/conclusion.mdx/0
{ "file_path": "agents-course/units/vi/unit1/conclusion.mdx", "repo_id": "agents-course", "token_count": 933 }
16
- title: 第 0 单元. 课程欢迎 sections: - local: unit0/introduction title: 欢迎来到课程 🤗 - local: unit0/onboarding title: 入门指南 - local: unit0/discord101 title: (可选) Discord 使用指南 - title: 直播 1. 课程运作方式和问答 sections: - local: communication/live1 title: 直播 1. 课程运作方式和问答 - title: 第 1 单元. 智能体简介 sections: - local: unit1/introduction title: 简介 - local: unit1/what-are-agents title: 什么是智能体? - local: unit1/quiz1 title: 快速测验 1 - local: unit1/what-are-llms title: 什么是 LLMs? - local: unit1/messages-and-special-tokens title: 消息和特殊令牌 - local: unit1/tools title: 什么是工具? - local: unit1/quiz2 title: 快速测验 2 - local: unit1/agent-steps-and-structure title: 通过思考-行动-观察循环理解 AI 智能体 - local: unit1/thoughts title: 思考、内部推理和 Re-Act 方法 - local: unit1/actions title: 行动,使智能体能够与环境交互 - local: unit1/observations title: 观察,整合反馈以反思和适应 - local: unit1/dummy-agent-library title: 简单智能体库 - local: unit1/tutorial title: 使用 Smolagents 创建我们的第一个智能体 - local: unit1/final-quiz title: 第 1 单元最终测验 - local: unit1/conclusion title: 结论 - title: 第 2 单元. AI 智能体框架 sections: - local: unit2/introduction title: AI 智能体框架 - title: 第 2.1 单元. smolagents 框架 sections: - local: unit2/smolagents/introduction title: smolagents 简介 - local: unit2/smolagents/why_use_smolagents title: 为什么使用 smolagents? - local: unit2/smolagents/quiz1 title: 快速测验1 - local: unit2/smolagents/code_agents title: 构建使用代码的智能体 - local: unit2/smolagents/tool_calling_agents title: 将智能体与工具集成 - local: unit2/smolagents/tools title: 工具 - local: unit2/smolagents/retrieval_agents title: 检索智能体 - local: unit2/smolagents/quiz2 title: 快速测验2 - local: unit2/smolagents/multi_agent_systems title: 多智能体系统 - local: unit2/smolagents/vision_agents title: 视觉和浏览器智能体 - local: unit2/smolagents/final_quiz title: 最终测验 - local: unit2/smolagents/conclusion title: 结论 - title: 第 2.2 单元. LlamaIndex 框架 sections: - local: unit2/llama-index/introduction title: LlamaIndex 简介 - local: unit2/llama-index/llama-hub title: LlamaHub 简介 - local: unit2/llama-index/components title: LlamaIndex 中的组件是什么? - local: unit2/llama-index/tools title: 在 LlamaIndex 中使用工具 - local: unit2/llama-index/quiz1 title: 快速测验1 - local: unit2/llama-index/agents title: 在 LlamaIndex 中使用智能体 - local: unit2/llama-index/workflows title: 在 LlamaIndex 中创建智能工作流 - local: unit2/llama-index/quiz2 title: 快速测验2 - local: unit2/llama-index/conclusion title: 结论 - title: 第 2.3 单元. LangGraph 框架 sections: - local: unit2/langgraph/introduction title: LangGraph 是什么? - local: unit2/langgraph/when_to_use_langgraph title: 何时使用 LangGraph? - local: unit2/langgraph/building_blocks title: LangGraph 的构建模块 - local: unit2/langgraph/first_graph title: 创建你的第一个 LangGraph - local: unit2/langgraph/document_analysis_agent title: 文档分析智能体 - local: unit2/langgraph/quiz1 title: 快速测验1 - local: unit2/langgraph/conclusion title: 结论 - title: 第 3 单元. Agentic RAG 的用例 sections: - local: unit3/agentic-rag/introduction title: Agentic RAG 用例简介 - local: unit3/agentic-rag/agentic-rag title: Agentic 检索增强生成(RAG) - local: unit3/agentic-rag/invitees title: 为宾客故事创建 RAG 工具 - local: unit3/agentic-rag/tools title: 为你的智能体构建和集成工具 - local: unit3/agentic-rag/agent title: 创建你的 Gala 智能体 - local: unit3/agentic-rag/conclusion title: 结论 - title: 第 4 单元. 最终项目 - 创建,测试和认证你的智能体 sections: - local: unit4/introduction title: 欢迎来到最后一个单元 - local: unit4/what-is-gaia title: 什么是GAIA? - local: unit4/hands-on title: 动手实践 - local: unit4/get-your-certificate title: 领取你的证书 - local: unit4/conclusion title: 结论 - local: unit4/additional-readings title: 那现在呢?我应该学习哪些主题? - title: 附加单元 1. 为函数调用微调大型语言模型 sections: - local: bonus-unit1/introduction title: 简介 - local: bonus-unit1/what-is-function-calling title: 什么是函数调用? - local: bonus-unit1/fine-tuning title: 让我们为函数调用微调模型 - local: bonus-unit1/conclusion title: 结论 - title: 附加单元 2. 智能体可观察性和评估 sections: - local: bonus_unit2/introduction title: 简介 - local: bonus_unit2/what-is-agent-observability-and-evaluation title: 什么是智能体可观察性和评估? - local: bonus_unit2/monitoring-and-evaluating-agents-notebook title: 监控和评估智能体 - local: bonus_unit2/quiz title: 测验 - title: 后续内容何时发布? sections: - local: communication/next-units title: 后续单元
agents-course/units/zh-CN/_toctree.yml/0
{ "file_path": "agents-course/units/zh-CN/_toctree.yml", "repo_id": "agents-course", "token_count": 2886 }
17
# 通过思考-行动-观察循环理解 AI 智能体 (Understanding AI Agents through the Thought-Action-Observation Cycle) <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/whiteboard-check-3.jpg" alt="Unit 1 planning"/> 在前面的章节中,我们学习了: - **如何在系统提示中向智能体提供工具 (tools)**。 - **AI 智能体 (AI agents) 是如何能够"推理"、规划并与其环境交互的系统**。 在本节中,**我们将探索完整的 AI 智能体工作流程**,这是我们定义的思考-行动-观察 (Thought-Action-Observation) 循环。 然后,我们将深入探讨这些步骤中的每一个。 ## 核心组件 (Core Components) 智能体在一个持续的循环中工作:**思考 (Thought) → 行动 (Act) 和观察 (Observe)**。 让我们一起分解这些行动: 1. **思考 (Thought)**:智能体的大语言模型 (LLM) 部分决定下一步应该是什么。 2. **行动 (Action)**:智能体通过使用相关参数调用工具来采取行动。 3. **观察 (Observation)**:模型对工具的响应进行反思。 ## 思考-行动-观察循环 (The Thought-Action-Observation Cycle) 这三个组件在一个持续的循环中协同工作。用编程的类比来说,智能体使用一个 **while 循环**:循环持续进行,直到智能体的目标被实现。 视觉上,它看起来是这样的: <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/AgentCycle.gif" alt="Think, Act, Observe cycle"/> 在许多智能体框架中,**规则和指南直接嵌入到系统提示中**,确保每个循环都遵循定义的逻辑。 在一个简化版本中,我们的系统提示可能看起来像这样: <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/system_prompt_cycle.png" alt="Think, Act, Observe cycle"/> 我们在这里看到,在系统消息中我们定义了: - *智能体的行为*。 - *我们的智能体可以访问的工具*,就像我们在上一节中描述的那样。 - *思考-行动-观察循环*,我们将其融入到大语言模型指令中。 让我们看一个小例子,在深入研究每个步骤之前理解这个过程。 ## 阿尔弗雷德,天气智能体 (Alfred, the Weather Agent) 我们创建了阿尔弗雷德,天气智能体。 用户问阿尔弗雷德:"今天纽约的天气如何?" <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/alfred-agent.jpg" alt="Alfred Agent"/> 阿尔弗雷德的工作是使用天气 API 工具回答这个查询。 以下是循环的展开过程: ### 思考 (Thought) **内部推理:** 在收到查询后,阿尔弗雷德的内部对话可能是: *"用户需要纽约的当前天气信息。我可以访问一个获取天气数据的工具。首先,我需要调用天气API来获取最新的详细信息。"* 这一步显示了智能体将问题分解成步骤:首先,收集必要的数据。 <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/alfred-agent-1.jpg" alt="Alfred Agent"/> ### 行动 (Action) **工具使用:** 基于其推理和阿尔弗雷德知道有一个`get_weather`工具的事实,阿尔弗雷德准备一个 JSON 格式的命令来调用天气 API 工具。例如,它的第一个动作可能是: 思考:我需要检查纽约的当前天气。 ``` { "action": "get_weather", "action_input": { "location": "New York" } } ``` 在这里,动作清楚地指定了要调用哪个工具(如get_weather)和要传递的参数("location": "New York")。 <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/alfred-agent-2.jpg" alt="Alfred Agent"/> ### 观察 (Observation) **来自环境的反馈:** 在工具调用之后,阿尔弗雷德接收到一个观察结果。这可能是来自API的原始天气数据,如: *"纽约当前天气:多云,15°C,湿度60%。"* <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/alfred-agent-3.jpg" alt="Alfred Agent"/> 这个观察结果然后被添加到提示中作为额外的上下文。它作为现实世界的反馈,确认行动是否成功并提供所需的细节。 ### 更新的思考 (Updated thought) **反思:** 获得观察结果后,阿尔弗雷德更新其内部推理: *"现在我有了纽约的天气数据,我可以为用户编写答案了。"* <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/alfred-agent-4.jpg" alt="Alfred Agent"/> ### 最终行动 (Final Action) 然后阿尔弗雷德生成一个按照我们告诉它的方式格式化的最终响应: 思考:我现在有了天气数据。纽约当前天气多云,温度15°C,湿度60%。 最终答案:纽约当前天气多云,温度15°C,湿度60%。 这个最终行动将答案发送回用户,完成循环。 <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/alfred-agent-5.jpg" alt="Alfred Agent"/> 我们在这个例子中看到: - **智能体在目标实现之前不断迭代循环:** **阿尔弗雷德的过程是循环的**。它从思考开始,然后通过调用工具采取行动,最后观察结果。如果观察结果表明有错误或数据不完整,阿尔弗雷德可以重新进入循环来纠正其方法。 - **工具集成 (Tool Integration):** 调用工具(如天气 API)的能力使阿尔弗雷德能够**超越静态知识并检索实时数据**,这是许多 AI 智能体的重要方面。 - **动态适应 (Dynamic Adaptation):** 每个循环都允许智能体将新信息(观察)整合到其推理(思考)中,确保最终答案是明智和准确的。 这个例子展示了 *ReAct 循环*背后的核心概念(这是我们将在下一节中发展的概念):**思考、行动和观察的相互作用使 AI 智能体(AI Agent)能够迭代地解决复杂任务**。 通过理解和应用这些原则,你可以设计出不仅能够推理其任务,而且能够**有效利用外部工具来完成它们**的智能体,同时基于环境反馈不断改进其输出。 --- 现在让我们深入了解过程中的各个步骤:思考、行动、观察。
agents-course/units/zh-CN/unit1/agent-steps-and-structure.mdx/0
{ "file_path": "agents-course/units/zh-CN/unit1/agent-steps-and-structure.mdx", "repo_id": "agents-course", "token_count": 3984 }
18
# 结语 祝贺您完成了第二单元的 `LangGraph` 模块!🥳 您现在已经掌握了使用 LangGraph 构建结构化工作流的基础知识,这些工作流可以直接投入生产环境。 本模块只是您 LangGraph 学习之旅的起点。对于更深入的学习内容,我们推荐: - 探索 [LangGraph 官方文档](https://github.com/langchain-ai/langgraph) - 参加 LangChain Academy 的 [LangGraph 入门课程](https://academy.langchain.com/courses/intro-to-langgraph) - 亲自构建一些项目! 在下一个单元中,您将探索真实的应用场景。是时候将理论付诸实践了! 我们非常重视 **您对课程的想法和改进建议**。如果有任何反馈,请👉[填写此表单](https://docs.google.com/forms/d/e/1FAIpQLSe9VaONn0eglax0uTwi29rIn4tM7H2sYmmybmG5jJNlE5v0xA/viewform?usp=dialog) ### 持续学习,保持激情!🤗 尊敬的先生/女士!🎩🦇 -Alfred-
agents-course/units/zh-CN/unit2/langgraph/conclusion.mdx/0
{ "file_path": "agents-course/units/zh-CN/unit2/langgraph/conclusion.mdx", "repo_id": "agents-course", "token_count": 608 }
19
<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/unit2/smolagents/code_agents.ipynb"}, ]} /> # 构建使用代码的智能体 代码智能体(Code agents)是 `smolagents` 中的默认智能体类型。它们生成 Python 工具调用来执行操作,实现高效、表达力强且准确的操作表示。 它们的简化方法减少了所需操作的数量,简化了复杂操作,并实现了对现有代码函数的重用。`smolagents` 提供了一个轻量级框架,用约 1,000 行代码实现构建代码智能体(code agents)。 ![代码与 JSON 操作对比](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/code_vs_json_actions.png) 图片来自论文 [Executable Code Actions Elicit Better LLM Agents](https://huggingface.co/papers/2402.01030) <Tip> 如果你想了解更多关于为什么代码智能体如此有效的信息,请查看 <a href="https://huggingface.co/docs/smolagents/en/conceptual_guides/intro_agents#code-agents" target="_blank">smolagents 文档中的这个指南</a>。 </Tip> ## 为什么选择代码智能体? 在多步骤智能体过程中,大语言模型(LLM)编写并执行操作,通常涉及外部工具调用。传统方法使用 JSON 格式来指定工具名称和参数作为字符串,**系统必须解析这些内容以确定要执行哪个工具**。 然而,研究表明,**工具调用型大语言模型直接使用代码工作更有效**。这是 `smolagents` 的核心原则,如上图所示,来自论文 [Executable Code Actions Elicit Better LLM Agents](https://huggingface.co/papers/2402.01030)。 用代码而非 JSON 编写操作提供了几个关键优势: * **可组合性(Composability)**:轻松组合和重用操作 * **对象管理(Object Management)**:直接处理复杂结构,如图像 * **通用性(Generality)**:表达任何计算上可能的任务 * **适合大语言模型**:高质量代码已存在于大语言模型的训练数据中 ## 代码智能体如何工作? ![来自 https://huggingface.co/docs/smolagents/conceptual_guides/react](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/smolagents/codeagent_docs.png) 上图说明了 `CodeAgent.run()` 如何操作,遵循我们在第 1 单元中提到的 ReAct 框架。`smolagents` 中智能体的主要抽象是 `MultiStepAgent`,它作为核心构建块。如我们将在下面的示例中看到的,`CodeAgent` 是一种特殊的 `MultiStepAgent`。 `CodeAgent` 通过一系列步骤执行操作,将现有变量和知识整合到智能体的上下文中,这些内容保存在执行日志中: 1. 系统提示存储在 `SystemPromptStep` 中,用户查询记录在 `TaskStep` 中。 2. 然后,执行以下循环: 2.1 方法 `agent.write_memory_to_messages()` 将智能体的日志写入大语言模型可读的[聊天消息](https://huggingface.co/docs/transformers/en/chat_templating)列表中。 2.2 这些消息发送给 `Model`,生成补全(completion)。 2.3 解析补全内容以提取操作,在我们的例子中,这应该是代码片段,因为我们使用的是 `CodeAgent`。 2.4 执行该操作。 2.5 将结果记录到内存中的 `ActionStep` 中。 在每个步骤结束时,如果智能体包含任何函数调用(在 `agent.step_callback` 中),它们将被执行。 ## 让我们看一些例子 <Tip> 你可以在 <a href="https://huggingface.co/agents-course/notebooks/blob/main/unit2/smolagents/code_agents.ipynb" target="_blank">这个笔记本</a> 中跟随代码,可以使用 Google Colab 运行。 </Tip> 阿尔弗雷德(Alfred)正在韦恩家族大宅计划一场派对,需要你的帮助确保一切顺利进行。为了帮助他,我们将应用我们所学到的关于多步骤 `CodeAgent` 如何运作的知识。 <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/smolagents/alfred-party.jpg" alt="Alfred 派对"/> 如果你还没有安装 `smolagents`,可以运行以下命令进行安装: ```bash pip install smolagents -U ``` 让我们也登录到 Hugging Face Hub,以便访问无服务器推理 API(Serverless Inference API)。 ```python from huggingface_hub import login login() ``` ### 使用 `smolagents` 为派对选择播放列表 音乐是成功派对的重要组成部分!阿尔弗雷德需要一些帮助来选择播放列表。幸运的是,`smolagents` 能够帮助我们!我们可以构建一个能够使用 DuckDuckGo 搜索网络的智能体。要让智能体访问此工具,我们在创建智能体时将其包含在工具列表中。 <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/smolagents/alfred-playlist.jpg" alt="Alfred 播放列表"/> 对于模型,我们将依赖 `InferenceClientModel`,它提供对 Hugging Face 的[无服务器推理 API](https://huggingface.co/docs/api-inference/index)的访问。默认模型是 `"Qwen/Qwen2.5-Coder-32B-Instruct"`,它性能良好并可用于快速推理,但你可以从 Hub 中选择任何兼容的模型。 运行智能体相当简单: ```python from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel agent = CodeAgent(tools=[DuckDuckGoSearchTool()], model=InferenceClientModel()) agent.run("Search for the best music recommendations for a party at the Wayne's mansion.") ``` 当你运行这个例子时,输出将**显示正在执行的工作流步骤的跟踪**。它还会打印相应的 Python 代码,并附带消息: ```python ─ Executing parsed code: ──────────────────────────────────────────────────────────────────────────────────────── results = web_search(query="best music for a Batman party") print(results) ───────────────────────────────────────────────────────────────────────────────────────────────────────────────── ``` 几个步骤后,你将看到阿尔弗雷德可以用于派对的生成播放列表!🎵 ### 使用自定义工具准备菜单 <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/smolagents/alfred-menu.jpg" alt="Alfred 菜单"/> 现在我们已经选择了播放列表,我们需要为客人组织菜单。同样,阿尔弗雷德可以利用 `smolagents` 来做到这一点。在这里,我们使用 `@tool` 装饰器定义一个作为工具的自定义函数。我们稍后将更详细地介绍工具创建,所以现在我们可以简单地运行代码。 如下例所示,我们将使用 `@tool` 装饰器创建一个工具,并将其包含在 `tools` 列表中。 ```python from smolagents import CodeAgent, tool, InferenceClientModel # 根据场合建议菜单的工具 @tool def suggest_menu(occasion: str) -> str: """ Suggests a menu based on the occasion. Args: occasion: The type of occasion for the party. """ if occasion == "casual": return "Pizza, snacks, and drinks." elif occasion == "formal": return "3-course dinner with wine and dessert." elif occasion == "superhero": return "Buffet with high-energy and healthy food." else: return "Custom menu for the butler." # 管家阿尔弗雷德,为派对准备菜单 agent = CodeAgent(tools=[suggest_menu], model=InferenceClientModel()) # 为派对准备正式菜单 agent.run("Prepare a formal menu for the party.") ``` 智能体将运行几个步骤,直到找到答案。 菜单准备好了!🥗 ### 在智能体内部使用 Python 导入 我们已经准备好了播放列表和菜单,但我们需要检查另一个关键细节:准备时间! 阿尔弗雷德需要计算如果他现在开始准备,什么时候一切都会准备就绪,以防他们需要其他超级英雄的帮助。 `smolagents` 专门用于编写和执行 Python 代码片段的智能体,处于安全方面的考量,其提供沙盒执行环境。 **代码执行有严格的安全措施** - 默认情况下,预定义安全列表之外的导入被阻止。但是,您可以通过将它们作为字符串传递到 `additional_authorized_imports` 中来授权额外的导入。 有关安全代码执行的更多详情,请参阅官方[指南](https://huggingface.co/docs/smolagents/tutorials/secure_code_execution)。 创建智能体时,我们将使用 `additional_authorized_imports` 来允许导入 `datetime` 模块。 ```python from smolagents import CodeAgent, InferenceClientModel import numpy as np import time import datetime agent = CodeAgent(tools=[], model=InferenceClientModel(), additional_authorized_imports=['datetime']) agent.run( """ Alfred needs to prepare for the party. Here are the tasks: 1. Prepare the drinks - 30 minutes 2. Decorate the mansion - 60 minutes 3. Set up the menu - 45 minutes 3. Prepare the music and playlist - 45 minutes If we start right now, at what time will the party be ready? """ ) ``` 这些例子只是代码智能体能做的事情的开始,我们已经开始看到它们对准备派对的实用性。 你可以在 [smolagents 文档](https://huggingface.co/docs/smolagents) 中了解更多关于如何构建代码智能体的信息。 总之,`smolagents` 专注于编写和执行 Python 代码片段的智能体,提供安全的沙盒执行环境。它支持本地和基于 API 的语言模型,使其适应各种开发环境。 ### 将我们的自定义派对准备智能体分享到 Hub **将我们自己的阿尔弗雷德智能体与社区分享**难道不会很棒吗?通过这样做,任何人都可以轻松地从 Hub 下载并直接使用这个智能体,将哥谭市的终极派对策划者带到他们的指尖!让我们实现这个想法!🎉 `smolagents` 库使这成为可能,允许你与社区分享完整的智能体,并下载其他人的智能体立即使用。这很简单,如下所示: ```python # 更改为你的用户名和仓库名 agent.push_to_hub('sergiopaniego/AlfredAgent') ``` 要再次下载智能体,请使用以下代码: ```python # 更改为你的用户名和仓库名 alfred_agent = agent.from_hub('sergiopaniego/AlfredAgent') alfred_agent.run("Give me the best playlist for a party at Wayne's mansion. The party idea is a 'villain masquerade' theme") ``` 令人兴奋的是,共享的智能体直接作为 Hugging Face Spaces 提供,允许你实时与它们交互。你可以在[这里](https://huggingface.co/spaces/davidberenstein1957/smolagents-and-tools)探索其他智能体。 例如,_AlfredAgent_ 在[这里](https://huggingface.co/spaces/sergiopaniego/AlfredAgent)可用。你可以直接在下面尝试: <iframe src="https://sergiopaniego-alfredagent.hf.space/" frameborder="0" width="850" height="450" ></iframe> 你可能想知道——阿尔弗雷德如何使用 `smolagents` 构建这样一个智能体?通过整合几个工具,他可以生成一个如下的智能体。现在不用担心这些工具,因为我们将在本单元后面有专门的部分详细探讨: ```python from smolagents import CodeAgent, DuckDuckGoSearchTool, FinalAnswerTool, InferenceClientModel, Tool, tool, VisitWebpageTool @tool def suggest_menu(occasion: str) -> str: """ Suggests a menu based on the occasion. Args: occasion: The type of occasion for the party. """ if occasion == "casual": return "Pizza, snacks, and drinks." elif occasion == "formal": return "3-course dinner with wine and dessert." elif occasion == "superhero": return "Buffet with high-energy and healthy food." else: return "Custom menu for the butler." @tool def catering_service_tool(query: str) -> str: """ This tool returns the highest-rated catering service in Gotham City. Args: query: A search term for finding catering services. """ # 餐饮服务及其评分的示例列表 services = { "Gotham Catering Co.": 4.9, "Wayne Manor Catering": 4.8, "Gotham City Events": 4.7, } # 找到评分最高的餐饮服务(模拟搜索查询过滤) best_service = max(services, key=services.get) return best_service class SuperheroPartyThemeTool(Tool): name = "superhero_party_theme_generator" description = """ This tool suggests creative superhero-themed party ideas based on a category. It returns a unique party theme idea.""" inputs = { "category": { "type": "string", "description": "The type of superhero party (e.g., 'classic heroes', 'villain masquerade', 'futuristic Gotham').", } } output_type = "string" def forward(self, category: str): themes = { "classic heroes": "Justice League Gala: Guests come dressed as their favorite DC heroes with themed cocktails like 'The Kryptonite Punch'.", "villain masquerade": "Gotham Rogues' Ball: A mysterious masquerade where guests dress as classic Batman villains.", "futuristic Gotham": "Neo-Gotham Night: A cyberpunk-style party inspired by Batman Beyond, with neon decorations and futuristic gadgets." } return themes.get(category.lower(), "Themed party idea not found. Try 'classic heroes', 'villain masquerade', or 'futuristic Gotham'.") # 管家阿尔弗雷德,为派对准备菜单 agent = CodeAgent( tools=[ DuckDuckGoSearchTool(), VisitWebpageTool(), suggest_menu, catering_service_tool, SuperheroPartyThemeTool() ], model=InferenceClientModel(), max_steps=10, verbosity_level=2 ) agent.run("Give me best playlist for a party at the Wayne's mansion. The party idea is a 'villain masquerade' theme") ``` 如你所见,我们创建了一个具有多种工具的 `CodeAgent`,这些工具增强了智能体的功能,将其变成了准备好与社区分享的终极派对策划者!🎉 现在,轮到你了:使用我们刚刚学到的知识,构建你自己的智能体并与社区分享!🕵️‍♂️💡 <Tip> 如果你想分享你的智能体项目,请创建一个 space 并在 Hugging Face Hub 上标记 [agents-course](https://huggingface.co/agents-course)。我们很想看看你创造了什么! </Tip> ### 使用 OpenTelemetry 和 Langfuse 检查我们的派对准备智能体 📡 随着阿尔弗雷德对派对准备智能体的微调,他对调试其运行越来越疲惫。智能体本质上是不可预测的,难以检查。但由于他的目标是构建终极派对准备智能体并将其部署到生产环境中,他需要强大的可追踪性,用于未来的监控和分析。 再一次,`smolagents` 来救援!它采用 [OpenTelemetry](https://opentelemetry.io/) 标准来检测智能体运行,允许无缝检查和日志记录。在 [Langfuse](https://langfuse.com/) 和 `SmolagentsInstrumentor` 的帮助下,阿尔弗雷德可以轻松跟踪和分析他的智能体行为。 设置非常简单! 首先,我们需要安装必要的依赖项: ```bash pip install opentelemetry-sdk opentelemetry-exporter-otlp openinference-instrumentation-smolagents langfuse ``` 接下来,阿尔弗雷德已经在 Langfuse 上创建了一个账户,并准备好了他的 API 密钥。如果你还没有这样做,你可以在[这里](https://cloud.langfuse.com/)注册 Langfuse Cloud 或探索[替代方案](https://huggingface.co/docs/smolagents/tutorials/inspect_runs)。 一旦你有了 API 密钥,它们需要正确配置如下: ```python import os # Get keys for your project from the project settings page: https://cloud.langfuse.com os.environ["LANGFUSE_PUBLIC_KEY"] = "pk-lf-..." os.environ["LANGFUSE_SECRET_KEY"] = "sk-lf-..." os.environ["LANGFUSE_HOST"] = "https://cloud.langfuse.com" # 🇪🇺 EU region # os.environ["LANGFUSE_HOST"] = "https://us.cloud.langfuse.com" # 🇺🇸 US region ``` With the environment variables set, we can now initialize the Langfuse client. get_client() initializes the Langfuse client using the credentials provided in the environment variables. ```python from langfuse import get_client langfuse = get_client() # Verify connection if langfuse.auth_check(): print("Langfuse client is authenticated and ready!") else: print("Authentication failed. Please check your credentials and host.") ``` 最后,阿尔弗雷德准备初始化 `SmolagentsInstrumentor` 并开始跟踪他的智能体性能。 ```python from openinference.instrumentation.smolagents import SmolagentsInstrumentor SmolagentsInstrumentor().instrument() ``` 阿尔弗雷德现在已连接 🔌!来自 `smolagents` 的运行正在 Langfuse 中记录,让他完全可见智能体的行为。有了这个设置,他准备重新访问之前的运行并进一步改进他的派对准备智能体。 ```python from smolagents import CodeAgent, InferenceClientModel agent = CodeAgent(tools=[], model=InferenceClientModel()) alfred_agent = agent.from_hub('sergiopaniego/AlfredAgent', trust_remote_code=True) alfred_agent.run("Give me the best playlist for a party at Wayne's mansion. The party idea is a 'villain masquerade' theme") ``` 阿尔弗雷德现在可以在[这里](https://cloud.langfuse.com/project/cm7bq0abj025rad078ak3luwi/traces/995fc019255528e4f48cf6770b0ce27b?timestamp=2025-02-19T10%3A28%3A36.929Z)访问这些日志来审查和分析它们。 同时,[建议的播放列表](https://open.spotify.com/playlist/0gZMMHjuxMrrybQ7wTMTpw)为派对准备设置了完美的氛围。很酷,对吧?🎶 --- 现在我们已经创建了我们的第一个代码智能体,让我们**学习如何创建工具调用智能体(Tool Calling Agents)**,这是 `smolagents` 中可用的第二种智能体类型。 ## 资源 - [smolagents 博客](https://huggingface.co/blog/smolagents) - smolagents 和代码交互介绍 - [smolagents:构建好的智能体](https://huggingface.co/docs/smolagents/tutorials/building_good_agents) - 可靠智能体的最佳实践 - [构建有效的智能体 - Anthropic](https://www.anthropic.com/research/building-effective-agents) - 智能体设计原则 - [使用 OpenTelemetry 共享运行](https://huggingface.co/docs/smolagents/tutorials/inspect_runs) - 关于如何为跟踪你的智能体设置 OpenTelemetry 的详细信息
agents-course/units/zh-CN/unit2/smolagents/code_agents.mdx/0
{ "file_path": "agents-course/units/zh-CN/unit2/smolagents/code_agents.mdx", "repo_id": "agents-course", "token_count": 9957 }
20
# 代理增强检索生成(Agentic RAG)用例介绍 ![代理增强 RAG 横幅图](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit3/agentic-rag/thumbnail.jpg) 在本单元中,我们将通过代理增强检索生成(Agentic RAG)技术,帮助负责主持晚会的友好智能体 Alfred 创建用于解答宾客问题的工具。 <Tip> 这是代理增强 RAG 的「真实世界」应用案例,您可直接应用于个人项目或工作场景。若想获得更多实践收获,何不尝试将其应用于您的实际场景并在 Discord 社区分享? </Tip> 您可以选择课程中讨论的任何框架来实现本用例。我们已在独立标签页中为每个框架提供代码示例。 ## 值得铭记的盛会 现在让我们进入实战环节,为这场盛会搭建舞台! **您决定举办本世纪最奢华、最盛大的派对**——这意味着将包含:豪华宴席、魅惑舞者、知名 DJ、精致饮品、震撼烟花表演等极致元素。 您的好邻居智能体 Alfred 正着手统筹派对的各项需求,**Alfred 将全权管理所有事务**。为此,他需要掌握包括菜单、宾客名单、日程安排、天气预报等在内的完整派对信息! 除此之外,他还需确保派对圆满成功,因此**必须具备在派对期间实时解答各类问题的能力**,同时处理可能出现的突发状况。 Alfred 无法孤军奋战,我们需要确保他能够获取所需的所有信息和工具。 首先,让我们为晚会制定核心需求清单。 ## 晚会核心需求 在**文艺复兴时期**,真正受过良好教育的人需具备三大核心素养: 需精通**体育、文化与科学知识**。因此,我们必须通过知识储备给宾客留下深刻印象,呈现真正难忘的盛会。 但为避免冲突,**政治与宗教等敏感话题应在晚会中回避**,确保派对氛围轻松愉快,不涉及信仰与理念分歧。 根据礼仪规范,**优秀的主办方应充分了解宾客背景**,包括其兴趣爱好与事业成就。同时应善于通过宾客间的故事分享促进交流。 最后,我们还需掌握**基础天气知识**,以便实时获取更新信息,精准把握烟花表演时机,为晚会画上完美句号!🎆 由此可见,Alfred 需要大量信息支持才能办好晚会。 幸运的是,我们可以通过**检索增强生成(RAG)训练**为 Alfred 做好准备! 现在让我们开始创建 Alfred 主持晚会所需的工具集!
agents-course/units/zh-CN/unit3/agentic-rag/introduction.mdx/0
{ "file_path": "agents-course/units/zh-CN/unit3/agentic-rag/introduction.mdx", "repo_id": "agents-course", "token_count": 1794 }
21
# Changelog This documents the main changes to the `candle` crate. ## v0.3.1 - Unreleased ### Added ### Modified ## v0.3.0 - 2023-10-01 ### Added - Added the Mistral 7b v0.1 model [983](https://github.com/huggingface/candle/pull/983). - Quantized version of the Mistral model [1009](https://github.com/huggingface/candle/pull/1009). - Add the gelu-erf op and activation function [969](https://github.com/huggingface/candle/pull/969). - Add the mixformer/phi-v1.5 model [930](https://github.com/huggingface/candle/pull/930). - Add the sclice-scatter op [927](https://github.com/huggingface/candle/pull/927). - Add the Wuerstchen diffusion model [911](https://github.com/huggingface/candle/pull/911). ### Modified - Support for simd128 intrinsics in some quantized vecdots [982](https://github.com/huggingface/candle/pull/982). - Optimize the index-select cuda kernel [976](https://github.com/huggingface/candle/pull/976). - Self-contained safetensor wrappers [946](https://github.com/huggingface/candle/pull/946). ## v0.2.2 - 2023-09-18 ### Added - Support for `top_p` sampling [819](https://github.com/huggingface/candle/pull/819). - T5 model including decoding [864](https://github.com/huggingface/candle/pull/864). - 1-d upsampling [839](https://github.com/huggingface/candle/pull/839). ### Modified - Bugfix for conv2d [820](https://github.com/huggingface/candle/pull/820). - Support tensor based indexing using `.i` [842](https://github.com/huggingface/candle/pull/842). ## v0.2.1 - 2023-09-11 ### Added - Add some RNNs (GRU and LSTM) in `candle-nn` [674](https://github.com/huggingface/candle/pull/674), [688](https://github.com/huggingface/candle/pull/688). - gguf v2 support [725](https://github.com/huggingface/candle/pull/725). - Quantized llama example in Python using the pyo3 api [716](https://github.com/huggingface/candle/pull/716). - `candle-nn` layer for conv2d-transposed [760](https://github.com/huggingface/candle/pull/760). - Add the Segment-Anything Model (SAM) as an example [773](https://github.com/huggingface/candle/pull/773). - TinyViT backbone for the segment anything example [787](https://github.com/huggingface/candle/pull/787). - Shape with holes support [770](https://github.com/huggingface/candle/pull/770). ### Modified - Dilations are now supported in conv-transpose2d. [671](https://github.com/huggingface/candle/pull/671). - Interactive mode for the quantized model [690](https://github.com/huggingface/candle/pull/690). - Faster softmax operation [747](https://github.com/huggingface/candle/pull/747). - Faster convolution operations on CPU and CUDA via im2col [802](https://github.com/huggingface/candle/pull/802). - Moving some models to a more central location [796](https://github.com/huggingface/candle/pull/796). ## v0.2.0 - 2023-08-30 ### Added - Add the powf op [664](https://github.com/huggingface/candle/pull/664). - Stable Diffusion XL support [647](https://github.com/huggingface/candle/pull/647). - Add the conv-transpose2d op [635](https://github.com/huggingface/candle/pull/635). - Refactor the VarBuilder api [627](https://github.com/huggingface/candle/pull/627). - Add some quantization command [625](https://github.com/huggingface/candle/pull/625). - Support more quantized types, e.g. Q2K, Q4K, Q5K... [586](https://github.com/huggingface/candle/pull/586). - Add pose estimation to the yolo example [589](https://github.com/huggingface/candle/pull/589). - Api to write GGUF files [585](https://github.com/huggingface/candle/pull/585). - Support more quantization types [580](https://github.com/huggingface/candle/pull/580). - Add EfficientNet as an example Computer Vision model [572](https://github.com/huggingface/candle/pull/572). - Add a group parameter to convolutions [566](https://github.com/huggingface/candle/pull/566). - New dtype: int64 [563](https://github.com/huggingface/candle/pull/563). - Handling of the GGUF file format. [559](https://github.com/huggingface/candle/pull/559). ## v0.1.2 - 2023-08-21
candle/CHANGELOG.md/0
{ "file_path": "candle/CHANGELOG.md", "repo_id": "candle", "token_count": 1525 }
22
# Creating a WASM app
candle/candle-book/src/apps/wasm.md/0
{ "file_path": "candle/candle-book/src/apps/wasm.md", "repo_id": "candle", "token_count": 7 }
23
# Using the hub Install the [`hf-hub`](https://github.com/huggingface/hf-hub) crate: ```bash cargo add hf-hub ``` Then let's start by downloading the [model file](https://huggingface.co/bert-base-uncased/tree/main). ```rust # extern crate candle_core; # extern crate hf_hub; use hf_hub::api::sync::Api; use candle_core::Device; let api = Api::new().unwrap(); let repo = api.model("bert-base-uncased".to_string()); let weights = repo.get("model.safetensors").unwrap(); let weights = candle_core::safetensors::load(weights, &Device::Cpu); ``` We now have access to all the [tensors](https://huggingface.co/bert-base-uncased?show_tensors=true) within the file. You can check all the names of the tensors [here](https://huggingface.co/bert-base-uncased?show_tensors=true) ## Using async `hf-hub` comes with an async API. ```bash cargo add hf-hub --features tokio ``` ```rust,ignore # This is tested directly in examples crate because it needs external dependencies unfortunately: # See [this](https://github.com/rust-lang/mdBook/issues/706) {{#include ../lib.rs:book_hub_1}} ``` ## Using in a real model. Now that we have our weights, we can use them in our bert architecture: ```rust # extern crate candle_core; # extern crate candle_nn; # extern crate hf_hub; # use hf_hub::api::sync::Api; # # let api = Api::new().unwrap(); # let repo = api.model("bert-base-uncased".to_string()); # # let weights = repo.get("model.safetensors").unwrap(); use candle_core::{Device, Tensor, DType}; use candle_nn::{Linear, Module}; let weights = candle_core::safetensors::load(weights, &Device::Cpu).unwrap(); let weight = weights.get("bert.encoder.layer.0.attention.self.query.weight").unwrap(); let bias = weights.get("bert.encoder.layer.0.attention.self.query.bias").unwrap(); let linear = Linear::new(weight.clone(), Some(bias.clone())); let input_ids = Tensor::zeros((3, 768), DType::F32, &Device::Cpu).unwrap(); let output = linear.forward(&input_ids).unwrap(); ``` For a full reference, you can check out the full [bert](https://github.com/LaurentMazare/candle/tree/main/candle-examples/examples/bert) example. ## Memory mapping For more efficient loading, instead of reading the file, you could use [`memmap2`](https://docs.rs/memmap2/latest/memmap2/) **Note**: Be careful about memory mapping it seems to cause issues on [Windows, WSL](https://github.com/AUTOMATIC1111/stable-diffusion-webui/issues/5893) and will definitely be slower on network mounted disk, because it will issue more read calls. ```rust,ignore {{#include ../lib.rs:book_hub_2}} ``` **Note**: This operation is **unsafe**. [See the safety notice](https://docs.rs/memmap2/latest/memmap2/struct.Mmap.html#safety). In practice model files should never be modified, and the mmaps should be mostly READONLY anyway, so the caveat most likely does not apply, but always keep it in mind. ## Tensor Parallel Sharding When using multiple GPUs to use in Tensor Parallel in order to get good latency, you can load only the part of the Tensor you need. For that you need to use [`safetensors`](https://crates.io/crates/safetensors) directly. ```bash cargo add safetensors ``` ```rust,ignore {{#include ../lib.rs:book_hub_3}} ```
candle/candle-book/src/inference/hub.md/0
{ "file_path": "candle/candle-book/src/inference/hub.md", "repo_id": "candle", "token_count": 1098 }
24
use crate::benchmarks::{BenchDevice, BenchDeviceHandler}; use candle_core::{Device, Tensor, WithDType}; use criterion::{black_box, criterion_group, Criterion, Throughput}; use std::time::Instant; fn run_copy_mask_benchmark<D: WithDType>(c: &mut Criterion, device: &Device, name: &str) { let batch_size = 128; let in_seq_len = 1; let kv_seq_len = 1024; let attn_mask = vec![vec![vec![D::zero(); kv_seq_len]; in_seq_len]; batch_size]; let size_in_bytes = batch_size * in_seq_len * kv_seq_len * D::DTYPE.size_in_bytes(); let mut group = c.benchmark_group(device.bench_name(name)); group.throughput(Throughput::Bytes(size_in_bytes as u64)); group.bench_function("iter", move |b| { b.iter_custom(|iters| { let attn_masks = vec![attn_mask.clone(); iters as usize]; let start = Instant::now(); for attn_mask in attn_masks.into_iter() { let tensor = Tensor::new(black_box(attn_mask), device).unwrap(); 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_copy_mask_benchmark::<f32>(c, &device, "copy_mask"); } } criterion_group!(benches, criterion_benchmark);
candle/candle-core/benches/benchmarks/copy.rs/0
{ "file_path": "candle/candle-core/benches/benchmarks/copy.rs", "repo_id": "candle", "token_count": 609 }
25
//! Implement conversion traits for tensors use crate::{DType, Device, Error, Tensor, WithDType}; use float8::F8E4M3; use half::{bf16, f16, slice::HalfFloatSliceExt}; use std::convert::TryFrom; impl<T: WithDType> TryFrom<&Tensor> for Vec<T> { type Error = Error; fn try_from(tensor: &Tensor) -> Result<Self, Self::Error> { tensor.to_vec1::<T>() } } impl<T: WithDType> TryFrom<&Tensor> for Vec<Vec<T>> { type Error = Error; fn try_from(tensor: &Tensor) -> Result<Self, Self::Error> { tensor.to_vec2::<T>() } } impl<T: WithDType> TryFrom<&Tensor> for Vec<Vec<Vec<T>>> { type Error = Error; fn try_from(tensor: &Tensor) -> Result<Self, Self::Error> { tensor.to_vec3::<T>() } } impl<T: WithDType> TryFrom<Tensor> for Vec<T> { type Error = Error; fn try_from(tensor: Tensor) -> Result<Self, Self::Error> { Vec::<T>::try_from(&tensor) } } impl<T: WithDType> TryFrom<Tensor> for Vec<Vec<T>> { type Error = Error; fn try_from(tensor: Tensor) -> Result<Self, Self::Error> { Vec::<Vec<T>>::try_from(&tensor) } } impl<T: WithDType> TryFrom<Tensor> for Vec<Vec<Vec<T>>> { type Error = Error; fn try_from(tensor: Tensor) -> Result<Self, Self::Error> { Vec::<Vec<Vec<T>>>::try_from(&tensor) } } impl<T: WithDType> TryFrom<&[T]> for Tensor { type Error = Error; fn try_from(v: &[T]) -> Result<Self, Self::Error> { Tensor::from_slice(v, v.len(), &Device::Cpu) } } impl<T: WithDType> TryFrom<Vec<T>> for Tensor { type Error = Error; fn try_from(v: Vec<T>) -> Result<Self, Self::Error> { let len = v.len(); Tensor::from_vec(v, len, &Device::Cpu) } } macro_rules! from_tensor { ($typ:ident) => { impl TryFrom<&Tensor> for $typ { type Error = Error; fn try_from(tensor: &Tensor) -> Result<Self, Self::Error> { tensor.to_scalar::<$typ>() } } impl TryFrom<Tensor> for $typ { type Error = Error; fn try_from(tensor: Tensor) -> Result<Self, Self::Error> { $typ::try_from(&tensor) } } impl TryFrom<$typ> for Tensor { type Error = Error; fn try_from(v: $typ) -> Result<Self, Self::Error> { Tensor::new(v, &Device::Cpu) } } }; } from_tensor!(f64); from_tensor!(f32); from_tensor!(f16); from_tensor!(bf16); from_tensor!(i64); from_tensor!(u32); from_tensor!(u8); impl Tensor { pub fn write_bytes<W: std::io::Write>(&self, f: &mut W) -> crate::Result<()> { use byteorder::{LittleEndian, WriteBytesExt}; let vs = self.flatten_all()?; match self.dtype() { DType::BF16 => { let vs = vs.to_vec1::<bf16>()?; for &v in vs.reinterpret_cast() { f.write_u16::<LittleEndian>(v)? } } DType::F16 => { let vs = vs.to_vec1::<f16>()?; for &v in vs.reinterpret_cast() { f.write_u16::<LittleEndian>(v)? } } DType::F32 => { // TODO: Avoid using a buffer when data is already on the CPU. for v in vs.to_vec1::<f32>()? { f.write_f32::<LittleEndian>(v)? } } DType::F64 => { for v in vs.to_vec1::<f64>()? { f.write_f64::<LittleEndian>(v)? } } DType::U32 => { for v in vs.to_vec1::<u32>()? { f.write_u32::<LittleEndian>(v)? } } DType::I64 => { for v in vs.to_vec1::<i64>()? { f.write_i64::<LittleEndian>(v)? } } DType::U8 => { let vs = vs.to_vec1::<u8>()?; f.write_all(&vs)?; } DType::F8E4M3 => { for v in vs.to_vec1::<F8E4M3>()? { f.write_u8(v.to_bits())? } } } Ok(()) } }
candle/candle-core/src/convert.rs/0
{ "file_path": "candle/candle-core/src/convert.rs", "repo_id": "candle", "token_count": 2378 }
26
//! Pretty printing of tensors //! //! This implementation should be in line with the [PyTorch version](https://github.com/pytorch/pytorch/blob/7b419e8513a024e172eae767e24ec1b849976b13/torch/_tensor_str.py). //! use crate::{DType, Result, Tensor, WithDType}; use float8::F8E4M3; use half::{bf16, f16}; impl Tensor { fn fmt_dt<T: WithDType + std::fmt::Display>( &self, f: &mut std::fmt::Formatter, ) -> std::fmt::Result { let device_str = match self.device().location() { crate::DeviceLocation::Cpu => "".to_owned(), crate::DeviceLocation::Cuda { gpu_id } => { format!(", cuda:{gpu_id}") } crate::DeviceLocation::Metal { gpu_id } => { format!(", metal:{gpu_id}") } }; write!(f, "Tensor[")?; match self.dims() { [] => { if let Ok(v) = self.to_scalar::<T>() { write!(f, "{v}")? } } [s] if *s < 10 => { if let Ok(vs) = self.to_vec1::<T>() { for (i, v) in vs.iter().enumerate() { if i > 0 { write!(f, ", ")?; } write!(f, "{v}")?; } } } dims => { write!(f, "dims ")?; for (i, d) in dims.iter().enumerate() { if i > 0 { write!(f, ", ")?; } write!(f, "{d}")?; } } } write!(f, "; {}{}]", self.dtype().as_str(), device_str) } } impl std::fmt::Debug for Tensor { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { match self.dtype() { DType::U8 => self.fmt_dt::<u8>(f), DType::U32 => self.fmt_dt::<u32>(f), DType::I64 => self.fmt_dt::<i64>(f), DType::BF16 => self.fmt_dt::<bf16>(f), DType::F16 => self.fmt_dt::<f16>(f), DType::F32 => self.fmt_dt::<f32>(f), DType::F64 => self.fmt_dt::<f64>(f), DType::F8E4M3 => self.fmt_dt::<F8E4M3>(f), } } } /// Options for Tensor pretty printing #[derive(Debug, Clone)] pub struct PrinterOptions { pub precision: usize, pub threshold: usize, pub edge_items: usize, pub line_width: usize, pub sci_mode: Option<bool>, } static PRINT_OPTS: std::sync::Mutex<PrinterOptions> = std::sync::Mutex::new(PrinterOptions::const_default()); impl PrinterOptions { // We cannot use the default trait as it's not const. const fn const_default() -> Self { Self { precision: 4, threshold: 1000, edge_items: 3, line_width: 80, sci_mode: None, } } } pub fn print_options() -> &'static std::sync::Mutex<PrinterOptions> { &PRINT_OPTS } pub fn set_print_options(options: PrinterOptions) { *PRINT_OPTS.lock().unwrap() = options } pub fn set_print_options_default() { *PRINT_OPTS.lock().unwrap() = PrinterOptions::const_default() } pub fn set_print_options_short() { *PRINT_OPTS.lock().unwrap() = PrinterOptions { precision: 2, threshold: 1000, edge_items: 2, line_width: 80, sci_mode: None, } } pub fn set_print_options_full() { *PRINT_OPTS.lock().unwrap() = PrinterOptions { precision: 4, threshold: usize::MAX, edge_items: 3, line_width: 80, sci_mode: None, } } pub fn set_line_width(line_width: usize) { PRINT_OPTS.lock().unwrap().line_width = line_width } pub fn set_precision(precision: usize) { PRINT_OPTS.lock().unwrap().precision = precision } pub fn set_edge_items(edge_items: usize) { PRINT_OPTS.lock().unwrap().edge_items = edge_items } pub fn set_threshold(threshold: usize) { PRINT_OPTS.lock().unwrap().threshold = threshold } pub fn set_sci_mode(sci_mode: Option<bool>) { PRINT_OPTS.lock().unwrap().sci_mode = sci_mode } struct FmtSize { current_size: usize, } impl FmtSize { fn new() -> Self { Self { current_size: 0 } } fn final_size(self) -> usize { self.current_size } } impl std::fmt::Write for FmtSize { fn write_str(&mut self, s: &str) -> std::fmt::Result { self.current_size += s.len(); Ok(()) } } trait TensorFormatter { type Elem: WithDType; fn fmt<T: std::fmt::Write>(&self, v: Self::Elem, max_w: usize, f: &mut T) -> std::fmt::Result; fn max_width(&self, to_display: &Tensor) -> usize { let mut max_width = 1; if let Ok(vs) = to_display.flatten_all().and_then(|t| t.to_vec1()) { for &v in vs.iter() { let mut fmt_size = FmtSize::new(); let _res = self.fmt(v, 1, &mut fmt_size); max_width = usize::max(max_width, fmt_size.final_size()) } } max_width } fn write_newline_indent(i: usize, f: &mut std::fmt::Formatter) -> std::fmt::Result { writeln!(f)?; for _ in 0..i { write!(f, " ")? } Ok(()) } fn fmt_tensor( &self, t: &Tensor, indent: usize, max_w: usize, summarize: bool, po: &PrinterOptions, f: &mut std::fmt::Formatter, ) -> std::fmt::Result { let dims = t.dims(); let edge_items = po.edge_items; write!(f, "[")?; match dims { [] => { if let Ok(v) = t.to_scalar::<Self::Elem>() { self.fmt(v, max_w, f)? } } [v] if summarize && *v > 2 * edge_items => { if let Ok(vs) = t .narrow(0, 0, edge_items) .and_then(|t| t.to_vec1::<Self::Elem>()) { for v in vs.into_iter() { self.fmt(v, max_w, f)?; write!(f, ", ")?; } } write!(f, "...")?; if let Ok(vs) = t .narrow(0, v - edge_items, edge_items) .and_then(|t| t.to_vec1::<Self::Elem>()) { for v in vs.into_iter() { write!(f, ", ")?; self.fmt(v, max_w, f)?; } } } [_] => { let elements_per_line = usize::max(1, po.line_width / (max_w + 2)); if let Ok(vs) = t.to_vec1::<Self::Elem>() { for (i, v) in vs.into_iter().enumerate() { if i > 0 { if i % elements_per_line == 0 { write!(f, ",")?; Self::write_newline_indent(indent, f)? } else { write!(f, ", ")?; } } self.fmt(v, max_w, f)? } } } _ => { if summarize && dims[0] > 2 * edge_items { for i in 0..edge_items { match t.get(i) { Ok(t) => self.fmt_tensor(&t, indent + 1, max_w, summarize, po, f)?, Err(e) => write!(f, "{e:?}")?, } write!(f, ",")?; Self::write_newline_indent(indent, f)? } write!(f, "...")?; Self::write_newline_indent(indent, f)?; for i in dims[0] - edge_items..dims[0] { match t.get(i) { Ok(t) => self.fmt_tensor(&t, indent + 1, max_w, summarize, po, f)?, Err(e) => write!(f, "{e:?}")?, } if i + 1 != dims[0] { write!(f, ",")?; Self::write_newline_indent(indent, f)? } } } else { for i in 0..dims[0] { match t.get(i) { Ok(t) => self.fmt_tensor(&t, indent + 1, max_w, summarize, po, f)?, Err(e) => write!(f, "{e:?}")?, } if i + 1 != dims[0] { write!(f, ",")?; Self::write_newline_indent(indent, f)? } } } } } write!(f, "]")?; Ok(()) } } struct FloatFormatter<S: WithDType> { int_mode: bool, sci_mode: bool, precision: usize, _phantom: std::marker::PhantomData<S>, } impl<S> FloatFormatter<S> where S: WithDType + num_traits::Float + std::fmt::Display, { fn new(t: &Tensor, po: &PrinterOptions) -> Result<Self> { let mut int_mode = true; let mut sci_mode = false; // Rather than containing all values, this should only include // values that end up being displayed according to [threshold]. let values = t .flatten_all()? .to_vec1()? .into_iter() .filter(|v: &S| v.is_finite() && !v.is_zero()) .collect::<Vec<_>>(); if !values.is_empty() { let mut nonzero_finite_min = S::max_value(); let mut nonzero_finite_max = S::min_value(); for &v in values.iter() { let v = v.abs(); if v < nonzero_finite_min { nonzero_finite_min = v } if v > nonzero_finite_max { nonzero_finite_max = v } } for &value in values.iter() { if value.ceil() != value { int_mode = false; break; } } if let Some(v1) = S::from(1000.) { if let Some(v2) = S::from(1e8) { if let Some(v3) = S::from(1e-4) { sci_mode = nonzero_finite_max / nonzero_finite_min > v1 || nonzero_finite_max > v2 || nonzero_finite_min < v3 } } } } match po.sci_mode { None => {} Some(v) => sci_mode = v, } Ok(Self { int_mode, sci_mode, precision: po.precision, _phantom: std::marker::PhantomData, }) } } impl<S> TensorFormatter for FloatFormatter<S> where S: WithDType + num_traits::Float + std::fmt::Display + std::fmt::LowerExp, { type Elem = S; fn fmt<T: std::fmt::Write>(&self, v: Self::Elem, max_w: usize, f: &mut T) -> std::fmt::Result { if self.sci_mode { write!( f, "{v:width$.prec$e}", v = v, width = max_w, prec = self.precision ) } else if self.int_mode { if v.is_finite() { write!(f, "{v:width$.0}.", v = v, width = max_w - 1) } else { write!(f, "{v:max_w$.0}") } } else { write!( f, "{v:width$.prec$}", v = v, width = max_w, prec = self.precision ) } } } struct IntFormatter<S: WithDType> { _phantom: std::marker::PhantomData<S>, } impl<S: WithDType> IntFormatter<S> { fn new() -> Self { Self { _phantom: std::marker::PhantomData, } } } impl<S> TensorFormatter for IntFormatter<S> where S: WithDType + std::fmt::Display, { type Elem = S; fn fmt<T: std::fmt::Write>(&self, v: Self::Elem, max_w: usize, f: &mut T) -> std::fmt::Result { write!(f, "{v:max_w$}") } } fn get_summarized_data(t: &Tensor, edge_items: usize) -> Result<Tensor> { let dims = t.dims(); if dims.is_empty() { Ok(t.clone()) } else if dims.len() == 1 { if dims[0] > 2 * edge_items { Tensor::cat( &[ t.narrow(0, 0, edge_items)?, t.narrow(0, dims[0] - edge_items, edge_items)?, ], 0, ) } else { Ok(t.clone()) } } else if dims[0] > 2 * edge_items { let mut vs: Vec<_> = (0..edge_items) .map(|i| get_summarized_data(&t.get(i)?, edge_items)) .collect::<Result<Vec<_>>>()?; for i in (dims[0] - edge_items)..dims[0] { vs.push(get_summarized_data(&t.get(i)?, edge_items)?) } Tensor::cat(&vs, 0) } else { let vs: Vec<_> = (0..dims[0]) .map(|i| get_summarized_data(&t.get(i)?, edge_items)) .collect::<Result<Vec<_>>>()?; Tensor::cat(&vs, 0) } } impl std::fmt::Display for Tensor { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let po = PRINT_OPTS.lock().unwrap(); let summarize = self.elem_count() > po.threshold; let to_display = if summarize { match get_summarized_data(self, po.edge_items) { Ok(v) => v, Err(err) => return write!(f, "{err:?}"), } } else { self.clone() }; match self.dtype() { DType::U8 => { let tf: IntFormatter<u8> = IntFormatter::new(); let max_w = tf.max_width(&to_display); tf.fmt_tensor(self, 1, max_w, summarize, &po, f)?; writeln!(f)?; } DType::U32 => { let tf: IntFormatter<u32> = IntFormatter::new(); let max_w = tf.max_width(&to_display); tf.fmt_tensor(self, 1, max_w, summarize, &po, f)?; writeln!(f)?; } DType::I64 => { let tf: IntFormatter<i64> = IntFormatter::new(); let max_w = tf.max_width(&to_display); tf.fmt_tensor(self, 1, max_w, summarize, &po, f)?; writeln!(f)?; } DType::BF16 => { if let Ok(tf) = FloatFormatter::<bf16>::new(&to_display, &po) { let max_w = tf.max_width(&to_display); tf.fmt_tensor(self, 1, max_w, summarize, &po, f)?; writeln!(f)?; } } DType::F16 => { if let Ok(tf) = FloatFormatter::<f16>::new(&to_display, &po) { let max_w = tf.max_width(&to_display); tf.fmt_tensor(self, 1, max_w, summarize, &po, f)?; writeln!(f)?; } } DType::F64 => { if let Ok(tf) = FloatFormatter::<f64>::new(&to_display, &po) { let max_w = tf.max_width(&to_display); tf.fmt_tensor(self, 1, max_w, summarize, &po, f)?; writeln!(f)?; } } DType::F32 => { if let Ok(tf) = FloatFormatter::<f32>::new(&to_display, &po) { let max_w = tf.max_width(&to_display); tf.fmt_tensor(self, 1, max_w, summarize, &po, f)?; writeln!(f)?; } } DType::F8E4M3 => { if let Ok(tf) = FloatFormatter::<F8E4M3>::new(&to_display, &po) { let max_w = tf.max_width(&to_display); tf.fmt_tensor(self, 1, max_w, summarize, &po, f)?; writeln!(f)?; } } }; let device_str = match self.device().location() { crate::DeviceLocation::Cpu => "".to_owned(), crate::DeviceLocation::Cuda { gpu_id } => { format!(", cuda:{gpu_id}") } crate::DeviceLocation::Metal { gpu_id } => { format!(", metal:{gpu_id}") } }; write!( f, "Tensor[{:?}, {}{}]", self.dims(), self.dtype().as_str(), device_str ) } }
candle/candle-core/src/display.rs/0
{ "file_path": "candle/candle-core/src/display.rs", "repo_id": "candle", "token_count": 10009 }
27
#![allow(unused)] use super::GgmlDType; use crate::{CudaDevice, CudaStorage, Error, Result}; pub struct QCudaStorage { dtype: GgmlDType, device: CudaDevice, } impl QCudaStorage { pub fn zeros(_: &CudaDevice, _: usize, _: GgmlDType) -> Result<Self> { Err(Error::NotCompiledWithCudaSupport) } pub fn dtype(&self) -> GgmlDType { self.dtype } pub fn device(&self) -> &CudaDevice { &self.device } pub fn dequantize(&self, _elem_count: usize) -> Result<CudaStorage> { Err(Error::NotCompiledWithCudaSupport) } pub fn dequantize_f16(&self, _elem_count: usize) -> Result<CudaStorage> { Err(Error::NotCompiledWithCudaSupport) } pub fn quantize(&mut self, _src: &CudaStorage) -> Result<()> { Err(Error::NotCompiledWithCudaSupport) } pub fn storage_size_in_bytes(&self) -> usize { 0 } pub fn fwd( &self, _self_shape: &crate::Shape, _storage: &CudaStorage, _layout: &crate::Layout, ) -> Result<(CudaStorage, crate::Shape)> { Err(Error::NotCompiledWithCudaSupport) } } pub fn load_quantized<T: super::GgmlType + Send + Sync + 'static>( _device: &CudaDevice, _data: &[T], ) -> Result<super::QStorage> { Err(Error::NotCompiledWithCudaSupport) }
candle/candle-core/src/quantized/dummy_cuda.rs/0
{ "file_path": "candle/candle-core/src/quantized/dummy_cuda.rs", "repo_id": "candle", "token_count": 594 }
28
use crate::Layout; /// An iterator over offset position for items of an N-dimensional arrays stored in a /// flat buffer using some potential strides. #[derive(Debug)] pub struct StridedIndex<'a> { next_storage_index: Option<usize>, multi_index: Vec<usize>, dims: &'a [usize], stride: &'a [usize], } impl<'a> StridedIndex<'a> { pub(crate) fn new(dims: &'a [usize], stride: &'a [usize], start_offset: usize) -> Self { let elem_count: usize = dims.iter().product(); let next_storage_index = if elem_count == 0 { None } else { // This applies to the scalar case. Some(start_offset) }; StridedIndex { next_storage_index, multi_index: vec![0; dims.len()], dims, stride, } } pub(crate) fn from_layout(l: &'a Layout) -> Self { Self::new(l.dims(), l.stride(), l.start_offset()) } } impl Iterator for StridedIndex<'_> { type Item = usize; fn next(&mut self) -> Option<Self::Item> { let storage_index = self.next_storage_index?; let mut updated = false; let mut next_storage_index = storage_index; for ((multi_i, max_i), stride_i) in self .multi_index .iter_mut() .zip(self.dims.iter()) .zip(self.stride.iter()) .rev() { let next_i = *multi_i + 1; if next_i < *max_i { *multi_i = next_i; updated = true; next_storage_index += stride_i; break; } else { next_storage_index -= *multi_i * stride_i; *multi_i = 0 } } self.next_storage_index = if updated { Some(next_storage_index) } else { None }; Some(storage_index) } } #[derive(Debug)] pub enum StridedBlocks<'a> { SingleBlock { start_offset: usize, len: usize, }, MultipleBlocks { block_start_index: StridedIndex<'a>, block_len: usize, }, }
candle/candle-core/src/strided_index.rs/0
{ "file_path": "candle/candle-core/src/strided_index.rs", "repo_id": "candle", "token_count": 1094 }
29
import torch from collections import OrderedDict # Write a trivial tensor to a pt file a= torch.tensor([[1,2,3,4], [5,6,7,8]]) o = OrderedDict() o["test"] = a # Write a trivial tensor to a pt file torch.save(o, "test.pt") ############################################################################################################ # Write a trivial tensor to a pt file with a key torch.save({"model_state_dict": o}, "test_with_key.pt") ############################################################################################################ # Create a tensor with fortran contiguous memory layout import numpy as np # Step 1: Create a 3D NumPy array with Fortran order using a range of numbers # For example, creating a 2x3x4 array array_fortran = np.asfortranarray(np.arange(1, 2*3*4 + 1).reshape(2, 3, 4)) # Verify the memory order print("Is Fortran contiguous (F order):", array_fortran.flags['F_CONTIGUOUS']) # Should be True print("Is C contiguous (C order):", array_fortran.flags['C_CONTIGUOUS']) # Should be False # Step 2: Convert the NumPy array to a PyTorch tensor tensor_fortran = torch.from_numpy(array_fortran) # Verify the tensor layout print("Tensor stride:", tensor_fortran.stride()) # Stride will reflect the Fortran memory layout # Step 3: Save the PyTorch tensor to a .pth file torch.save({"tensor_fortran": tensor_fortran}, 'fortran_tensor_3d.pth') print("3D Tensor saved with Fortran layout.")
candle/candle-core/tests/pth.py/0
{ "file_path": "candle/candle-core/tests/pth.py", "repo_id": "candle", "token_count": 441 }
30
//! The CIFAR-10 dataset. //! //! The files can be downloaded from the following page: //! <https://www.cs.toronto.edu/~kriz/cifar.html> //! The binary version of the dataset is used. use crate::vision::Dataset; use candle::{DType, Device, Error, Result, Tensor}; use hf_hub::{api::sync::Api, Repo, RepoType}; use parquet::file::reader::{FileReader, SerializedFileReader}; use std::fs::File; use std::io::{BufReader, Read}; const W: usize = 32; const H: usize = 32; const C: usize = 3; const BYTES_PER_IMAGE: usize = W * H * C + 1; const SAMPLES_PER_FILE: usize = 10000; fn read_file(filename: &std::path::Path) -> Result<(Tensor, Tensor)> { let mut buf_reader = BufReader::new(File::open(filename)?); let mut data = vec![0u8; SAMPLES_PER_FILE * BYTES_PER_IMAGE]; buf_reader.read_exact(&mut data)?; let mut images = vec![]; let mut labels = vec![]; for index in 0..SAMPLES_PER_FILE { let content_offset = BYTES_PER_IMAGE * index; labels.push(data[content_offset]); images.push(&data[1 + content_offset..content_offset + BYTES_PER_IMAGE]); } let images: Vec<u8> = images .iter() .copied() .flatten() .copied() .collect::<Vec<_>>(); let labels = Tensor::from_vec(labels, SAMPLES_PER_FILE, &Device::Cpu)?; let images = Tensor::from_vec(images, (SAMPLES_PER_FILE, C, H, W), &Device::Cpu)?; let images = (images.to_dtype(DType::F32)? / 255.)?; Ok((images, labels)) } pub fn load_dir<T: AsRef<std::path::Path>>(dir: T) -> Result<Dataset> { let dir = dir.as_ref(); let (test_images, test_labels) = read_file(&dir.join("test_batch.bin"))?; let train_images_and_labels = [ "data_batch_1.bin", "data_batch_2.bin", "data_batch_3.bin", "data_batch_4.bin", "data_batch_5.bin", ] .iter() .map(|x| read_file(&dir.join(x))) .collect::<Result<Vec<_>>>()?; let (train_images, train_labels): (Vec<_>, Vec<_>) = train_images_and_labels.into_iter().unzip(); Ok(Dataset { train_images: Tensor::cat(&train_images, 0)?, train_labels: Tensor::cat(&train_labels, 0)?, test_images, test_labels, labels: 10, }) } fn load_parquet(parquet: SerializedFileReader<std::fs::File>) -> Result<(Tensor, Tensor)> { let samples = parquet.metadata().file_metadata().num_rows() as usize; let mut buffer_images: Vec<u8> = Vec::with_capacity(samples * 1_024); let mut buffer_labels: Vec<u8> = Vec::with_capacity(samples); for row in parquet.into_iter().flatten() { for (_name, field) in row.get_column_iter() { if let parquet::record::Field::Group(subrow) = field { for (_name, field) in subrow.get_column_iter() { if let parquet::record::Field::Bytes(value) = field { // image-rs crate convention is to load in (width, height, channels) order // See: https://docs.rs/image/latest/image/trait.ImageDecoder.html#tymethod.dimensions let image = image::load_from_memory(value.data()).unwrap(); buffer_images.extend(image.to_rgb8().as_raw()); } } } else if let parquet::record::Field::Long(label) = field { buffer_labels.push(*label as u8); } } } // Reorder image-rs convention (width, height, channels) to candle/pytorch convolution convention (channels, height, width) let images = (Tensor::from_vec(buffer_images, (samples, 32, 32, 3), &Device::Cpu)? .to_dtype(DType::F32)? .permute((0, 3, 2, 1))? / 255.)?; let labels = Tensor::from_vec(buffer_labels, (samples,), &Device::Cpu)?; Ok((images, labels)) } pub fn load() -> Result<Dataset> { let api = Api::new().map_err(|e| Error::Msg(format!("Api error: {e}")))?; let dataset_id = "cifar10".to_string(); let repo = Repo::with_revision( dataset_id, RepoType::Dataset, "refs/convert/parquet".to_string(), ); let repo = api.repo(repo); let test_parquet_filename = repo .get("plain_text/test/0000.parquet") .map_err(|e| Error::Msg(format!("Api error: {e}")))?; let train_parquet_filename = repo .get("plain_text/train/0000.parquet") .map_err(|e| Error::Msg(format!("Api error: {e}")))?; let test_parquet = SerializedFileReader::new(std::fs::File::open(test_parquet_filename)?) .map_err(|e| Error::Msg(format!("Parquet error: {e}")))?; let train_parquet = SerializedFileReader::new(std::fs::File::open(train_parquet_filename)?) .map_err(|e| Error::Msg(format!("Parquet error: {e}")))?; let (test_images, test_labels) = load_parquet(test_parquet)?; let (train_images, train_labels) = load_parquet(train_parquet)?; Ok(crate::vision::Dataset { train_images, train_labels, test_images, test_labels, labels: 10, }) }
candle/candle-datasets/src/vision/cifar.rs/0
{ "file_path": "candle/candle-datasets/src/vision/cifar.rs", "repo_id": "candle", "token_count": 2290 }
31
#[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; use anyhow::Error as E; use clap::Parser; use candle::{DType, Device, Result, Tensor}; use candle_examples::token_output_stream::TokenOutputStream; use candle_nn::VarBuilder; use candle_transformers::models::blip; use candle_transformers::models::quantized_blip; use tokenizers::Tokenizer; enum Model { M(blip::BlipForConditionalGeneration), Q(quantized_blip::BlipForConditionalGeneration), } impl Model { fn text_decoder_forward(&mut self, xs: &Tensor, img_xs: &Tensor) -> Result<Tensor> { match self { Self::M(m) => m.text_decoder().forward(xs, img_xs), Self::Q(m) => m.text_decoder().forward(xs, img_xs), } } } // TODO: Maybe add support for the conditional prompt. #[derive(Parser)] struct Args { #[arg(long)] model: Option<String>, #[arg(long)] tokenizer: Option<String>, #[arg(long)] image: String, /// Run on CPU rather than on GPU. #[arg(long)] cpu: bool, /// Use the quantized version of the model. #[arg(long)] quantized: bool, } const SEP_TOKEN_ID: u32 = 102; /// Loads an image from disk using the image crate, this returns a tensor with shape /// (3, 384, 384). OpenAI normalization is applied. pub fn load_image<P: AsRef<std::path::Path>>(p: P) -> Result<Tensor> { let img = image::ImageReader::open(p)? .decode() .map_err(candle::Error::wrap)? .resize_to_fill(384, 384, image::imageops::FilterType::Triangle); let img = img.to_rgb8(); let data = img.into_raw(); let data = Tensor::from_vec(data, (384, 384, 3), &Device::Cpu)?.permute((2, 0, 1))?; let mean = Tensor::new(&[0.48145466f32, 0.4578275, 0.40821073], &Device::Cpu)?.reshape((3, 1, 1))?; let std = Tensor::new(&[0.26862954f32, 0.261_302_6, 0.275_777_1], &Device::Cpu)? .reshape((3, 1, 1))?; (data.to_dtype(candle::DType::F32)? / 255.)? .broadcast_sub(&mean)? .broadcast_div(&std) } pub fn main() -> anyhow::Result<()> { let args = Args::parse(); let model_file = match args.model { None => { let api = hf_hub::api::sync::Api::new()?; if args.quantized { let api = api.model("lmz/candle-blip".to_string()); api.get("blip-image-captioning-large-q4k.gguf")? } else { let api = api.repo(hf_hub::Repo::with_revision( "Salesforce/blip-image-captioning-large".to_string(), hf_hub::RepoType::Model, "refs/pr/18".to_string(), )); api.get("model.safetensors")? } } Some(model) => model.into(), }; let tokenizer = match args.tokenizer { None => { let api = hf_hub::api::sync::Api::new()?; let api = api.model("Salesforce/blip-image-captioning-large".to_string()); api.get("tokenizer.json")? } Some(file) => file.into(), }; let tokenizer = Tokenizer::from_file(tokenizer).map_err(E::msg)?; let mut tokenizer = TokenOutputStream::new(tokenizer); let mut logits_processor = candle_transformers::generation::LogitsProcessor::new(1337, None, None); let config = blip::Config::image_captioning_large(); let device = candle_examples::device(args.cpu)?; let (image_embeds, device, mut model) = if args.quantized { let device = Device::Cpu; let image = load_image(args.image)?.to_device(&device)?; println!("loaded image {image:?}"); let vb = quantized_blip::VarBuilder::from_gguf(model_file, &device)?; let model = quantized_blip::BlipForConditionalGeneration::new(&config, vb)?; let image_embeds = image.unsqueeze(0)?.apply(model.vision_model())?; (image_embeds, device, Model::Q(model)) } else { let image = load_image(args.image)?.to_device(&device)?; println!("loaded image {image:?}"); let vb = unsafe { VarBuilder::from_mmaped_safetensors(&[model_file], DType::F32, &device)? }; let model = blip::BlipForConditionalGeneration::new(&config, vb)?; let image_embeds = image.unsqueeze(0)?.apply(model.vision_model())?; (image_embeds, device, Model::M(model)) }; let mut token_ids = vec![30522u32]; for index in 0..1000 { let context_size = if index > 0 { 1 } else { token_ids.len() }; let start_pos = token_ids.len().saturating_sub(context_size); let input_ids = Tensor::new(&token_ids[start_pos..], &device)?.unsqueeze(0)?; let logits = model.text_decoder_forward(&input_ids, &image_embeds)?; let logits = logits.squeeze(0)?; let logits = logits.get(logits.dim(0)? - 1)?; let token = logits_processor.sample(&logits)?; if token == SEP_TOKEN_ID { break; } token_ids.push(token); if let Some(t) = tokenizer.next_token(token)? { use std::io::Write; print!("{t}"); std::io::stdout().flush()?; } } if let Some(rest) = tokenizer.decode_rest().map_err(E::msg)? { print!("{rest}"); } println!(); Ok(()) }
candle/candle-examples/examples/blip/main.rs/0
{ "file_path": "candle/candle-examples/examples/blip/main.rs", "repo_id": "candle", "token_count": 2436 }
32
#[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::csm::{Config, Model}; use candle::{DType, IndexOp, Tensor}; use candle_nn::VarBuilder; use hf_hub::{api::sync::Api, Repo, RepoType}; use tokenizers::Tokenizer; #[derive(Clone, Debug, Copy, PartialEq, Eq, clap::ValueEnum)] enum Which { #[value(name = "1b")] Csm1b, } #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] struct Args { /// Run on CPU rather than on GPU. #[arg(long)] cpu: bool, /// Enable tracing (generates a trace-timestamp.json file). #[arg(long)] tracing: bool, #[arg(long)] use_flash_attn: bool, /// The prompt to be used for the generation, use a | to separate the speakers. #[arg(long, default_value = "Hey how are you doing today?")] prompt: String, /// The voices to be used, in safetensors format. #[arg(long)] voices: String, /// The output file using the wav format. #[arg(long, default_value = "out.wav")] out_file: String, /// The temperature used to generate samples. #[arg(long, default_value_t = 0.7)] temperature: f64, /// Nucleus sampling probability cutoff. #[arg(long)] top_p: Option<f64>, /// Only sample among the top K samples. #[arg(long)] top_k: Option<usize>, /// The seed to use when generating random samples. #[arg(long, default_value_t = 299792458)] seed: u64, /// The length of the sample to generate (in tokens). #[arg(long, short = 'n', default_value_t = 10000)] sample_len: usize, /// The model size to use. #[arg(long, default_value = "1b")] which: Which, #[arg(long)] model_id: Option<String>, #[arg(long, default_value = "main")] revision: String, #[arg(long)] tokenizer: Option<String>, #[arg(long)] config: Option<String>, #[arg(long)] weights: Option<String>, /// The mimi model weight file, in safetensor format. #[arg(long)] mimi_weights: Option<String>, /// Penalty to be applied for repeating tokens, 1. means no penalty. #[arg(long, default_value_t = 1.1)] repeat_penalty: f32, /// The context size to consider for the repeat penalty. #[arg(long, default_value_t = 64)] repeat_last_n: usize, } fn main() -> Result<()> { use tracing_chrome::ChromeLayerBuilder; use tracing_subscriber::prelude::*; let args = Args::parse(); let _guard = if args.tracing { let (chrome_layer, guard) = ChromeLayerBuilder::new().build(); tracing_subscriber::registry().with(chrome_layer).init(); Some(guard) } else { None }; println!( "avx: {}, neon: {}, simd128: {}, f16c: {}", candle::utils::with_avx(), candle::utils::with_neon(), candle::utils::with_simd128(), candle::utils::with_f16c() ); println!( "temp: {:.2} repeat-penalty: {:.2} repeat-last-n: {}", args.temperature, args.repeat_penalty, args.repeat_last_n ); let start = std::time::Instant::now(); let api = Api::new()?; let model_id = match args.model_id { Some(model_id) => model_id, None => { let name = match args.which { Which::Csm1b => "sesame/csm-1b", }; name.to_string() } }; let repo = api.repo(Repo::with_revision( model_id, RepoType::Model, args.revision, )); let filenames = match args.weights { Some(files) => files .split(',') .map(std::path::PathBuf::from) .collect::<Vec<_>>(), None => vec![repo.get("model.safetensors")?], }; let tokenizer_filename = match args.tokenizer { Some(file) => std::path::PathBuf::from(file), None => api .model("meta-llama/Llama-3.2-1B".to_string()) .get("tokenizer.json")?, }; let mimi_filename = match args.mimi_weights { Some(model) => std::path::PathBuf::from(model), None => Api::new()? .model("kyutai/mimi".to_string()) .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 config: Config = match args.config { Some(config_file) => serde_json::from_slice(&std::fs::read(config_file)?)?, None => { let config_file = repo.get("config.json")?; serde_json::from_slice(&std::fs::read(config_file)?)? } }; let device = candle_examples::device(args.cpu)?; let (mut model, device) = { let dtype = device.bf16_default_to_f32(); let vb = unsafe { VarBuilder::from_mmaped_safetensors(&filenames, dtype, &device)? }; let model = Model::new(&config, vb)?; (model, device) }; let mut mimi_model = { use candle_transformers::models::mimi; let vb = unsafe { VarBuilder::from_mmaped_safetensors(&[mimi_filename], DType::F32, &device)? }; let config = mimi::Config::v0_1(Some(32)); mimi::Model::new(config, vb)? }; let cb = config.audio_num_codebooks; println!("loaded the model in {:?}", start.elapsed()); let voices = candle::safetensors::load(args.voices, &device)?; let mut lp = candle_transformers::generation::LogitsProcessor::new( args.seed, Some(args.temperature), None, ); let tokens = voices .get("tokens") .expect("no tokens in prompt") .to_dtype(DType::U32)?; let mask = voices.get("mask").expect("no mask in prompt").clone(); let mut pos = 0; let _frame = model.generate_frame(&tokens, &mask, pos, &mut lp)?; pos += tokens.dim(1)?; let mut all_pcms = vec![]; for (turn_idx, prompt) in args.prompt.split('|').enumerate() { println!("{prompt:?}"); let speaker_idx = turn_idx % 2; let prompt = format!("[{speaker_idx}]{prompt}<|end_of_text|>"); let prompt = tokenizer.encode(prompt, true).map_err(E::msg)?; let (mut tokens, mut mask) = model.text_tokens_and_mask(prompt.get_ids())?; let mut generated_tokens = vec![]; loop { let frame = model.generate_frame(&tokens, &mask, pos, &mut lp)?; pos += tokens.dim(1)?; let is_done = frame.iter().all(|&x| x == 0); (tokens, mask) = model.audio_tokens_and_mask(frame)?; print!("\rframe {pos}"); if is_done { let _frame = model.generate_frame(&tokens, &mask, pos, &mut lp)?; pos += tokens.dim(1)?; break; } generated_tokens.push(tokens.clone()); } println!(); let generated_tokens = Tensor::cat(&generated_tokens, 1)?.narrow(2, 0, cb)?.t()?; let pcm = mimi_model.decode(&generated_tokens)?; let pcm = pcm.i(0)?.i(0)?.to_dtype(DType::F32)?; let pcm = candle_examples::audio::normalize_loudness(&pcm, 24_000, true)?; all_pcms.push(pcm); } let pcm = Tensor::cat(&all_pcms, 0)?; let pcm = pcm.to_vec1::<f32>()?; println!("writing output file {}", args.out_file); let mut output = std::fs::File::create(args.out_file)?; candle_examples::wav::write_pcm_as_wav(&mut output, &pcm, 24_000)?; Ok(()) }
candle/candle-examples/examples/csm/main.rs/0
{ "file_path": "candle/candle-examples/examples/csm/main.rs", "repo_id": "candle", "token_count": 3417 }
33
# candle-dinov2-reg4 [DINOv2-reg4](https://arxiv.org/abs/2309.16588) is the lastest version of DINOv2 with registers. In this example, it is used as an plant species classifier: the model returns the probability for the image to belong to each of the 7806 PlantCLEF2024 categories. ## Running some example ```bash # Download classes names and a plant picture to identify curl https://huggingface.co/vincent-espitalier/dino-v2-reg4-with-plantclef2024-weights/raw/main/species_id_mapping.txt --output candle-examples/examples/dinov2reg4/species_id_mapping.txt curl https://bs.plantnet.org/image/o/bd2d3830ac3270218ba82fd24e2290becd01317c --output candle-examples/examples/dinov2reg4/bd2d3830ac3270218ba82fd24e2290becd01317c.jpg # Perform inference cargo run --example dinov2reg4 --release -- --image candle-examples/examples/dinov2reg4/bd2d3830ac3270218ba82fd24e2290becd01317c.jpg > Orchis simia Lam. : 45.55% > Orchis × bergonii Nanteuil: 9.80% > Orchis italica Poir. : 9.66% > Orchis × angusticruris Franch.: 2.76% > Orchis × bivonae Tod. : 2.54% ``` ![Orchis Simia](https://bs.plantnet.org/image/o/bd2d3830ac3270218ba82fd24e2290becd01317c)
candle/candle-examples/examples/dinov2reg4/README.md/0
{ "file_path": "candle/candle-examples/examples/dinov2reg4/README.md", "repo_id": "candle", "token_count": 466 }
34
# candle-fastvit [FastViT: A Fast Hybrid Vision Transformer using Structural Reparameterization](https://arxiv.org/abs/2303.14189). This candle implementation uses a pre-trained FastViT network for inference. The classification head has been trained on the ImageNet dataset and returns the probabilities for the top-5 classes. ## Running an example ``` $ cargo run --example fastvit --release -- --image candle-examples/examples/yolo-v8/assets/bike.jpg --which sa12 loaded image Tensor[dims 3, 256, 256; f32] model built mountain bike, all-terrain bike, off-roader: 52.67% bicycle-built-for-two, tandem bicycle, tandem: 7.93% unicycle, monocycle : 3.46% maillot : 1.32% crash helmet : 1.28% ```
candle/candle-examples/examples/fastvit/README.md/0
{ "file_path": "candle/candle-examples/examples/fastvit/README.md", "repo_id": "candle", "token_count": 258 }
35
# hiera [Hiera: A Hierarchical Vision Transformer without the Bells-and-Whistles](https://arxiv.org/abs/2306.00989) This candle implementation uses pre-trained Hiera models from timm for inference. The classification head has been trained on the ImageNet dataset and returns the probabilities for the top-5 classes. ## Running an example ``` $ cargo run --example hiera --release -- --image candle-examples/examples/yolo-v8/assets/bike.jpg --which tiny loaded image Tensor[dims 3, 224, 224; f32] model built mountain bike, all-terrain bike, off-roader: 71.15% unicycle, monocycle : 7.11% knee pad : 4.26% crash helmet : 1.48% moped : 1.07% ```
candle/candle-examples/examples/hiera/README.md/0
{ "file_path": "candle/candle-examples/examples/hiera/README.md", "repo_id": "candle", "token_count": 260 }
36
#[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; use anyhow::{Error as E, Result}; use clap::{Parser, ValueEnum}; mod model; use model::{Config, Model}; use candle::{DType, Device, Module, Tensor}; use candle_examples::token_output_stream::TokenOutputStream; use candle_nn::VarBuilder; use candle_transformers::generation::LogitsProcessor; use hf_hub::{api::sync::Api, Repo, RepoType}; use tokenizers::Tokenizer; struct TextGeneration { model: Model, device: Device, tokenizer: TokenOutputStream, logits_processor: LogitsProcessor, repeat_penalty: f32, repeat_last_n: usize, } impl TextGeneration { #[allow(clippy::too_many_arguments)] fn new( model: Model, tokenizer: Tokenizer, seed: u64, temp: Option<f64>, top_p: Option<f64>, repeat_penalty: f32, repeat_last_n: usize, device: &Device, ) -> Self { let logits_processor = LogitsProcessor::new(seed, temp, top_p); Self { model, tokenizer: TokenOutputStream::new(tokenizer), logits_processor, repeat_penalty, repeat_last_n, device: device.clone(), } } fn run(&mut self, prompt: &str, sample_len: usize) -> Result<()> { use std::io::Write; self.tokenizer.clear(); let mut tokens = self .tokenizer .tokenizer() .encode(prompt, true) .map_err(E::msg)? .get_ids() .to_vec(); for &t in tokens.iter() { if let Some(t) = self.tokenizer.next_token(t)? { print!("{t}") } } std::io::stdout().flush()?; let mut generated_tokens = 0usize; let eos_token = match self.tokenizer.get_token("<|endoftext|>") { Some(token) => token, None => anyhow::bail!("cannot find the </s> token"), }; let start_gen = std::time::Instant::now(); for _ in 0..sample_len { let input = Tensor::new(tokens.as_slice(), &self.device)?.unsqueeze(0)?; let logits = self.model.forward(&input)?; let logits = logits.squeeze(0)?.squeeze(0)?.to_dtype(DType::F32)?; let logits = if self.repeat_penalty == 1. { logits } else { let start_at = tokens.len().saturating_sub(self.repeat_last_n); candle_transformers::utils::apply_repeat_penalty( &logits, self.repeat_penalty, &tokens[start_at..], )? }; let next_token = self.logits_processor.sample(&logits)?; tokens.push(next_token); generated_tokens += 1; if next_token == eos_token { break; } if let Some(t) = self.tokenizer.next_token(next_token)? { print!("{t}"); std::io::stdout().flush()?; } } let dt = start_gen.elapsed(); if let Some(rest) = self.tokenizer.decode_rest().map_err(E::msg)? { print!("{rest}"); } std::io::stdout().flush()?; println!( "\n{generated_tokens} tokens generated ({:.2} token/s)", generated_tokens as f64 / dt.as_secs_f64(), ); Ok(()) } } #[derive(Parser, ValueEnum, Clone, Copy, PartialEq, Eq, Debug)] enum Which { Mamba130m, Mamba370m, Mamba790m, Mamba1_4b, Mamba2_8b, Mamba2_8bSlimPj, } impl std::fmt::Display for Which { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{self:?}") } } impl Which { fn model_id(&self) -> &'static str { match self { Self::Mamba130m => "state-spaces/mamba-130m", Self::Mamba370m => "state-spaces/mamba-370m", Self::Mamba790m => "state-spaces/mamba-790m", Self::Mamba1_4b => "state-spaces/mamba-1.4b", Self::Mamba2_8b => "state-spaces/mamba-2.8b", Self::Mamba2_8bSlimPj => "state-spaces/mamba-2.8b-slimpj'", } } fn revision(&self) -> &'static str { match self { Self::Mamba130m | Self::Mamba370m | Self::Mamba790m | Self::Mamba1_4b | Self::Mamba2_8bSlimPj => "refs/pr/1", Self::Mamba2_8b => "refs/pr/4", } } } #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] struct Args { /// Run on CPU rather than on GPU. #[arg(long)] cpu: bool, /// Enable tracing (generates a trace-timestamp.json file). #[arg(long)] tracing: bool, #[arg(long)] 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 = 5000)] sample_len: usize, #[arg(long, default_value = "mamba130m")] which: Which, #[arg(long)] model_id: Option<String>, #[arg(long)] revision: Option<String>, #[arg(long)] tokenizer_file: Option<String>, #[arg(long)] weight_files: Option<String>, #[arg(long)] config_file: Option<String>, /// Penalty to be applied for repeating tokens, 1. means no penalty. #[arg(long, default_value_t = 1.1)] repeat_penalty: f32, /// The context size to consider for the repeat penalty. #[arg(long, default_value_t = 64)] repeat_last_n: usize, } fn main() -> Result<()> { use tracing_chrome::ChromeLayerBuilder; use tracing_subscriber::prelude::*; let args = Args::parse(); let _guard = if args.tracing { let (chrome_layer, guard) = ChromeLayerBuilder::new().build(); tracing_subscriber::registry().with(chrome_layer).init(); Some(guard) } else { None }; println!( "avx: {}, neon: {}, simd128: {}, f16c: {}", candle::utils::with_avx(), candle::utils::with_neon(), candle::utils::with_simd128(), candle::utils::with_f16c() ); println!( "temp: {:.2} repeat-penalty: {:.2} repeat-last-n: {}", args.temperature.unwrap_or(0.), args.repeat_penalty, args.repeat_last_n ); let start = std::time::Instant::now(); let api = Api::new()?; let repo = api.repo(Repo::with_revision( args.model_id .unwrap_or_else(|| args.which.model_id().to_string()), RepoType::Model, args.revision .unwrap_or_else(|| args.which.revision().to_string()), )); let tokenizer_filename = match args.tokenizer_file { Some(file) => std::path::PathBuf::from(file), None => api .model("EleutherAI/gpt-neox-20b".to_string()) .get("tokenizer.json")?, }; let config_filename = match args.config_file { Some(file) => std::path::PathBuf::from(file), None => repo.get("config.json")?, }; let filenames = match args.weight_files { Some(files) => files .split(',') .map(std::path::PathBuf::from) .collect::<Vec<_>>(), None => { vec![repo.get("model.safetensors")?] } }; println!("retrieved the files in {:?}", start.elapsed()); let tokenizer = Tokenizer::from_file(tokenizer_filename).map_err(E::msg)?; let start = std::time::Instant::now(); let config: Config = serde_json::from_slice(&std::fs::read(config_filename)?)?; let device = candle_examples::device(args.cpu)?; let vb = unsafe { VarBuilder::from_mmaped_safetensors(&filenames, DType::F32, &device)? }; let model = Model::new(&config, vb.pp("backbone"))?; println!("loaded the model in {:?}", start.elapsed()); let mut pipeline = TextGeneration::new( model, tokenizer, args.seed, args.temperature, args.top_p, args.repeat_penalty, args.repeat_last_n, &device, ); pipeline.run(&args.prompt, args.sample_len)?; Ok(()) }
candle/candle-examples/examples/mamba-minimal/main.rs/0
{ "file_path": "candle/candle-examples/examples/mamba-minimal/main.rs", "repo_id": "candle", "token_count": 4086 }
37
# NV-Embed-v2 Candle implementation (inference only) of [NV-Embed-v2](https://huggingface.co/nvidia/NV-Embed-v2), a text embedding model that ranks No. 1 (as of Nov 25 2024) on the [MTEB](https://huggingface.co/spaces/mteb/leaderboard) benchmark with a score of 72.31 across 56 text embedding tasks. ## Running an example: Retrieval ```bash cargo run --example nvembed_v2 --release > scores: [[87.4269, 0.4629], > [ 0.9653, 86.0372]] > Tensor[[2, 2], f32] ``` In this example, we have two queries and two passages (the corresponding answers). The output tensor represents the similarity scores between each query-passage pair. The scores are computed by taking the dot product of the query and passage embeddings and scaling the result by 100. ```rust let queries = [ "are judo throws allowed in wrestling?", "how to become a radiology technician in michigan?", ]; let query_instruction = "Instruct: Given a question, retrieve passages that answer the question\nQuery: " .to_string(); let passages = [ "Since you're reading this, you are probably someone from a judo background or someone who is just wondering how judo techniques can be applied under wrestling rules. So without further ado, let's get to the question. Are Judo throws allowed in wrestling? Yes, judo throws are allowed in freestyle and folkstyle wrestling. You only need to be careful to follow the slam rules when executing judo throws. In wrestling, a slam is lifting and returning an opponent to the mat with unnecessary force.", "Below are the basic steps to becoming a radiologic technologist in Michigan:Earn a high school diploma. As with most careers in health care, a high school education is the first step to finding entry-level employment. Taking classes in math and science, such as anatomy, biology, chemistry, physiology, and physics, can help prepare students for their college studies and future careers.Earn an associate degree. Entry-level radiologic positions typically require at least an Associate of Applied Science. Before enrolling in one of these degree programs, students should make sure it has been properly accredited by the Joint Review Committee on Education in Radiologic Technology (JRCERT).Get licensed or certified in the state of Michigan." ]; let passage_instruction = "".to_string(); ``` If you already have the model and tokenizer files, you can use the `--tokenizer` and `--model-files` options to specify their full paths, instead of downloading them from the hub. ## Running an example: Sentence embedding ```bash cargo run --example nvembed_v2 --release -- --prompt "Here is a test sentence" > Embedding: [[ 0.0066, -0.0048, 0.0066, ..., -0.0096, 0.0119, -0.0052]] > Tensor[[1, 4096], f32] ``` In this example, we pass a prompt to the model and it outputs the vector encoding of the prompt. ## Hardware Requirements 29.25GB at fp32 ## License CC-BY-NC-4.0. This model should not be used for any commercial purpose. Refer the [license](https://spdx.org/licenses/CC-BY-NC-4.0) for the detailed terms.
candle/candle-examples/examples/nvembed_v2/README.md/0
{ "file_path": "candle/candle-examples/examples/nvembed_v2/README.md", "repo_id": "candle", "token_count": 851 }
38
# candle-phi: 1.3b and 2.7b LLM with state of the art performance for <10b models. [Phi-1.5](https://huggingface.co/microsoft/phi-1_5), [Phi-2](https://huggingface.co/microsoft/phi-2), and [Phi-3](https://huggingface.co/microsoft/Phi-3-mini-4k-instruct) are language models using only 1.3, 2.7, and 3.8 billion parameters but with state of the art performance compared to models with up to 10 billion parameters. The candle implementation provides both the standard version as well as a quantized variant. ## Running some examples For the v2 version. ```bash $ cargo run --example phi --release -- --model 2 \ --prompt "A skier slides down a frictionless slope of height 40m and length 80m. What's the skier speed at the bottom?" A skier slides down a frictionless slope of height 40m and length 80m. What's the skier speed at the bottom? Solution: The potential energy of the skier is converted into kinetic energy as it slides down the slope. The formula for potential energy is mgh, where m is mass, g is acceleration due to gravity (9.8 m/s^2), and h is height. Since there's no friction, all the potential energy is converted into kinetic energy at the bottom of the slope. The formula for kinetic energy is 1/2mv^2, where v is velocity. We can equate these two formulas: mgh = 1/2mv^2 Solving for v, we get: v = sqrt(2gh) Substituting the given values, we get: v = sqrt(2*9.8*40) = 28 m/s Therefore, the skier speed at the bottom of the slope is 28 m/s. ``` For the v1.5 version. ```bash $ cargo run --example phi --release -- --prompt "def print_prime(n): " def print_prime(n): print("Printing prime numbers") for i in range(2, n+1): if is_prime(i): print(i) def is_prime(n): if n <= 1: return False for i in range(2, int(math.sqrt(n))+1): if n % i == 0: return False return True $ cargo run --example phi --release -- \ --prompt "Explain how to find the median of an array and write the corresponding python function.\nAnswer:" \ --quantized --sample-len 200 Explain how to find the median of an array and write the corresponding python function. Answer: The median is the middle value in an array. If the array has an even number of elements, the median is the average of the two middle values. def median(arr): arr.sort() n = len(arr) if n % 2 == 0: return (arr[n//2 - 1] + arr[n//2]) / 2 else: return arr[n//2] ``` This also supports the [Puffin Phi v2 model](https://huggingface.co/teknium/Puffin-Phi-v2) for human interaction. ``` $ cargo run --example phi --release -- \ --prompt "USER: What would you do on a sunny day in Paris?\nASSISTANT:" \ --sample-len 200 --model puffin-phi-v2 --quantized USER: What would you do on a sunny day in Paris? ASSISTANT: On a sunny day in Paris, you could visit the Musée du Louvre to admire the famous painting "Mona Lisa" by Leonardo da Vinci. You might also want to stroll along the Champs-Élysées and enjoy the beautiful architecture of the buildings around you. Don't forget to stop by a café for a cup of coffee and to soak up the sun!" ```
candle/candle-examples/examples/phi/README.md/0
{ "file_path": "candle/candle-examples/examples/phi/README.md", "repo_id": "candle", "token_count": 1048 }
39
#[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; use clap::{Parser, ValueEnum}; use std::io::Write; use tokenizers::Tokenizer; use candle::quantized::{ggml_file, gguf_file}; use candle::Tensor; use candle_transformers::generation::{LogitsProcessor, Sampling}; use candle_examples::token_output_stream::TokenOutputStream; use candle_transformers::models::quantized_llama as model; use model::ModelWeights; const DEFAULT_PROMPT: &str = "My favorite theorem is "; #[derive(Debug)] enum Prompt { Interactive, Chat, One(String), } #[derive(Clone, Debug, Copy, PartialEq, Eq, ValueEnum)] enum Which { #[value(name = "7b")] L7b, #[value(name = "13b")] L13b, #[value(name = "70b")] L70b, #[value(name = "7b-chat")] L7bChat, #[value(name = "13b-chat")] L13bChat, #[value(name = "70b-chat")] L70bChat, #[value(name = "7b-code")] L7bCode, #[value(name = "13b-code")] L13bCode, #[value(name = "32b-code")] L34bCode, #[value(name = "7b-leo")] Leo7b, #[value(name = "13b-leo")] Leo13b, #[value(name = "7b-mistral")] Mistral7b, #[value(name = "7b-mistral-instruct")] Mistral7bInstruct, #[value(name = "7b-mistral-instruct-v0.2")] Mistral7bInstructV02, #[value(name = "7b-zephyr-a")] Zephyr7bAlpha, #[value(name = "7b-zephyr-b")] Zephyr7bBeta, #[value(name = "7b-open-chat-3.5")] OpenChat35, #[value(name = "7b-starling-a")] Starling7bAlpha, #[value(name = "mixtral")] Mixtral, #[value(name = "mixtral-instruct")] MixtralInstruct, #[value(name = "llama3-8b")] L8b, #[value(name = "phi3")] Phi3, #[value(name = "SmoLM2-360M-Instruct")] SmolLM2_360MInstruct, #[value(name = "SmoLM2-1.7B-Instruct")] SmolLM2_1BInstruct, #[value(name = "deepseekr1-llama8b")] DeepseekR1Llama8b, } impl Which { fn is_mistral(&self) -> bool { match self { Self::L7b | Self::L13b | Self::L70b | Self::L7bChat | Self::L13bChat | Self::L70bChat | Self::L7bCode | Self::L13bCode | Self::L34bCode | Self::Leo7b | Self::Leo13b | Self::L8b | Self::Phi3 | Self::SmolLM2_1BInstruct | Self::SmolLM2_360MInstruct | Self::DeepseekR1Llama8b => false, // Zephyr and OpenChat are fine tuned versions of mistral and should be treated in the // same way. Starling is a fine tuned version of OpenChat. Self::OpenChat35 | Self::Starling7bAlpha | Self::Zephyr7bAlpha | Self::Zephyr7bBeta | Self::Mixtral | Self::MixtralInstruct | Self::Mistral7b | Self::Mistral7bInstruct | Self::Mistral7bInstructV02 => true, } } fn is_zephyr(&self) -> bool { match self { Self::L7b | Self::L13b | Self::L70b | Self::L7bChat | Self::L13bChat | Self::L70bChat | Self::L7bCode | Self::L13bCode | Self::L34bCode | Self::Leo7b | Self::Leo13b | Self::Mixtral | Self::MixtralInstruct | Self::Mistral7b | Self::Mistral7bInstruct | Self::Mistral7bInstructV02 | Self::OpenChat35 | Self::Starling7bAlpha | Self::L8b | Self::SmolLM2_1BInstruct | Self::SmolLM2_360MInstruct | Self::Phi3 | Self::DeepseekR1Llama8b => false, Self::Zephyr7bAlpha | Self::Zephyr7bBeta => true, } } fn is_open_chat(&self) -> bool { match self { Self::L7b | Self::L13b | Self::L70b | Self::L7bChat | Self::L13bChat | Self::L70bChat | Self::L7bCode | Self::L13bCode | Self::L34bCode | Self::Leo7b | Self::Leo13b | Self::Mixtral | Self::MixtralInstruct | Self::Mistral7b | Self::Mistral7bInstruct | Self::Mistral7bInstructV02 | Self::Zephyr7bAlpha | Self::Zephyr7bBeta | Self::L8b | Self::SmolLM2_1BInstruct | Self::SmolLM2_360MInstruct | Self::Phi3 | Self::DeepseekR1Llama8b => false, Self::OpenChat35 | Self::Starling7bAlpha => true, } } fn is_deepseek(&self) -> bool { match self { Self::L7b | Self::L13b | Self::L70b | Self::L7bChat | Self::L13bChat | Self::L70bChat | Self::L7bCode | Self::L13bCode | Self::L34bCode | Self::Leo7b | Self::Leo13b | Self::Mixtral | Self::MixtralInstruct | Self::Mistral7b | Self::Mistral7bInstruct | Self::Mistral7bInstructV02 | Self::Zephyr7bAlpha | Self::Zephyr7bBeta | Self::L8b | Self::SmolLM2_1BInstruct | Self::SmolLM2_360MInstruct | Self::Phi3 | Self::OpenChat35 | Self::Starling7bAlpha => false, Self::DeepseekR1Llama8b => true, } } fn tokenizer_repo(&self) -> &'static str { match self { Self::L7b | Self::L13b | Self::L70b | Self::L7bChat | Self::L13bChat | Self::L70bChat | Self::L7bCode | Self::L13bCode | Self::L34bCode => "hf-internal-testing/llama-tokenizer", Self::Leo7b => "LeoLM/leo-hessianai-7b", Self::Leo13b => "LeoLM/leo-hessianai-13b", Self::Mixtral => "mistralai/Mixtral-8x7B-v0.1", Self::MixtralInstruct => "mistralai/Mixtral-8x7B-Instruct-v0.1", Self::Mistral7b | Self::Mistral7bInstruct | Self::Mistral7bInstructV02 | Self::Zephyr7bAlpha | Self::Zephyr7bBeta => "mistralai/Mistral-7B-v0.1", Self::OpenChat35 => "openchat/openchat_3.5", Self::Starling7bAlpha => "berkeley-nest/Starling-LM-7B-alpha", Self::L8b => "meta-llama/Meta-Llama-3-8B", Self::Phi3 => "microsoft/Phi-3-mini-4k-instruct", Self::SmolLM2_360MInstruct => "HuggingFaceTB/SmolLM2-360M-Instruct", Self::SmolLM2_1BInstruct => "HuggingFaceTB/SmolLM2-1.7B-Instruct", Self::DeepseekR1Llama8b => "deepseek-ai/DeepSeek-R1-Distill-Llama-8B", } } } #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] struct Args { /// GGML/GGUF file to load, typically a .bin/.gguf file generated by the quantize command from llama.cpp #[arg(long)] model: Option<String>, /// The initial prompt, use 'interactive' for entering multiple prompts in an interactive way /// and 'chat' for an interactive model where history of previous prompts and generated tokens /// is preserved. #[arg(long)] prompt: Option<String>, /// The length of the sample to generate (in tokens). #[arg(short = 'n', long, default_value_t = 1000)] sample_len: usize, /// The tokenizer config in json format. #[arg(long)] tokenizer: Option<String>, /// The temperature used to generate samples, use 0 for greedy sampling. #[arg(long, default_value_t = 0.8)] temperature: f64, /// Nucleus sampling probability cutoff. #[arg(long)] top_p: Option<f64>, /// Only sample among the top K samples. #[arg(long)] top_k: Option<usize>, /// The seed to use when generating random samples. #[arg(long, default_value_t = 299792458)] seed: u64, /// Enable tracing (generates a trace-timestamp.json file). #[arg(long)] tracing: bool, /// Display the token for the specified prompt. #[arg(long)] verbose_prompt: bool, /// Process prompt elements separately. #[arg(long)] split_prompt: bool, /// Run on CPU rather than GPU even if a GPU is available. #[arg(long)] cpu: bool, /// Penalty to be applied for repeating tokens, 1. means no penalty. #[arg(long, default_value_t = 1.1)] repeat_penalty: f32, /// The context size to consider for the repeat penalty. #[arg(long, default_value_t = 64)] repeat_last_n: usize, /// The model size to use. #[arg(long, default_value = "7b")] which: Which, /// Group-Query Attention, use 8 for the 70B version of LLaMAv2. #[arg(long)] gqa: Option<usize>, /// Use the slower dmmv cuda kernel. #[arg(long)] force_dmmv: bool, } impl Args { fn tokenizer(&self) -> anyhow::Result<Tokenizer> { let tokenizer_path = match &self.tokenizer { Some(config) => std::path::PathBuf::from(config), None => { let api = hf_hub::api::sync::Api::new()?; let repo = self.which.tokenizer_repo(); let api = api.model(repo.to_string()); api.get("tokenizer.json")? } }; Tokenizer::from_file(tokenizer_path).map_err(anyhow::Error::msg) } fn model(&self) -> anyhow::Result<std::path::PathBuf> { let model_path = match &self.model { Some(config) => std::path::PathBuf::from(config), None => { let (repo, filename) = match self.which { Which::L7b => ("TheBloke/Llama-2-7B-GGML", "llama-2-7b.ggmlv3.q4_0.bin"), Which::L13b => ("TheBloke/Llama-2-13B-GGML", "llama-2-13b.ggmlv3.q4_0.bin"), Which::L70b => ("TheBloke/Llama-2-70B-GGML", "llama-2-70b.ggmlv3.q4_0.bin"), Which::L7bChat => ( "TheBloke/Llama-2-7B-Chat-GGML", "llama-2-7b-chat.ggmlv3.q4_0.bin", ), Which::L13bChat => ( "TheBloke/Llama-2-13B-Chat-GGML", "llama-2-13b-chat.ggmlv3.q4_0.bin", ), Which::L70bChat => ( "TheBloke/Llama-2-70B-Chat-GGML", "llama-2-70b-chat.ggmlv3.q4_0.bin", ), Which::L7bCode => ("TheBloke/CodeLlama-7B-GGUF", "codellama-7b.Q8_0.gguf"), Which::L13bCode => ("TheBloke/CodeLlama-13B-GGUF", "codellama-13b.Q8_0.gguf"), Which::L34bCode => ("TheBloke/CodeLlama-34B-GGUF", "codellama-34b.Q8_0.gguf"), Which::Leo7b => ( "TheBloke/leo-hessianai-7B-GGUF", "leo-hessianai-7b.Q4_K_M.gguf", ), Which::Leo13b => ( "TheBloke/leo-hessianai-13B-GGUF", "leo-hessianai-13b.Q4_K_M.gguf", ), Which::Mixtral => ( "TheBloke/Mixtral-8x7B-v0.1-GGUF", "mixtral-8x7b-v0.1.Q4_K_M.gguf", ), Which::MixtralInstruct => ( "TheBloke/Mixtral-8x7B-Instruct-v0.1-GGUF", "mixtral-8x7b-instruct-v0.1.Q4_K_M.gguf", ), Which::Mistral7b => ( "TheBloke/Mistral-7B-v0.1-GGUF", "mistral-7b-v0.1.Q4_K_S.gguf", ), Which::Mistral7bInstruct => ( "TheBloke/Mistral-7B-Instruct-v0.1-GGUF", "mistral-7b-instruct-v0.1.Q4_K_S.gguf", ), Which::Mistral7bInstructV02 => ( "TheBloke/Mistral-7B-Instruct-v0.2-GGUF", "mistral-7b-instruct-v0.2.Q4_K_S.gguf", ), Which::Zephyr7bAlpha => ( "TheBloke/zephyr-7B-alpha-GGUF", "zephyr-7b-alpha.Q4_K_M.gguf", ), Which::Zephyr7bBeta => { ("TheBloke/zephyr-7B-beta-GGUF", "zephyr-7b-beta.Q4_K_M.gguf") } Which::OpenChat35 => ("TheBloke/openchat_3.5-GGUF", "openchat_3.5.Q4_K_M.gguf"), Which::Starling7bAlpha => ( "TheBloke/Starling-LM-7B-alpha-GGUF", "starling-lm-7b-alpha.Q4_K_M.gguf", ), // TODO: swap to TheBloke model when available Which::L8b => ( "QuantFactory/Meta-Llama-3-8B-GGUF", "Meta-Llama-3-8B.Q4_K_S.gguf", ), Which::Phi3 => ( "microsoft/Phi-3-mini-4k-instruct-gguf", "Phi-3-mini-4k-instruct-q4.gguf", ), Which::SmolLM2_360MInstruct => ( "HuggingFaceTB/SmolLM2-360M-Instruct-GGUF", "smollm2-360m-instruct-q8_0.gguf", ), Which::SmolLM2_1BInstruct => ( "HuggingFaceTB/SmolLM2-1.7B-Instruct-GGUF", "smollm2-1.7b-instruct-q4_k_m.gguf", ), Which::DeepseekR1Llama8b => ( "unsloth/DeepSeek-R1-Distill-Llama-8B-GGUF", "DeepSeek-R1-Distill-Llama-8B-Q4_K_M.gguf", ), }; let revision = if self.which == Which::Phi3 { "5eef2ce24766d31909c0b269fe90c817a8f263fb" } else { "main" }; let api = hf_hub::api::sync::Api::new()?; api.repo(hf_hub::Repo::with_revision( repo.to_string(), hf_hub::RepoType::Model, revision.to_string(), )) .get(filename)? } }; Ok(model_path) } } fn format_size(size_in_bytes: usize) -> String { if size_in_bytes < 1_000 { format!("{size_in_bytes}B") } else if size_in_bytes < 1_000_000 { format!("{:.2}KB", size_in_bytes as f64 / 1e3) } else if size_in_bytes < 1_000_000_000 { format!("{:.2}MB", size_in_bytes as f64 / 1e6) } else { format!("{:.2}GB", size_in_bytes as f64 / 1e9) } } fn main() -> anyhow::Result<()> { use tracing_chrome::ChromeLayerBuilder; use tracing_subscriber::prelude::*; let args = Args::parse(); #[cfg(feature = "cuda")] candle::quantized::cuda::set_force_dmmv(args.force_dmmv); candle::cuda::set_gemm_reduced_precision_f16(true); candle::cuda::set_gemm_reduced_precision_bf16(true); 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, args.repeat_penalty, args.repeat_last_n ); let model_path = args.model()?; let mut file = std::fs::File::open(&model_path)?; let start = std::time::Instant::now(); let device = candle_examples::device(args.cpu)?; let mut model = match model_path.extension().and_then(|v| v.to_str()) { Some("gguf") => { let model = gguf_file::Content::read(&mut file).map_err(|e| e.with_path(model_path))?; let mut total_size_in_bytes = 0; for (_, tensor) in model.tensor_infos.iter() { let elem_count = tensor.shape.elem_count(); total_size_in_bytes += elem_count * tensor.ggml_dtype.type_size() / tensor.ggml_dtype.block_size(); } println!( "loaded {:?} tensors ({}) in {:.2}s", model.tensor_infos.len(), &format_size(total_size_in_bytes), start.elapsed().as_secs_f32(), ); ModelWeights::from_gguf(model, &mut file, &device)? } Some("ggml" | "bin") | Some(_) | None => { let model = ggml_file::Content::read(&mut file, &device) .map_err(|e| e.with_path(model_path))?; let mut total_size_in_bytes = 0; for (_, tensor) in model.tensors.iter() { let elem_count = tensor.shape().elem_count(); total_size_in_bytes += elem_count * tensor.dtype().type_size() / tensor.dtype().block_size(); } println!( "loaded {:?} tensors ({}) in {:.2}s", model.tensors.len(), &format_size(total_size_in_bytes), start.elapsed().as_secs_f32(), ); println!("params: {:?}", model.hparams); let default_gqa = match args.which { Which::L7b | Which::L13b | Which::L7bChat | Which::L13bChat | Which::L7bCode | Which::L13bCode | Which::L34bCode | Which::Leo7b | Which::Leo13b | Which::L8b | Which::SmolLM2_1BInstruct | Which::SmolLM2_360MInstruct | Which::DeepseekR1Llama8b | Which::Phi3 => 1, Which::Mixtral | Which::MixtralInstruct | Which::Mistral7b | Which::Mistral7bInstruct | Which::Mistral7bInstructV02 | Which::Zephyr7bAlpha | Which::Zephyr7bBeta | Which::L70b | Which::L70bChat | Which::OpenChat35 | Which::Starling7bAlpha => 8, }; ModelWeights::from_ggml(model, args.gqa.unwrap_or(default_gqa))? } }; println!("model built"); let tokenizer = args.tokenizer()?; let mut tos = TokenOutputStream::new(tokenizer); let prompt = match args.prompt.as_deref() { Some("chat") => Prompt::Chat, Some("interactive") => Prompt::Interactive, Some(s) => Prompt::One(s.to_string()), None => Prompt::One(DEFAULT_PROMPT.to_string()), }; let mut pre_prompt_tokens = vec![]; for prompt_index in 0.. { let prompt_str = match &prompt { Prompt::One(prompt) => prompt.clone(), Prompt::Interactive | Prompt::Chat => { let is_interactive = matches!(prompt, Prompt::Interactive); print!("> "); std::io::stdout().flush()?; let mut prompt = String::new(); std::io::stdin().read_line(&mut prompt)?; if prompt.ends_with('\n') { prompt.pop(); if prompt.ends_with('\r') { prompt.pop(); } } if args.which.is_open_chat() { format!("GPT4 Correct User: {prompt}<|end_of_turn|>GPT4 Correct Assistant:") } else if args.which.is_zephyr() { if prompt_index == 0 || is_interactive { format!("<|system|>\n</s>\n<|user|>\n{prompt}</s>\n<|assistant|>",) } else { format!("<|user|>\n{prompt}</s>\n<|assistant|>") } } else if args.which.is_mistral() { format!("[INST] {prompt} [/INST]") } else if args.which.is_deepseek() { format!("<|User|>{prompt}<|Assistant|>") } else { prompt } } }; print!("{}", &prompt_str); let tokens = tos .tokenizer() .encode(prompt_str, true) .map_err(anyhow::Error::msg)?; if args.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 prompt_tokens = [&pre_prompt_tokens, tokens.get_ids()].concat(); let to_sample = args.sample_len.saturating_sub(1); let prompt_tokens = if prompt_tokens.len() + to_sample > model::MAX_SEQ_LEN - 10 { let to_remove = prompt_tokens.len() + to_sample + 10 - model::MAX_SEQ_LEN; prompt_tokens[prompt_tokens.len().saturating_sub(to_remove)..].to_vec() } else { prompt_tokens }; let mut all_tokens = vec![]; let mut logits_processor = { let temperature = args.temperature; let sampling = if temperature <= 0. { Sampling::ArgMax } else { match (args.top_k, args.top_p) { (None, None) => Sampling::All { temperature }, (Some(k), None) => Sampling::TopK { k, temperature }, (None, Some(p)) => Sampling::TopP { p, temperature }, (Some(k), Some(p)) => Sampling::TopKThenTopP { k, p, temperature }, } }; LogitsProcessor::from_sampling(args.seed, sampling) }; let start_prompt_processing = std::time::Instant::now(); let mut next_token = if !args.split_prompt { let input = Tensor::new(prompt_tokens.as_slice(), &device)?.unsqueeze(0)?; let logits = model.forward(&input, 0)?; let logits = logits.squeeze(0)?; logits_processor.sample(&logits)? } else { let mut next_token = 0; for (pos, token) in prompt_tokens.iter().enumerate() { let input = Tensor::new(&[*token], &device)?.unsqueeze(0)?; let logits = model.forward(&input, pos)?; let logits = logits.squeeze(0)?; next_token = logits_processor.sample(&logits)? } next_token }; let prompt_dt = start_prompt_processing.elapsed(); all_tokens.push(next_token); if let Some(t) = tos.next_token(next_token)? { print!("{t}"); std::io::stdout().flush()?; } let eos_token = match args.which { Which::SmolLM2_360MInstruct | Which::SmolLM2_1BInstruct => "<|endoftext|>", Which::L8b => "<|end_of_text|>", Which::DeepseekR1Llama8b => "<|end▁of▁sentence|>", _ => match args.which.is_open_chat() { true => "<|end_of_turn|>", false => "</s>", }, }; let eos_token = *tos.tokenizer().get_vocab(true).get(eos_token).unwrap(); let start_post_prompt = std::time::Instant::now(); let mut sampled = 0; for index in 0..to_sample { let input = Tensor::new(&[next_token], &device)?.unsqueeze(0)?; let logits = model.forward(&input, prompt_tokens.len() + index)?; let logits = logits.squeeze(0)?; let logits = if args.repeat_penalty == 1. { logits } else { let start_at = all_tokens.len().saturating_sub(args.repeat_last_n); candle_transformers::utils::apply_repeat_penalty( &logits, args.repeat_penalty, &all_tokens[start_at..], )? }; next_token = logits_processor.sample(&logits)?; all_tokens.push(next_token); if let Some(t) = tos.next_token(next_token)? { print!("{t}"); std::io::stdout().flush()?; } sampled += 1; if next_token == eos_token { break; }; } if let Some(rest) = tos.decode_rest().map_err(candle::Error::msg)? { print!("{rest}"); } std::io::stdout().flush()?; let dt = start_post_prompt.elapsed(); println!( "\n\n{:4} prompt tokens processed: {:.2} token/s", prompt_tokens.len(), prompt_tokens.len() as f64 / prompt_dt.as_secs_f64(), ); println!( "{sampled:4} tokens generated: {:.2} token/s", sampled as f64 / dt.as_secs_f64(), ); match prompt { Prompt::One(_) => break, Prompt::Interactive => {} Prompt::Chat => { pre_prompt_tokens = [prompt_tokens.as_slice(), all_tokens.as_slice()].concat() } } } Ok(()) }
candle/candle-examples/examples/quantized/main.rs/0
{ "file_path": "candle/candle-examples/examples/quantized/main.rs", "repo_id": "candle", "token_count": 14373 }
40
#[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::repvgg; #[derive(Clone, Copy, Debug, ValueEnum)] enum Which { A0, A1, A2, B0, B1, B2, B3, B1G4, B2G4, B3G4, } impl Which { fn model_filename(&self) -> String { let name = match self { Self::A0 => "a0", Self::A1 => "a1", Self::A2 => "a2", Self::B0 => "b0", Self::B1 => "b1", Self::B2 => "b2", Self::B3 => "b3", Self::B1G4 => "b1g4", Self::B2G4 => "b2g4", Self::B3G4 => "b3g4", }; format!("timm/repvgg_{name}.rvgg_in1k") } fn config(&self) -> repvgg::Config { match self { Self::A0 => repvgg::Config::a0(), Self::A1 => repvgg::Config::a1(), Self::A2 => repvgg::Config::a2(), Self::B0 => repvgg::Config::b0(), Self::B1 => repvgg::Config::b1(), Self::B2 => repvgg::Config::b2(), Self::B3 => repvgg::Config::b3(), Self::B1G4 => repvgg::Config::b1g4(), Self::B2G4 => repvgg::Config::b2g4(), Self::B3G4 => repvgg::Config::b3g4(), } } } #[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::A0)] 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 = repvgg::repvgg(&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/repvgg/main.rs/0
{ "file_path": "candle/candle-examples/examples/repvgg/main.rs", "repo_id": "candle", "token_count": 1524 }
41
# silero-vad: Voice Activity Detection [Silero VAD (v5)](https://github.com/snakers4/silero-vad) detects voice activity in streaming audio. This example uses the models available in the hugging face [onnx-community/silero-vad](https://huggingface.co/onnx-community/silero-vad). ## Running the example ### using arecord ```bash $ arecord -t raw -f S16_LE -r 16000 -c 1 -d 5 - | cargo run --example silero-vad --release --features onnx -- --sample-rate 16000 ``` ### using SoX ```bash $ rec -t raw -r 48000 -b 16 -c 1 -e signed-integer - trim 0 5 | sox -t raw -r 48000 -b 16 -c 1 -e signed-integer - -t raw -r 16000 -b 16 -c 1 -e signed-integer - | cargo run --example silero-vad --release --features onnx -- --sample-rate 16000 ```
candle/candle-examples/examples/silero-vad/README.md/0
{ "file_path": "candle/candle-examples/examples/silero-vad/README.md", "repo_id": "candle", "token_count": 266 }
42
# candle-voxtral: speech recognition An implementation of Voxtral speech recognition using candle. ## Running the example Run with the `cuda` feature for GPU acceleration: ```bash cargo run --example voxtral --features tekken,symphonia,rubato,cuda --release # you may also add the `cudnn` feature for extra performance # cargo run --example voxtral --features tekken,symphonia,rubato,cuda,cudnn --release ``` Remove the `cuda` feature to run on the CPU instead: ```bash cargo run --example voxtral --features tekken,symphonia,rubato --release # or pass the `--cpu` flag to force CPU usage # cargo run --example voxtral --features tekken,symphonia,rubato,cuda --release -- --cpu ``` ## Command line options - `--cpu`: Run on CPU rather than on GPU (default: false, uses GPU if available) - `--input`: Audio file path in wav format. If not provided, a sample file is automatically downloaded from the hub. - `--model-id`: Model to use (default: `mistralai/Voxtral-Mini-3B-2507`)
candle/candle-examples/examples/voxtral/README.md/0
{ "file_path": "candle/candle-examples/examples/voxtral/README.md", "repo_id": "candle", "token_count": 304 }
43
#[cfg(feature = "accelerate")] extern crate accelerate_src; #[cfg(feature = "mkl")] extern crate intel_mkl_src; use candle_transformers::models::stable_diffusion; use candle_transformers::models::wuerstchen; use anyhow::{Error as E, Result}; use candle::{DType, Device, IndexOp, Tensor}; use clap::Parser; use tokenizers::Tokenizer; const PRIOR_GUIDANCE_SCALE: f64 = 4.0; const RESOLUTION_MULTIPLE: f64 = 42.67; const LATENT_DIM_SCALE: f64 = 10.67; const PRIOR_CIN: usize = 16; const DECODER_CIN: usize = 4; #[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, #[arg(long)] use_flash_attn: 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 decoder weight file, in .safetensors format. #[arg(long, value_name = "FILE")] decoder_weights: Option<String>, /// The CLIP weight file, in .safetensors format. #[arg(long, value_name = "FILE")] clip_weights: Option<String>, /// The CLIP weight file used by the prior model, in .safetensors format. #[arg(long, value_name = "FILE")] prior_clip_weights: Option<String>, /// The prior weight file, in .safetensors format. #[arg(long, value_name = "FILE")] prior_weights: Option<String>, /// The VQGAN weight file, in .safetensors format. #[arg(long, value_name = "FILE")] vqgan_weights: Option<String>, #[arg(long, value_name = "FILE")] /// The file specifying the tokenizer to used for tokenization. tokenizer: Option<String>, #[arg(long, value_name = "FILE")] /// The file specifying the tokenizer to used for prior tokenization. prior_tokenizer: Option<String>, /// The number of samples to generate. #[arg(long, default_value_t = 1)] num_samples: i64, /// The name of the final image to generate. #[arg(long, value_name = "FILE", default_value = "sd_final.png")] final_image: String, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum ModelFile { Tokenizer, PriorTokenizer, Clip, PriorClip, Decoder, VqGan, Prior, } impl ModelFile { fn get(&self, filename: Option<String>) -> Result<std::path::PathBuf> { use hf_hub::api::sync::Api; match filename { Some(filename) => Ok(std::path::PathBuf::from(filename)), None => { let repo_main = "warp-ai/wuerstchen"; let repo_prior = "warp-ai/wuerstchen-prior"; let (repo, path) = match self { Self::Tokenizer => (repo_main, "tokenizer/tokenizer.json"), Self::PriorTokenizer => (repo_prior, "tokenizer/tokenizer.json"), Self::Clip => (repo_main, "text_encoder/model.safetensors"), Self::PriorClip => (repo_prior, "text_encoder/model.safetensors"), Self::Decoder => (repo_main, "decoder/diffusion_pytorch_model.safetensors"), Self::VqGan => (repo_main, "vqgan/diffusion_pytorch_model.safetensors"), Self::Prior => (repo_prior, "prior/diffusion_pytorch_model.safetensors"), }; let filename = Api::new()?.model(repo.to_string()).get(path)?; Ok(filename) } } } } fn output_filename( basename: &str, sample_idx: i64, num_samples: i64, 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}") } }, } } fn encode_prompt( prompt: &str, uncond_prompt: Option<&str>, tokenizer: std::path::PathBuf, clip_weights: std::path::PathBuf, clip_config: stable_diffusion::clip::Config, device: &Device, ) -> Result<Tensor> { let tokenizer = Tokenizer::from_file(tokenizer).map_err(E::msg)?; let pad_id = match &clip_config.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(); let tokens_len = tokens.len(); while tokens.len() < clip_config.max_position_embeddings { tokens.push(pad_id) } let tokens = Tensor::new(tokens.as_slice(), device)?.unsqueeze(0)?; println!("Building the clip transformer."); let text_model = stable_diffusion::build_clip_transformer(&clip_config, clip_weights, device, DType::F32)?; let text_embeddings = text_model.forward_with_mask(&tokens, tokens_len - 1)?; match uncond_prompt { None => Ok(text_embeddings), Some(uncond_prompt) => { let mut uncond_tokens = tokenizer .encode(uncond_prompt, true) .map_err(E::msg)? .get_ids() .to_vec(); let uncond_tokens_len = uncond_tokens.len(); while uncond_tokens.len() < clip_config.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_with_mask(&uncond_tokens, uncond_tokens_len - 1)?; let text_embeddings = Tensor::cat(&[text_embeddings, uncond_embeddings], 0)?; Ok(text_embeddings) } } } fn run(args: Args) -> Result<()> { use tracing_chrome::ChromeLayerBuilder; use tracing_subscriber::prelude::*; let Args { prompt, uncond_prompt, cpu, height, width, tokenizer, final_image, num_samples, clip_weights, prior_weights, vqgan_weights, decoder_weights, tracing, .. } = args; let _guard = if tracing { let (chrome_layer, guard) = ChromeLayerBuilder::new().build(); tracing_subscriber::registry().with(chrome_layer).init(); Some(guard) } else { None }; let device = candle_examples::device(cpu)?; let height = height.unwrap_or(1024); let width = width.unwrap_or(1024); let prior_text_embeddings = { let tokenizer = ModelFile::PriorTokenizer.get(args.prior_tokenizer)?; let weights = ModelFile::PriorClip.get(args.prior_clip_weights)?; encode_prompt( &prompt, Some(&uncond_prompt), tokenizer.clone(), weights, stable_diffusion::clip::Config::wuerstchen_prior(), &device, )? }; println!("generated prior text embeddings {prior_text_embeddings:?}"); let text_embeddings = { let tokenizer = ModelFile::Tokenizer.get(tokenizer)?; let weights = ModelFile::Clip.get(clip_weights)?; encode_prompt( &prompt, None, tokenizer.clone(), weights, stable_diffusion::clip::Config::wuerstchen(), &device, )? }; println!("generated text embeddings {text_embeddings:?}"); println!("Building the prior."); let b_size = 1; let image_embeddings = { // https://huggingface.co/warp-ai/wuerstchen-prior/blob/main/prior/config.json let latent_height = (height as f64 / RESOLUTION_MULTIPLE).ceil() as usize; let latent_width = (width as f64 / RESOLUTION_MULTIPLE).ceil() as usize; let mut latents = Tensor::randn( 0f32, 1f32, (b_size, PRIOR_CIN, latent_height, latent_width), &device, )?; let prior = { let file = ModelFile::Prior.get(prior_weights)?; let vb = unsafe { candle_nn::VarBuilder::from_mmaped_safetensors(&[file], DType::F32, &device)? }; wuerstchen::prior::WPrior::new( /* c_in */ PRIOR_CIN, /* c */ 1536, /* c_cond */ 1280, /* c_r */ 64, /* depth */ 32, /* nhead */ 24, args.use_flash_attn, vb, )? }; let prior_scheduler = wuerstchen::ddpm::DDPMWScheduler::new(60, Default::default())?; let timesteps = prior_scheduler.timesteps(); let timesteps = &timesteps[..timesteps.len() - 1]; println!("prior denoising"); for (index, &t) in timesteps.iter().enumerate() { let start_time = std::time::Instant::now(); let latent_model_input = Tensor::cat(&[&latents, &latents], 0)?; let ratio = (Tensor::ones(2, DType::F32, &device)? * t)?; let noise_pred = prior.forward(&latent_model_input, &ratio, &prior_text_embeddings)?; let noise_pred = noise_pred.chunk(2, 0)?; let (noise_pred_text, noise_pred_uncond) = (&noise_pred[0], &noise_pred[1]); let noise_pred = (noise_pred_uncond + ((noise_pred_text - noise_pred_uncond)? * PRIOR_GUIDANCE_SCALE)?)?; latents = prior_scheduler.step(&noise_pred, t, &latents)?; let dt = start_time.elapsed().as_secs_f32(); println!("step {}/{} done, {:.2}s", index + 1, timesteps.len(), dt); } ((latents * 42.)? - 1.)? }; println!("Building the vqgan."); let vqgan = { let file = ModelFile::VqGan.get(vqgan_weights)?; let vb = unsafe { candle_nn::VarBuilder::from_mmaped_safetensors(&[file], DType::F32, &device)? }; wuerstchen::paella_vq::PaellaVQ::new(vb)? }; println!("Building the decoder."); // https://huggingface.co/warp-ai/wuerstchen/blob/main/decoder/config.json let decoder = { let file = ModelFile::Decoder.get(decoder_weights)?; let vb = unsafe { candle_nn::VarBuilder::from_mmaped_safetensors(&[file], DType::F32, &device)? }; wuerstchen::diffnext::WDiffNeXt::new( /* c_in */ DECODER_CIN, /* c_out */ DECODER_CIN, /* c_r */ 64, /* c_cond */ 1024, /* clip_embd */ 1024, /* patch_size */ 2, args.use_flash_attn, vb, )? }; for idx in 0..num_samples { // https://huggingface.co/warp-ai/wuerstchen/blob/main/model_index.json let latent_height = (image_embeddings.dim(2)? as f64 * LATENT_DIM_SCALE) as usize; let latent_width = (image_embeddings.dim(3)? as f64 * LATENT_DIM_SCALE) as usize; let mut latents = Tensor::randn( 0f32, 1f32, (b_size, DECODER_CIN, latent_height, latent_width), &device, )?; println!("diffusion process with prior {image_embeddings:?}"); let scheduler = wuerstchen::ddpm::DDPMWScheduler::new(12, Default::default())?; let timesteps = scheduler.timesteps(); let timesteps = &timesteps[..timesteps.len() - 1]; for (index, &t) in timesteps.iter().enumerate() { let start_time = std::time::Instant::now(); let ratio = (Tensor::ones(1, DType::F32, &device)? * t)?; let noise_pred = decoder.forward(&latents, &ratio, &image_embeddings, Some(&text_embeddings))?; latents = scheduler.step(&noise_pred, t, &latents)?; let dt = start_time.elapsed().as_secs_f32(); println!("step {}/{} done, {:.2}s", index + 1, timesteps.len(), dt); } println!( "Generating the final image for sample {}/{}.", idx + 1, num_samples ); let image = vqgan.decode(&(&latents * 0.3764)?)?; let image = (image.clamp(0f32, 1f32)? * 255.)? .to_dtype(DType::U8)? .i(0)?; let image_filename = output_filename(&final_image, idx + 1, num_samples, None); candle_examples::save_image(&image, image_filename)? } Ok(()) } fn main() -> Result<()> { let args = Args::parse(); run(args) }
candle/candle-examples/examples/wuerstchen/main.rs/0
{ "file_path": "candle/candle-examples/examples/wuerstchen/main.rs", "repo_id": "candle", "token_count": 6372 }
44
use candle::{DType, IndexOp, Result, Tensor, D}; use candle_nn::{batch_norm, conv2d, conv2d_no_bias, Conv2d, Conv2dConfig, Module, VarBuilder}; #[derive(Clone, Copy, PartialEq, Debug)] pub struct Multiples { depth: f64, width: f64, ratio: f64, } impl Multiples { pub fn n() -> Self { Self { depth: 0.33, width: 0.25, ratio: 2.0, } } pub fn s() -> Self { Self { depth: 0.33, width: 0.50, ratio: 2.0, } } pub fn m() -> Self { Self { depth: 0.67, width: 0.75, ratio: 1.5, } } pub fn l() -> Self { Self { depth: 1.00, width: 1.00, ratio: 1.0, } } pub fn x() -> Self { Self { depth: 1.00, width: 1.25, ratio: 1.0, } } fn filters(&self) -> (usize, usize, usize) { let f1 = (256. * self.width) as usize; let f2 = (512. * self.width) as usize; let f3 = (512. * self.width * self.ratio) as usize; (f1, f2, f3) } } #[derive(Debug)] struct Upsample { scale_factor: usize, } impl Upsample { fn new(scale_factor: usize) -> Result<Self> { Ok(Upsample { scale_factor }) } } impl Module for Upsample { fn forward(&self, xs: &Tensor) -> candle::Result<Tensor> { let (_b_size, _channels, h, w) = xs.dims4()?; xs.upsample_nearest2d(self.scale_factor * h, self.scale_factor * w) } } #[derive(Debug)] struct ConvBlock { conv: Conv2d, span: tracing::Span, } impl ConvBlock { fn load( vb: VarBuilder, c1: usize, c2: usize, k: usize, stride: usize, padding: Option<usize>, ) -> Result<Self> { let padding = padding.unwrap_or(k / 2); let cfg = Conv2dConfig { padding, stride, groups: 1, dilation: 1, cudnn_fwd_algo: None, }; let bn = batch_norm(c2, 1e-3, vb.pp("bn"))?; let conv = conv2d_no_bias(c1, c2, k, cfg, vb.pp("conv"))?.absorb_bn(&bn)?; Ok(Self { conv, span: tracing::span!(tracing::Level::TRACE, "conv-block"), }) } } impl Module for ConvBlock { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let xs = self.conv.forward(xs)?; candle_nn::ops::silu(&xs) } } #[derive(Debug)] struct Bottleneck { cv1: ConvBlock, cv2: ConvBlock, residual: bool, span: tracing::Span, } impl Bottleneck { fn load(vb: VarBuilder, c1: usize, c2: usize, shortcut: bool) -> Result<Self> { let channel_factor = 1.; let c_ = (c2 as f64 * channel_factor) as usize; let cv1 = ConvBlock::load(vb.pp("cv1"), c1, c_, 3, 1, None)?; let cv2 = ConvBlock::load(vb.pp("cv2"), c_, c2, 3, 1, None)?; let residual = c1 == c2 && shortcut; Ok(Self { cv1, cv2, residual, span: tracing::span!(tracing::Level::TRACE, "bottleneck"), }) } } impl Module for Bottleneck { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let ys = self.cv2.forward(&self.cv1.forward(xs)?)?; if self.residual { xs + ys } else { Ok(ys) } } } #[derive(Debug)] struct C2f { cv1: ConvBlock, cv2: ConvBlock, bottleneck: Vec<Bottleneck>, span: tracing::Span, } impl C2f { fn load(vb: VarBuilder, c1: usize, c2: usize, n: usize, shortcut: bool) -> Result<Self> { let c = (c2 as f64 * 0.5) as usize; let cv1 = ConvBlock::load(vb.pp("cv1"), c1, 2 * c, 1, 1, None)?; let cv2 = ConvBlock::load(vb.pp("cv2"), (2 + n) * c, c2, 1, 1, None)?; let mut bottleneck = Vec::with_capacity(n); for idx in 0..n { let b = Bottleneck::load(vb.pp(format!("bottleneck.{idx}")), c, c, shortcut)?; bottleneck.push(b) } Ok(Self { cv1, cv2, bottleneck, span: tracing::span!(tracing::Level::TRACE, "c2f"), }) } } impl Module for C2f { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let ys = self.cv1.forward(xs)?; let mut ys = ys.chunk(2, 1)?; for m in self.bottleneck.iter() { ys.push(m.forward(ys.last().unwrap())?) } let zs = Tensor::cat(ys.as_slice(), 1)?; self.cv2.forward(&zs) } } #[derive(Debug)] struct Sppf { cv1: ConvBlock, cv2: ConvBlock, k: usize, span: tracing::Span, } impl Sppf { fn load(vb: VarBuilder, c1: usize, c2: usize, k: usize) -> Result<Self> { let c_ = c1 / 2; let cv1 = ConvBlock::load(vb.pp("cv1"), c1, c_, 1, 1, None)?; let cv2 = ConvBlock::load(vb.pp("cv2"), c_ * 4, c2, 1, 1, None)?; Ok(Self { cv1, cv2, k, span: tracing::span!(tracing::Level::TRACE, "sppf"), }) } } impl Module for Sppf { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let (_, _, _, _) = xs.dims4()?; let xs = self.cv1.forward(xs)?; let xs2 = xs .pad_with_zeros(2, self.k / 2, self.k / 2)? .pad_with_zeros(3, self.k / 2, self.k / 2)? .max_pool2d_with_stride(self.k, 1)?; let xs3 = xs2 .pad_with_zeros(2, self.k / 2, self.k / 2)? .pad_with_zeros(3, self.k / 2, self.k / 2)? .max_pool2d_with_stride(self.k, 1)?; let xs4 = xs3 .pad_with_zeros(2, self.k / 2, self.k / 2)? .pad_with_zeros(3, self.k / 2, self.k / 2)? .max_pool2d_with_stride(self.k, 1)?; self.cv2.forward(&Tensor::cat(&[&xs, &xs2, &xs3, &xs4], 1)?) } } #[derive(Debug)] struct Dfl { conv: Conv2d, num_classes: usize, span: tracing::Span, } impl Dfl { fn load(vb: VarBuilder, num_classes: usize) -> Result<Self> { let conv = conv2d_no_bias(num_classes, 1, 1, Default::default(), vb.pp("conv"))?; Ok(Self { conv, num_classes, span: tracing::span!(tracing::Level::TRACE, "dfl"), }) } } impl Module for Dfl { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let (b_sz, _channels, anchors) = xs.dims3()?; let xs = xs .reshape((b_sz, 4, self.num_classes, anchors))? .transpose(2, 1)?; let xs = candle_nn::ops::softmax(&xs, 1)?; self.conv.forward(&xs)?.reshape((b_sz, 4, anchors)) } } #[derive(Debug)] struct DarkNet { b1_0: ConvBlock, b1_1: ConvBlock, b2_0: C2f, b2_1: ConvBlock, b2_2: C2f, b3_0: ConvBlock, b3_1: C2f, b4_0: ConvBlock, b4_1: C2f, b5: Sppf, span: tracing::Span, } impl DarkNet { fn load(vb: VarBuilder, m: Multiples) -> Result<Self> { let (w, r, d) = (m.width, m.ratio, m.depth); let b1_0 = ConvBlock::load(vb.pp("b1.0"), 3, (64. * w) as usize, 3, 2, Some(1))?; let b1_1 = ConvBlock::load( vb.pp("b1.1"), (64. * w) as usize, (128. * w) as usize, 3, 2, Some(1), )?; let b2_0 = C2f::load( vb.pp("b2.0"), (128. * w) as usize, (128. * w) as usize, (3. * d).round() as usize, true, )?; let b2_1 = ConvBlock::load( vb.pp("b2.1"), (128. * w) as usize, (256. * w) as usize, 3, 2, Some(1), )?; let b2_2 = C2f::load( vb.pp("b2.2"), (256. * w) as usize, (256. * w) as usize, (6. * d).round() as usize, true, )?; let b3_0 = ConvBlock::load( vb.pp("b3.0"), (256. * w) as usize, (512. * w) as usize, 3, 2, Some(1), )?; let b3_1 = C2f::load( vb.pp("b3.1"), (512. * w) as usize, (512. * w) as usize, (6. * d).round() as usize, true, )?; let b4_0 = ConvBlock::load( vb.pp("b4.0"), (512. * w) as usize, (512. * w * r) as usize, 3, 2, Some(1), )?; let b4_1 = C2f::load( vb.pp("b4.1"), (512. * w * r) as usize, (512. * w * r) as usize, (3. * d).round() as usize, true, )?; let b5 = Sppf::load( vb.pp("b5.0"), (512. * w * r) as usize, (512. * w * r) as usize, 5, )?; Ok(Self { b1_0, b1_1, b2_0, b2_1, b2_2, b3_0, b3_1, b4_0, b4_1, b5, span: tracing::span!(tracing::Level::TRACE, "darknet"), }) } fn forward(&self, xs: &Tensor) -> Result<(Tensor, Tensor, Tensor)> { let _enter = self.span.enter(); let x1 = self.b1_1.forward(&self.b1_0.forward(xs)?)?; let x2 = self .b2_2 .forward(&self.b2_1.forward(&self.b2_0.forward(&x1)?)?)?; let x3 = self.b3_1.forward(&self.b3_0.forward(&x2)?)?; let x4 = self.b4_1.forward(&self.b4_0.forward(&x3)?)?; let x5 = self.b5.forward(&x4)?; Ok((x2, x3, x5)) } } #[derive(Debug)] struct YoloV8Neck { up: Upsample, n1: C2f, n2: C2f, n3: ConvBlock, n4: C2f, n5: ConvBlock, n6: C2f, span: tracing::Span, } impl YoloV8Neck { fn load(vb: VarBuilder, m: Multiples) -> Result<Self> { let up = Upsample::new(2)?; let (w, r, d) = (m.width, m.ratio, m.depth); let n = (3. * d).round() as usize; let n1 = C2f::load( vb.pp("n1"), (512. * w * (1. + r)) as usize, (512. * w) as usize, n, false, )?; let n2 = C2f::load( vb.pp("n2"), (768. * w) as usize, (256. * w) as usize, n, false, )?; let n3 = ConvBlock::load( vb.pp("n3"), (256. * w) as usize, (256. * w) as usize, 3, 2, Some(1), )?; let n4 = C2f::load( vb.pp("n4"), (768. * w) as usize, (512. * w) as usize, n, false, )?; let n5 = ConvBlock::load( vb.pp("n5"), (512. * w) as usize, (512. * w) as usize, 3, 2, Some(1), )?; let n6 = C2f::load( vb.pp("n6"), (512. * w * (1. + r)) as usize, (512. * w * r) as usize, n, false, )?; Ok(Self { up, n1, n2, n3, n4, n5, n6, span: tracing::span!(tracing::Level::TRACE, "neck"), }) } fn forward(&self, p3: &Tensor, p4: &Tensor, p5: &Tensor) -> Result<(Tensor, Tensor, Tensor)> { let _enter = self.span.enter(); let x = self .n1 .forward(&Tensor::cat(&[&self.up.forward(p5)?, p4], 1)?)?; let head_1 = self .n2 .forward(&Tensor::cat(&[&self.up.forward(&x)?, p3], 1)?)?; let head_2 = self .n4 .forward(&Tensor::cat(&[&self.n3.forward(&head_1)?, &x], 1)?)?; let head_3 = self .n6 .forward(&Tensor::cat(&[&self.n5.forward(&head_2)?, p5], 1)?)?; Ok((head_1, head_2, head_3)) } } #[derive(Debug)] struct DetectionHead { dfl: Dfl, cv2: [(ConvBlock, ConvBlock, Conv2d); 3], cv3: [(ConvBlock, ConvBlock, Conv2d); 3], ch: usize, no: usize, span: tracing::Span, } #[derive(Debug)] struct PoseHead { detect: DetectionHead, cv4: [(ConvBlock, ConvBlock, Conv2d); 3], kpt: (usize, usize), span: tracing::Span, } fn make_anchors( xs0: &Tensor, xs1: &Tensor, xs2: &Tensor, (s0, s1, s2): (usize, usize, usize), grid_cell_offset: f64, ) -> Result<(Tensor, Tensor)> { let dev = xs0.device(); let mut anchor_points = vec![]; let mut stride_tensor = vec![]; for (xs, stride) in [(xs0, s0), (xs1, s1), (xs2, s2)] { // xs is only used to extract the h and w dimensions. let (_, _, h, w) = xs.dims4()?; let sx = (Tensor::arange(0, w as u32, dev)?.to_dtype(DType::F32)? + grid_cell_offset)?; let sy = (Tensor::arange(0, h as u32, dev)?.to_dtype(DType::F32)? + grid_cell_offset)?; let sx = sx .reshape((1, sx.elem_count()))? .repeat((h, 1))? .flatten_all()?; let sy = sy .reshape((sy.elem_count(), 1))? .repeat((1, w))? .flatten_all()?; anchor_points.push(Tensor::stack(&[&sx, &sy], D::Minus1)?); stride_tensor.push((Tensor::ones(h * w, DType::F32, dev)? * stride as f64)?); } let anchor_points = Tensor::cat(anchor_points.as_slice(), 0)?; let stride_tensor = Tensor::cat(stride_tensor.as_slice(), 0)?.unsqueeze(1)?; Ok((anchor_points, stride_tensor)) } fn dist2bbox(distance: &Tensor, anchor_points: &Tensor) -> Result<Tensor> { let chunks = distance.chunk(2, 1)?; let lt = &chunks[0]; let rb = &chunks[1]; let x1y1 = anchor_points.sub(lt)?; let x2y2 = anchor_points.add(rb)?; let c_xy = ((&x1y1 + &x2y2)? * 0.5)?; let wh = (&x2y2 - &x1y1)?; Tensor::cat(&[c_xy, wh], 1) } struct DetectionHeadOut { pred: Tensor, anchors: Tensor, strides: Tensor, } impl DetectionHead { fn load(vb: VarBuilder, nc: usize, filters: (usize, usize, usize)) -> Result<Self> { let ch = 16; let dfl = Dfl::load(vb.pp("dfl"), ch)?; let c1 = usize::max(filters.0, nc); let c2 = usize::max(filters.0 / 4, ch * 4); let cv3 = [ Self::load_cv3(vb.pp("cv3.0"), c1, nc, filters.0)?, Self::load_cv3(vb.pp("cv3.1"), c1, nc, filters.1)?, Self::load_cv3(vb.pp("cv3.2"), c1, nc, filters.2)?, ]; let cv2 = [ Self::load_cv2(vb.pp("cv2.0"), c2, ch, filters.0)?, Self::load_cv2(vb.pp("cv2.1"), c2, ch, filters.1)?, Self::load_cv2(vb.pp("cv2.2"), c2, ch, filters.2)?, ]; let no = nc + ch * 4; Ok(Self { dfl, cv2, cv3, ch, no, span: tracing::span!(tracing::Level::TRACE, "detection-head"), }) } fn load_cv3( vb: VarBuilder, c1: usize, nc: usize, filter: usize, ) -> Result<(ConvBlock, ConvBlock, Conv2d)> { let block0 = ConvBlock::load(vb.pp("0"), filter, c1, 3, 1, None)?; let block1 = ConvBlock::load(vb.pp("1"), c1, c1, 3, 1, None)?; let conv = conv2d(c1, nc, 1, Default::default(), vb.pp("2"))?; Ok((block0, block1, conv)) } fn load_cv2( vb: VarBuilder, c2: usize, ch: usize, filter: usize, ) -> Result<(ConvBlock, ConvBlock, Conv2d)> { let block0 = ConvBlock::load(vb.pp("0"), filter, c2, 3, 1, None)?; let block1 = ConvBlock::load(vb.pp("1"), c2, c2, 3, 1, None)?; let conv = conv2d(c2, 4 * ch, 1, Default::default(), vb.pp("2"))?; Ok((block0, block1, conv)) } fn forward(&self, xs0: &Tensor, xs1: &Tensor, xs2: &Tensor) -> Result<DetectionHeadOut> { let _enter = self.span.enter(); let forward_cv = |xs, i: usize| { let xs_2 = self.cv2[i].0.forward(xs)?; let xs_2 = self.cv2[i].1.forward(&xs_2)?; let xs_2 = self.cv2[i].2.forward(&xs_2)?; let xs_3 = self.cv3[i].0.forward(xs)?; let xs_3 = self.cv3[i].1.forward(&xs_3)?; let xs_3 = self.cv3[i].2.forward(&xs_3)?; Tensor::cat(&[&xs_2, &xs_3], 1) }; let xs0 = forward_cv(xs0, 0)?; let xs1 = forward_cv(xs1, 1)?; let xs2 = forward_cv(xs2, 2)?; let (anchors, strides) = make_anchors(&xs0, &xs1, &xs2, (8, 16, 32), 0.5)?; let anchors = anchors.transpose(0, 1)?.unsqueeze(0)?; let strides = strides.transpose(0, 1)?; let reshape = |xs: &Tensor| { let d = xs.dim(0)?; let el = xs.elem_count(); xs.reshape((d, self.no, el / (d * self.no))) }; let ys0 = reshape(&xs0)?; let ys1 = reshape(&xs1)?; let ys2 = reshape(&xs2)?; let x_cat = Tensor::cat(&[ys0, ys1, ys2], 2)?; let box_ = x_cat.i((.., ..self.ch * 4))?; let cls = x_cat.i((.., self.ch * 4..))?; let dbox = dist2bbox(&self.dfl.forward(&box_)?, &anchors)?; let dbox = dbox.broadcast_mul(&strides)?; let pred = Tensor::cat(&[dbox, candle_nn::ops::sigmoid(&cls)?], 1)?; Ok(DetectionHeadOut { pred, anchors, strides, }) } } impl PoseHead { // kpt: keypoints, (17, 3) // nc: num-classes, 80 fn load( vb: VarBuilder, nc: usize, kpt: (usize, usize), filters: (usize, usize, usize), ) -> Result<Self> { let detect = DetectionHead::load(vb.clone(), nc, filters)?; let nk = kpt.0 * kpt.1; let c4 = usize::max(filters.0 / 4, nk); let cv4 = [ Self::load_cv4(vb.pp("cv4.0"), c4, nk, filters.0)?, Self::load_cv4(vb.pp("cv4.1"), c4, nk, filters.1)?, Self::load_cv4(vb.pp("cv4.2"), c4, nk, filters.2)?, ]; Ok(Self { detect, cv4, kpt, span: tracing::span!(tracing::Level::TRACE, "pose-head"), }) } fn load_cv4( vb: VarBuilder, c1: usize, nc: usize, filter: usize, ) -> Result<(ConvBlock, ConvBlock, Conv2d)> { let block0 = ConvBlock::load(vb.pp("0"), filter, c1, 3, 1, None)?; let block1 = ConvBlock::load(vb.pp("1"), c1, c1, 3, 1, None)?; let conv = conv2d(c1, nc, 1, Default::default(), vb.pp("2"))?; Ok((block0, block1, conv)) } fn forward(&self, xs0: &Tensor, xs1: &Tensor, xs2: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let d = self.detect.forward(xs0, xs1, xs2)?; let forward_cv = |xs: &Tensor, i: usize| { let (b_sz, _, h, w) = xs.dims4()?; let xs = self.cv4[i].0.forward(xs)?; let xs = self.cv4[i].1.forward(&xs)?; let xs = self.cv4[i].2.forward(&xs)?; xs.reshape((b_sz, self.kpt.0 * self.kpt.1, h * w)) }; let xs0 = forward_cv(xs0, 0)?; let xs1 = forward_cv(xs1, 1)?; let xs2 = forward_cv(xs2, 2)?; let xs = Tensor::cat(&[xs0, xs1, xs2], D::Minus1)?; let (b_sz, _nk, hw) = xs.dims3()?; let xs = xs.reshape((b_sz, self.kpt.0, self.kpt.1, hw))?; let ys01 = ((xs.i((.., .., 0..2))? * 2.)?.broadcast_add(&d.anchors)? - 0.5)? .broadcast_mul(&d.strides)?; let ys2 = candle_nn::ops::sigmoid(&xs.i((.., .., 2..3))?)?; let ys = Tensor::cat(&[ys01, ys2], 2)?.flatten(1, 2)?; Tensor::cat(&[d.pred, ys], 1) } } #[derive(Debug)] pub struct YoloV8 { net: DarkNet, fpn: YoloV8Neck, head: DetectionHead, span: tracing::Span, } impl YoloV8 { pub fn load(vb: VarBuilder, m: Multiples, num_classes: usize) -> Result<Self> { let net = DarkNet::load(vb.pp("net"), m)?; let fpn = YoloV8Neck::load(vb.pp("fpn"), m)?; let head = DetectionHead::load(vb.pp("head"), num_classes, m.filters())?; Ok(Self { net, fpn, head, span: tracing::span!(tracing::Level::TRACE, "yolo-v8"), }) } } impl Module for YoloV8 { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let (xs1, xs2, xs3) = self.net.forward(xs)?; let (xs1, xs2, xs3) = self.fpn.forward(&xs1, &xs2, &xs3)?; Ok(self.head.forward(&xs1, &xs2, &xs3)?.pred) } } #[derive(Debug)] pub struct YoloV8Pose { net: DarkNet, fpn: YoloV8Neck, head: PoseHead, span: tracing::Span, } impl YoloV8Pose { pub fn load( vb: VarBuilder, m: Multiples, num_classes: usize, kpt: (usize, usize), ) -> Result<Self> { let net = DarkNet::load(vb.pp("net"), m)?; let fpn = YoloV8Neck::load(vb.pp("fpn"), m)?; let head = PoseHead::load(vb.pp("head"), num_classes, kpt, m.filters())?; Ok(Self { net, fpn, head, span: tracing::span!(tracing::Level::TRACE, "yolo-v8-pose"), }) } } impl Module for YoloV8Pose { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let (xs1, xs2, xs3) = self.net.forward(xs)?; let (xs1, xs2, xs3) = self.fpn.forward(&xs1, &xs2, &xs3)?; self.head.forward(&xs1, &xs2, &xs3) } }
candle/candle-examples/examples/yolo-v8/model.rs/0
{ "file_path": "candle/candle-examples/examples/yolo-v8/model.rs", "repo_id": "candle", "token_count": 12446 }
45
/****************************************************************************** * Copyright (c) 2023, Tri Dao. ******************************************************************************/ #pragma once #include <cuda.h> #include <vector> // #include <ATen/cuda/CUDAGeneratorImpl.h> // For at::Generator and at::PhiloxCudaState constexpr int TOTAL_DIM = 0; constexpr int H_DIM = 1; constexpr int D_DIM = 2; //////////////////////////////////////////////////////////////////////////////////////////////////// struct Qkv_params { using index_t = int64_t; // The QKV matrices. void *__restrict__ q_ptr; void *__restrict__ k_ptr; void *__restrict__ v_ptr; // The stride between rows of the Q, K and V matrices. index_t q_batch_stride; index_t k_batch_stride; index_t v_batch_stride; index_t q_row_stride; index_t k_row_stride; index_t v_row_stride; index_t q_head_stride; index_t k_head_stride; index_t v_head_stride; // The number of heads. int h, h_k; // In the case of multi-query and grouped-query attention (MQA/GQA), nheads_k could be // different from nheads (query). int h_h_k_ratio; // precompute h / h_k, }; //////////////////////////////////////////////////////////////////////////////////////////////////// struct Flash_fwd_params : public Qkv_params { // The O matrix (output). void * __restrict__ o_ptr; void * __restrict__ oaccum_ptr; // The stride between rows of O. index_t o_batch_stride; index_t o_row_stride; index_t o_head_stride; // The pointer to the P matrix. void * __restrict__ p_ptr; // The pointer to the softmax sum. void * __restrict__ softmax_lse_ptr; void * __restrict__ softmax_lseaccum_ptr; // The dimensions. int b, seqlen_q, seqlen_k, seqlen_knew, d, seqlen_q_rounded, seqlen_k_rounded, d_rounded, rotary_dim, total_q; // The scaling factors for the kernel. float scale_softmax; float scale_softmax_log2; // array of length b+1 holding starting offset of each sequence. int * __restrict__ cu_seqlens_q; int * __restrict__ cu_seqlens_k; int * __restrict__ leftpad_k; // If provided, the actual length of each k sequence. int * __restrict__ seqused_k; int *__restrict__ blockmask; // The K_new and V_new matrices. void * __restrict__ knew_ptr; void * __restrict__ vnew_ptr; // The stride between rows of the Q, K and V matrices. index_t knew_batch_stride; index_t vnew_batch_stride; index_t knew_row_stride; index_t vnew_row_stride; index_t knew_head_stride; index_t vnew_head_stride; // The cos and sin matrices for rotary embedding. void * __restrict__ rotary_cos_ptr; void * __restrict__ rotary_sin_ptr; // The indices to index into the KV cache. int * __restrict__ cache_batch_idx; // Paged KV cache int * __restrict__ block_table; index_t block_table_batch_stride; int page_block_size; // The dropout probability (probability of keeping an activation). float p_dropout; // uint32_t p_dropout_in_uint; // uint16_t p_dropout_in_uint16_t; uint8_t p_dropout_in_uint8_t; // Scale factor of 1 / (1 - p_dropout). float rp_dropout; float scale_softmax_rp_dropout; // Local window size int window_size_left, window_size_right; float softcap; // Random state. // at::PhiloxCudaState philox_args; // Pointer to the RNG seed (idx 0) and offset (idx 1). uint64_t * rng_state; bool is_bf16; bool is_causal; // If is_seqlens_k_cumulative, then seqlen_k is cu_seqlens_k[bidb + 1] - cu_seqlens_k[bidb]. // Otherwise it's cu_seqlens_k[bidb], i.e., we use cu_seqlens_k to store the sequence lengths of K. bool is_seqlens_k_cumulative; bool is_rotary_interleaved; int num_splits; // For split-KV version void * __restrict__ alibi_slopes_ptr; index_t alibi_slopes_batch_stride; bool unpadded_lse; // For varlen paths: LSE is in [nheads, total_seqlen_q] format instead of [b, nheads, seqlen_q]. bool seqlenq_ngroups_swapped; // q has been transposed from (b, 1, (nheads_kv ngroups), d) to (b, ngroups, nheads_kv, d). }; //////////////////////////////////////////////////////////////////////////////////////////////////// struct Flash_bwd_params : public Flash_fwd_params { // The dO and dQKV matrices. void *__restrict__ do_ptr; void *__restrict__ dq_ptr; void *__restrict__ dk_ptr; void *__restrict__ dv_ptr; // To accumulate dQ void *__restrict__ dq_accum_ptr; void *__restrict__ dk_accum_ptr; void *__restrict__ dv_accum_ptr; // // To accumulate dK and dV in case we're splitting the bwd along seqlen_q // dimension void *__restrict__ dk_accum_ptr; void *__restrict__ // dv_accum_ptr; // The stride between rows of the dO, dQ, dK and dV matrices. // TD [2022-04-16]: We're using 32-bit indexing to save registers. // The code probably won't work for arrays larger than 2GB. index_t do_batch_stride; index_t do_row_stride; index_t do_head_stride; index_t dq_batch_stride; index_t dk_batch_stride; index_t dv_batch_stride; index_t dq_row_stride; index_t dk_row_stride; index_t dv_row_stride; index_t dq_head_stride; index_t dk_head_stride; index_t dv_head_stride; // The pointer to the softmax d sum. void *__restrict__ dsoftmax_sum; bool deterministic; index_t dq_accum_split_stride; }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<typename T, int Headdim, bool Is_causal> void run_mha_fwd_(Flash_fwd_params &params, cudaStream_t stream); // template<typename T, int Headdim, bool Is_causal> void run_mha_fwd_splitkv_dispatch(Flash_fwd_params &params, cudaStream_t stream); // template<typename T, int Headdim, bool Is_causal> void run_mha_bwd_(Flash_bwd_params &params, cudaStream_t stream);
candle/candle-flash-attn/kernels/flash.h/0
{ "file_path": "candle/candle-flash-attn/kernels/flash.h", "repo_id": "candle", "token_count": 2326 }
46
mod ffi; use candle::backend::BackendStorage; use candle::cuda_backend::cudarc::driver::DevicePtr; use candle::{CpuStorage, DType, Layout, Result, Shape, Tensor}; use half::{bf16, f16}; pub struct FlashAttn { pub softmax_scale: f32, pub alibi_slopes: Option<Tensor>, pub window_size_left: Option<usize>, pub window_size_right: Option<usize>, pub softcap: Option<f32>, } fn round_multiple(x: usize, m: usize) -> usize { (x + m - 1) / m * m } impl FlashAttn { fn cuda_fwd_t< T: candle::cuda_backend::CudaDType + candle::cuda_backend::cudarc::driver::DeviceRepr, >( &self, q: &candle::CudaStorage, q_l: &Layout, k: &candle::CudaStorage, k_l: &Layout, v: &candle::CudaStorage, v_l: &Layout, is_bf16: bool, ) -> Result<(candle::CudaStorage, Shape)> { // https://github.com/Dao-AILab/flash-attention/blob/b252072409e69c25f2b9d473cc534e49b24decd2/csrc/flash_attn/flash_api.cpp#L187 let dev = q.device(); let out_shape = q_l.shape().clone(); let out_l = Layout::contiguous(&out_shape); let q = q.as_cuda_slice::<T>()?; let k = k.as_cuda_slice::<T>()?; let v = v.as_cuda_slice::<T>()?; let q = q.slice(q_l.start_offset()..); let k = k.slice(k_l.start_offset()..); let v = v.slice(v_l.start_offset()..); let q_stride = q_l.stride(); let k_stride = k_l.stride(); let v_stride = v_l.stride(); let o_stride = out_l.stride(); let q_rank = q_stride.len(); let k_rank = k_stride.len(); let v_rank = v_stride.len(); let o_rank = o_stride.len(); if q_rank != 4 || k_rank != 4 || v_rank != 4 { candle::bail!( "flash-attn expects input tensors of rank 4 (q: {q_rank}, k: {k_rank}, v: {v_rank}" ) } if q_stride[q_rank - 1] != 1 { candle::bail!("the last dim of q must be contiguous {q_stride:?}") } if k_stride[k_rank - 1] != 1 { candle::bail!("the last dim of k must be contiguous {k_stride:?}") } if v_stride[v_rank - 1] != 1 { candle::bail!("the last dim of v must be contiguous {v_stride:?}") } let (b_sz, seqlen_q, num_heads, head_size_og) = q_l.shape().dims4()?; let (_b_sz, seqlen_k, num_heads_k, _head_size_og) = k_l.shape().dims4()?; let expected_kv = (b_sz, seqlen_k, num_heads_k, head_size_og); if expected_kv != k_l.shape().dims4()? { candle::bail!("shape mismatch q {:?} and k {:?}", q_l.shape(), k_l.shape()) } if expected_kv != v_l.shape().dims4()? { candle::bail!("shape mismatch q {:?} and v {:?}", q_l.shape(), v_l.shape()) } if head_size_og > 256 { candle::bail!("only supports head dimension at most 256 (got {head_size_og})") } if head_size_og % 8 != 0 { // TODO: Handle head sizes that are not a multiple of 8 via some padding. candle::bail!("only supports head sizes that are a multiple of 8 (got {head_size_og})") } if num_heads % num_heads_k != 0 { candle::bail!("number of k/v heads {num_heads_k} must divide number of heads in query {num_heads}") } let stream = dev.cuda_stream(); let alibi_slopes_ptr = if let Some(alibi_slopes) = &self.alibi_slopes { if alibi_slopes.dtype() != DType::F32 { candle::bail!( "DType mismatch alibi_slopes {:?}, expected {:?}", alibi_slopes.dtype(), DType::F32 ); } let (alibi_slopes, alibi_slopes_layout) = alibi_slopes.storage_and_layout(); if num_heads != alibi_slopes_layout.shape().dims1()? { candle::bail!( "shape mismatch alibi_slopes {:?}, expected {:?}", alibi_slopes_layout.shape(), (num_heads) ); } let alibi_slopes = match &*alibi_slopes { candle::Storage::Cuda(c) => c.as_cuda_slice::<f32>()?, _ => candle::bail!("alibi_slopes must be a cuda tensor"), }; let alibi_slopes = alibi_slopes.slice(alibi_slopes_layout.start_offset()..); // Dropping the guard here doesn't seem very safe. let (ptr, _guard) = alibi_slopes.device_ptr(&stream); ptr as *const core::ffi::c_void } else { std::ptr::null() }; // if window_size_left > self.max_seqlen_k or None => -1 let mut window_size_left = self .window_size_left .filter(|v| v <= &seqlen_k) .map(|v| v as i32) .unwrap_or(-1); // if window_size_right > self.max_seqlen_k or None => -1 let mut window_size_right = self .window_size_right .filter(|v| v <= &seqlen_k) .map(|v| v as i32) .unwrap_or(-1); let head_size = round_multiple(head_size_og, 8); let head_size_rounded = round_multiple(head_size, 32); let seqlen_q_rounded = round_multiple(seqlen_q, 128); let seqlen_k_rounded = round_multiple(seqlen_k, 128); let elem_count = out_shape.elem_count(); let dst = unsafe { dev.alloc::<T>(elem_count)? }; let softmax_lse = dev.alloc_zeros::<f32>(b_sz * 128 * num_heads * seqlen_q)?; let is_bf16 = if is_bf16 { 1 } else { 0 }; // Causal is the special case where window_size_right == 0 and window_size_left < 0. // Local is the more general case where window_size_right >= 0 or window_size_left >= 0. let is_causal = if window_size_left < 0 && window_size_right == 0 { 1 } else { 0 }; if window_size_left < 0 && window_size_right >= 0 { window_size_left = seqlen_k as i32; } if window_size_left >= 0 && window_size_right < 0 { window_size_right = seqlen_k as i32; } unsafe { let (q_ptr, _guard) = q.device_ptr(&stream); let (k_ptr, _guard) = k.device_ptr(&stream); let (v_ptr, _guard) = v.device_ptr(&stream); let (dst_ptr, _guard) = dst.device_ptr(&stream); let (softmax_lse_ptr, _guard) = softmax_lse.device_ptr(&stream); ffi::run_mha( q_ptr as *const core::ffi::c_void, k_ptr as *const core::ffi::c_void, v_ptr as *const core::ffi::c_void, dst_ptr as *const core::ffi::c_void, softmax_lse_ptr as *const core::ffi::c_void, /* alibi_slopes_ptr */ alibi_slopes_ptr, /* cu_seqlens_q_ptr */ std::ptr::null(), /* cu_seqlens_k_ptr */ std::ptr::null(), /* q_batch_stride */ q_stride[0] as u32, /* k_batch_stride */ k_stride[0] as u32, /* v_batch_stride */ v_stride[0] as u32, /* o_batch_stride */ o_stride[0] as u32, /* alibi_slopes_batch_stride */ 0, /* q_row_stride */ q_stride[q_rank - 3] as u32, /* k_row_stride */ k_stride[k_rank - 3] as u32, /* v_row_stride */ v_stride[v_rank - 3] as u32, /* o_row_stride */ o_stride[o_rank - 3] as u32, /* q_head_stride */ q_stride[q_rank - 2] as u32, /* k_head_stride */ k_stride[k_rank - 2] as u32, /* v_head_stride */ v_stride[v_rank - 2] as u32, /* o_head_stride */ o_stride[o_rank - 2] as u32, /* b */ b_sz as u32, /* h */ num_heads as u32, /* h_k */ num_heads_k as u32, /* d */ head_size as u32, /* d_rounded */ head_size_rounded as u32, /* softmax_scale*/ self.softmax_scale, /* seqlen_q */ seqlen_q as u32, /* seqlen_k */ seqlen_k as u32, /* seqlen_q_rounded */ seqlen_q_rounded as u32, /* seqlen_k_rounded */ seqlen_k_rounded as u32, /* is_bf16 */ is_bf16, /* is_causal */ is_causal, /* upadded_lse */ 0, /* window_size_left */ window_size_left, /* window_size_right */ window_size_right, /* softcap */ self.softcap.unwrap_or(0f32), ) } let dst = candle::CudaStorage::wrap_cuda_slice(dst, dev.clone()); Ok((dst, out_shape)) } } impl candle::CustomOp3 for FlashAttn { fn name(&self) -> &'static str { "flash-attn" } fn cpu_fwd( &self, _: &CpuStorage, _: &Layout, _: &CpuStorage, _: &Layout, _: &CpuStorage, _: &Layout, ) -> Result<(CpuStorage, Shape)> { candle::bail!("no cpu support for flash-attn") } fn cuda_fwd( &self, q: &candle::CudaStorage, q_l: &Layout, k: &candle::CudaStorage, k_l: &Layout, v: &candle::CudaStorage, v_l: &Layout, ) -> Result<(candle::CudaStorage, Shape)> { match q.dtype() { candle::DType::F16 => self.cuda_fwd_t::<f16>(q, q_l, k, k_l, v, v_l, false), candle::DType::BF16 => self.cuda_fwd_t::<bf16>(q, q_l, k, k_l, v, v_l, true), dt => candle::bail!("flash-attn is only supported for f16/bf16 ({dt:?})"), } } } /// Flash-attention v2 layer. /// /// This implements scaled dot-product attention, `softmax(Q @ K^T . softmax_scale) @ V`. /// Multi-query and grouped-query attention are supported by using tensors k and v with fewer heads /// than q, the number of heads in k and v has to be divisible by the number of heads in q. /// /// # Arguments /// /// * `q` - Query tensor with shape `(batch, seq_len_q, num_heads_q, head_size)`. /// * `k` - Key tensor with shape `(batch, seq_len_kv, num_heads_kv, head_size)`. /// * `v` - Value tensor with shape `(batch, seq_len_kv, num_heads_kv, head_size)`. /// /// The resulting tensor has dimensions `(batch, seq_len_q, num_heads_q, head_size)`. pub fn flash_attn( q: &Tensor, k: &Tensor, v: &Tensor, softmax_scale: f32, causal: bool, ) -> Result<Tensor> { let window_size_left = None; let window_size_right = if causal { Some(0) } else { None }; let op = FlashAttn { softmax_scale, alibi_slopes: None, window_size_left, window_size_right, softcap: None, }; q.apply_op3(k, v, op) } /// Flash-attention v2 layer. /// /// This implements scaled dot-product attention, `softmax(Q @ K^T . softmax_scale) @ V`. /// Multi-query and grouped-query attention are supported by using tensors k and v with fewer heads /// than q, the number of heads in k and v has to be divisible by the number of heads in q. /// /// # Arguments /// /// * `q` - Query tensor with shape `(batch, seq_len_q, num_heads_q, head_size)`. /// * `k` - Key tensor with shape `(batch, seq_len_kv, num_heads_kv, head_size)`. /// * `v` - Value tensor with shape `(batch, seq_len_kv, num_heads_kv, head_size)`. /// * `window_size_left` - Limit left attention to value tokens. /// * `window_size_right` - Limit right attention to value tokens. /// /// # Causal mask /// /// `window_size_left=None` with `window_size_right=Some(0)` applies a causal mask to the result /// of `Q @ K^T` /// /// The resulting tensor has dimensions `(batch, seq_len_q, num_heads_q, head_size)`. pub fn flash_attn_windowed( q: &Tensor, k: &Tensor, v: &Tensor, softmax_scale: f32, window_size_left: Option<usize>, window_size_right: Option<usize>, ) -> Result<Tensor> { let op = FlashAttn { softmax_scale, alibi_slopes: None, window_size_left, window_size_right, softcap: None, }; q.apply_op3(k, v, op) } /// Flash-attention v2 layer. /// /// This implements scaled dot-product attention, `softmax(Q @ K^T . softmax_scale) @ V`. /// Multi-query and grouped-query attention are supported by using tensors k and v with fewer heads /// than q, the number of heads in k and v has to be divisible by the number of heads in q. /// /// # Arguments /// /// * `q` - Query tensor with shape `(batch, seq_len_q, num_heads_q, head_size)`. /// * `k` - Key tensor with shape `(batch, seq_len_kv, num_heads_kv, head_size)`. /// * `v` - Value tensor with shape `(batch, seq_len_kv, num_heads_kv, head_size)`. /// * `alibi_slopes` - Alibi slopes tensor with shape `(num_heads_q)`. /// /// The resulting tensor has dimensions `(batch, seq_len_q, num_heads_q, head_size)`. pub fn flash_attn_alibi( q: &Tensor, k: &Tensor, v: &Tensor, alibi_slopes: &Tensor, softmax_scale: f32, causal: bool, ) -> Result<Tensor> { let window_size_left = None; let window_size_right = if causal { Some(0) } else { None }; let op = FlashAttn { softmax_scale, alibi_slopes: Some(alibi_slopes.clone()), window_size_left, window_size_right, softcap: None, }; q.apply_op3(k, v, op) } /// Flash-attention v2 layer. /// /// This implements scaled dot-product attention, `softmax(Q @ K^T . softmax_scale) @ V`. /// Multi-query and grouped-query attention are supported by using tensors k and v with fewer heads /// than q, the number of heads in k and v has to be divisible by the number of heads in q. /// /// # Arguments /// /// * `q` - Query tensor with shape `(batch, seq_len_q, num_heads_q, head_size)`. /// * `k` - Key tensor with shape `(batch, seq_len_kv, num_heads_kv, head_size)`. /// * `v` - Value tensor with shape `(batch, seq_len_kv, num_heads_kv, head_size)`. /// * `alibi_slopes` - Alibi slopes tensor with shape `(num_heads_q)`. /// * `window_size_left` - Limit left attention to value tokens. /// * `window_size_right` - Limit right attention to value tokens. /// /// # Causal mask /// /// `window_size_left=None` with `window_size_right=Some(0)` applies a causal mask to the result /// of `Q @ K^T` /// /// The resulting tensor has dimensions `(batch, seq_len_q, num_heads_q, head_size)`. pub fn flash_attn_alibi_windowed( q: &Tensor, k: &Tensor, v: &Tensor, alibi_slopes: &Tensor, softmax_scale: f32, window_size_left: Option<usize>, window_size_right: Option<usize>, ) -> Result<Tensor> { let op = FlashAttn { softmax_scale, alibi_slopes: Some(alibi_slopes.clone()), window_size_left, window_size_right, softcap: None, }; q.apply_op3(k, v, op) } /// Flash-attention v2 layer. /// /// This implements scaled dot-product attention, `softmax(Q @ K^T . softmax_scale) @ V`. /// Multi-query and grouped-query attention are supported by using tensors `k` and `v` with fewer heads /// than `q`. The number of heads in `k` and `v` must be divisible by the number of heads in `q`. /// /// # Arguments /// /// * `q` - Query tensor with shape `(batch, seq_len_q, num_heads_q, head_size)`. /// * `k` - Key tensor with shape `(batch, seq_len_kv, num_heads_kv, head_size)`. /// * `v` - Value tensor with shape `(batch, seq_len_kv, num_heads_kv, head_size)`. /// * `alibi_slopes` - Optional alibi slopes tensor with shape `(num_heads_q)`. /// * `softmax_scale` - Scaling factor for the softmax operation. /// * `window_size_left` - Optional limit on left attention to value tokens. /// * `window_size_right` - Optional limit on right attention to value tokens. /// * `softcap` - Gemma style softcap the attention logits before the softmax. /// /// # Causal Mask /// /// Setting `window_size_left=None` and `window_size_right=Some(0)` applies a causal mask to the result /// of `Q @ K^T`. /// /// # Returns /// /// The resulting tensor has dimensions `(batch, seq_len_q, num_heads_q, head_size)`. pub fn flash_attn_alibi_windowed_softcap( q: &Tensor, k: &Tensor, v: &Tensor, alibi_slopes: Option<&Tensor>, softmax_scale: f32, window_size_left: Option<usize>, window_size_right: Option<usize>, softcap: f32, ) -> Result<Tensor> { let op = FlashAttn { softmax_scale, alibi_slopes: alibi_slopes.cloned(), window_size_left, window_size_right, softcap: Some(softcap), }; q.apply_op3(k, v, op) } struct FlashAttnVarLen { pub softmax_scale: f32, pub max_seqlen_q: usize, pub max_seqlen_k: usize, pub seqlens_q: Tensor, pub seqlens_k: Tensor, pub alibi_slopes: Option<Tensor>, pub window_size_left: Option<usize>, pub window_size_right: Option<usize>, pub softcap: Option<f32>, } impl FlashAttnVarLen { fn cuda_fwd_t< T: candle::cuda_backend::CudaDType + candle::cuda_backend::cudarc::driver::DeviceRepr, >( &self, q: &candle::CudaStorage, q_l: &Layout, k: &candle::CudaStorage, k_l: &Layout, v: &candle::CudaStorage, v_l: &Layout, is_bf16: bool, ) -> Result<(candle::CudaStorage, Shape)> { // https://github.com/Dao-AILab/flash-attention/blob/184b992dcb2a0890adaa19eb9b541c3e4f9d2a08/csrc/flash_attn/flash_api.cpp#L327 let dev = q.device(); let out_shape = q_l.shape().clone(); let out_l = Layout::contiguous(&out_shape); let (seqlens_q, seqlens_q_layout) = self.seqlens_q.storage_and_layout(); let seqlens_q = match &*seqlens_q { candle::Storage::Cuda(c) => c.as_cuda_slice::<u32>()?, // Should be i32! _ => candle::bail!("seqlens_q must be a cuda tensor"), }; let seqlens_q = match seqlens_q_layout.contiguous_offsets() { Some((o1, o2)) => seqlens_q.slice(o1..o2), None => candle::bail!("seqlens_q has to be contiguous"), }; let (seqlens_k, seqlens_k_layout) = self.seqlens_k.storage_and_layout(); let seqlens_k = match &*seqlens_k { candle::Storage::Cuda(c) => c.as_cuda_slice::<u32>()?, // Should be i32! _ => candle::bail!("seqlens_k must be a cuda tensor"), }; let seqlens_k = match seqlens_k_layout.contiguous_offsets() { Some((o1, o2)) => seqlens_k.slice(o1..o2), None => candle::bail!("seqlens_k has to be contiguous"), }; let q = q.as_cuda_slice::<f16>()?; let k = k.as_cuda_slice::<f16>()?; let v = v.as_cuda_slice::<f16>()?; let q = q.slice(q_l.start_offset()..); let k = k.slice(k_l.start_offset()..); let v = v.slice(v_l.start_offset()..); let q_stride = q_l.stride(); let k_stride = k_l.stride(); let v_stride = v_l.stride(); let o_stride = out_l.stride(); let q_rank = q_stride.len(); let k_rank = k_stride.len(); let v_rank = v_stride.len(); let o_rank = o_stride.len(); if q_rank != 3 || k_rank != 3 || v_rank != 3 { candle::bail!( "flash-attn-varlen expects input tensors of rank 3 (q: {q_rank}, k: {k_rank}, v: {v_rank}" ) } if q_stride[q_rank - 1] != 1 { candle::bail!("the last dim of q must be contiguous {q_stride:?}") } if k_stride[k_rank - 1] != 1 { candle::bail!("the last dim of k must be contiguous {k_stride:?}") } if v_stride[v_rank - 1] != 1 { candle::bail!("the last dim of v must be contiguous {v_stride:?}") } let (total_q, num_heads, head_size_og) = q_l.shape().dims3()?; let (total_k, num_heads_k, _head_size_og) = k_l.shape().dims3()?; let expected_kv = (total_k, num_heads_k, head_size_og); if expected_kv != k_l.shape().dims3()? { candle::bail!("shape mismatch q {:?} and k {:?}", q_l.shape(), k_l.shape()) } if expected_kv != v_l.shape().dims3()? { candle::bail!("shape mismatch q {:?} and v {:?}", q_l.shape(), v_l.shape()) } if head_size_og > 256 { candle::bail!("only supports head dimension at most 256 (got {head_size_og})") } if head_size_og % 8 != 0 { // TODO: Handle head sizes that are not a multiple of 8 via some padding. candle::bail!("only supports head sizes that are a multiple of 8 (got {head_size_og})") } if num_heads % num_heads_k != 0 { candle::bail!("number of k/v heads {num_heads_k} must divide number of heads in query {num_heads}") } let nseqlens_q = seqlens_q_layout.shape().dims1()?; if nseqlens_q < 2 { candle::bail!("seqlens_q should have a len >= 2 {nseqlens_q}") } let nseqlens_k = seqlens_k_layout.shape().dims1()?; if nseqlens_k != nseqlens_q { candle::bail!("seqlens_q and seqlens_k should have the same number of elements {nseqlens_q} <> {nseqlens_k}") } let batch_size = nseqlens_q - 1; let stream = dev.cuda_stream(); let alibi_slopes_ptr = if let Some(alibi_slopes) = &self.alibi_slopes { if alibi_slopes.dtype() != DType::F32 { candle::bail!( "DType mismatch alibi_slopes {:?}, expected {:?}", alibi_slopes.dtype(), DType::F32 ); } let (alibi_slopes, alibi_slopes_layout) = alibi_slopes.storage_and_layout(); if num_heads != alibi_slopes_layout.shape().dims1()? { candle::bail!( "shape mismatch alibi_slopes {:?}, expected {:?}", alibi_slopes_layout.shape(), (num_heads) ); } let alibi_slopes = match &*alibi_slopes { candle::Storage::Cuda(c) => c.as_cuda_slice::<f32>()?, _ => candle::bail!("alibi_slopes must be a cuda tensor"), }; let alibi_slopes = alibi_slopes.slice(alibi_slopes_layout.start_offset()..); // Dropping the guard here doesn't seem very safe. let (ptr, _guard) = alibi_slopes.device_ptr(&stream); ptr as *const core::ffi::c_void } else { std::ptr::null() }; // if window_size_left > self.max_seqlen_k or None => -1 let mut window_size_left = self .window_size_left .filter(|v| v <= &self.max_seqlen_k) .map(|v| v as i32) .unwrap_or(-1); // if window_size_right > self.max_seqlen_k or None => -1 let mut window_size_right = self .window_size_right .filter(|v| v <= &self.max_seqlen_k) .map(|v| v as i32) .unwrap_or(-1); let head_size = round_multiple(head_size_og, 8); let head_size_rounded = round_multiple(head_size, 32); let seqlen_q_rounded = round_multiple(self.max_seqlen_q, 128); let seqlen_k_rounded = round_multiple(self.max_seqlen_k, 128); let elem_count = out_shape.elem_count(); let dst = unsafe { dev.alloc::<f16>(elem_count)? }; let softmax_lse = dev.alloc_zeros::<f32>(num_heads * total_q)?; let is_bf16 = if is_bf16 { 1 } else { 0 }; // Causal is the special case where window_size_right == 0 and window_size_left < 0. // Local is the more general case where window_size_right >= 0 or window_size_left >= 0. let is_causal = if window_size_left < 0 && window_size_right == 0 { 1 } else { 0 }; if window_size_left < 0 && window_size_right >= 0 { window_size_left = self.max_seqlen_k as i32; } if window_size_left >= 0 && window_size_right < 0 { window_size_right = self.max_seqlen_k as i32; } unsafe { let (q_ptr, _guard) = q.device_ptr(&stream); let (k_ptr, _guard) = k.device_ptr(&stream); let (v_ptr, _guard) = v.device_ptr(&stream); let (dst_ptr, _guard) = dst.device_ptr(&stream); let (softmax_lse_ptr, _guard) = softmax_lse.device_ptr(&stream); let (seqlens_q_ptr, _guard) = seqlens_q.device_ptr(&stream); let (seqlens_k_ptr, _guard) = seqlens_k.device_ptr(&stream); ffi::run_mha( q_ptr as *const core::ffi::c_void, k_ptr as *const core::ffi::c_void, v_ptr as *const core::ffi::c_void, dst_ptr as *const core::ffi::c_void, softmax_lse_ptr as *const core::ffi::c_void, /* alibi_slopes_ptr */ alibi_slopes_ptr as *const core::ffi::c_void, /* cu_seqlens_q_ptr */ seqlens_q_ptr as *const i32, /* cu_seqlens_k_ptr */ seqlens_k_ptr as *const i32, /* q_batch_stride */ 0, /* k_batch_stride */ 0, /* v_batch_stride */ 0, /* o_batch_stride */ 0, /* alibi_slopes_batch_stride */ 0, /* q_row_stride */ q_stride[q_rank - 3] as u32, /* k_row_stride */ k_stride[k_rank - 3] as u32, /* v_row_stride */ v_stride[v_rank - 3] as u32, /* o_row_stride */ o_stride[o_rank - 3] as u32, /* q_head_stride */ q_stride[q_rank - 2] as u32, /* k_head_stride */ k_stride[k_rank - 2] as u32, /* v_head_stride */ v_stride[v_rank - 2] as u32, /* o_head_stride */ o_stride[o_rank - 2] as u32, /* b */ batch_size as u32, /* h */ num_heads as u32, /* h_k */ num_heads_k as u32, /* d */ head_size as u32, /* d_rounded */ head_size_rounded as u32, /* softmax_scale*/ self.softmax_scale, /* seqlen_q */ self.max_seqlen_q as u32, /* seqlen_k */ self.max_seqlen_k as u32, /* seqlen_q_rounded */ seqlen_q_rounded as u32, /* seqlen_k_rounded */ seqlen_k_rounded as u32, /* is_bf16 */ is_bf16, /* is_causal */ is_causal, /* upadded_lse */ 1, /* window_size_left */ window_size_left, /* window_size_right */ window_size_right, /* softcap */ self.softcap.unwrap_or(0.0), ) } let dst = candle::CudaStorage::wrap_cuda_slice(dst, dev.clone()); Ok((dst, out_shape)) } } impl candle::CustomOp3 for FlashAttnVarLen { fn name(&self) -> &'static str { "flash-attn-varlen" } fn cpu_fwd( &self, _: &CpuStorage, _: &Layout, _: &CpuStorage, _: &Layout, _: &CpuStorage, _: &Layout, ) -> Result<(CpuStorage, Shape)> { candle::bail!("no cpu support for flash-attn") } fn cuda_fwd( &self, q: &candle::CudaStorage, q_l: &Layout, k: &candle::CudaStorage, k_l: &Layout, v: &candle::CudaStorage, v_l: &Layout, ) -> Result<(candle::CudaStorage, Shape)> { match q.dtype() { candle::DType::F16 => self.cuda_fwd_t::<f16>(q, q_l, k, k_l, v, v_l, false), candle::DType::BF16 => self.cuda_fwd_t::<bf16>(q, q_l, k, k_l, v, v_l, true), dt => candle::bail!("flash-attn is only supported for f16/bf16 ({dt:?})"), } } } #[allow(clippy::too_many_arguments)] /// Flash-attention v2 layer with variable-length batching. /// /// This implements scaled dot-product attention, `softmax(Q @ K^T . softmax_scale) @ V`. /// Multi-query and grouped-query attention are supported by using tensors k and v with fewer heads /// than q, the number of heads in k and v has to be divisible by the number of heads in q. /// /// # Arguments /// /// * `q` - Query tensor with shape `(total_q, num_heads_q, head_size)`. /// * `k` - Key tensor with shape `(total_kv, num_heads_kv, head_size)`. /// * `v` - Value tensor with shape `(total_kv, num_heads_kv, head_size)`. /// * `seqlens_q` - The cumulative lengths of the sequences in the batch, used to index in q. /// * `seqlens_k` - The cumulative lengths of the sequences in the batch, used to index in k and v. /// * `max_seqlen_q` - The maximum query sequence length for q in the batch. /// * `max_seqlen_k` - The maximum query sequence length for k and v in the batch. /// /// `seqlens_q` and `seqlens_k` contain `batch_size + 1` elements, typically `0`, `seqlen_1`, /// `seqlen_1 + seqlen_2`, etc. /// /// The resulting tensor has dimensions `(total_q, num_heads_q, head_size)`. pub fn flash_attn_varlen( q: &Tensor, k: &Tensor, v: &Tensor, seqlens_q: &Tensor, seqlens_k: &Tensor, max_seqlen_q: usize, max_seqlen_k: usize, softmax_scale: f32, causal: bool, ) -> Result<Tensor> { let window_size_left = None; let window_size_right = if causal { Some(0) } else { None }; let op = FlashAttnVarLen { softmax_scale, max_seqlen_q, max_seqlen_k, seqlens_q: seqlens_q.clone(), seqlens_k: seqlens_k.clone(), alibi_slopes: None, window_size_left, window_size_right, softcap: None, }; q.apply_op3(k, v, op) } #[allow(clippy::too_many_arguments)] /// Flash-attention v2 layer with variable-length batching. /// /// This implements scaled dot-product attention, `softmax(Q @ K^T . softmax_scale) @ V`. /// Multi-query and grouped-query attention are supported by using tensors k and v with fewer heads /// than q, the number of heads in k and v has to be divisible by the number of heads in q. /// /// # Arguments /// /// * `q` - Query tensor with shape `(total_q, num_heads_q, head_size)`. /// * `k` - Key tensor with shape `(total_kv, num_heads_kv, head_size)`. /// * `v` - Value tensor with shape `(total_kv, num_heads_kv, head_size)`. /// * `seqlens_q` - The cumulative lengths of the sequences in the batch, used to index in q. /// * `seqlens_k` - The cumulative lengths of the sequences in the batch, used to index in k and v. /// * `max_seqlen_q` - The maximum query sequence length for q in the batch. /// * `max_seqlen_k` - The maximum query sequence length for k and v in the batch. /// * `window_size_left` - Limit left attention to value tokens. /// * `window_size_right` - Limit right attention to value tokens. /// /// `seqlens_q` and `seqlens_k` contain `batch_size + 1` elements, typically `0`, `seqlen_1`, /// `seqlen_1 + seqlen_2`, etc. /// /// The resulting tensor has dimensions `(total_q, num_heads_q, head_size)`. /// /// # Causal mask /// /// `window_size_left=None` with `window_size_right=Some(0)` applies a causal mask to the result /// of `Q @ K^T` pub fn flash_attn_varlen_windowed( q: &Tensor, k: &Tensor, v: &Tensor, seqlens_q: &Tensor, seqlens_k: &Tensor, max_seqlen_q: usize, max_seqlen_k: usize, softmax_scale: f32, window_size_left: Option<usize>, window_size_right: Option<usize>, ) -> Result<Tensor> { let op = FlashAttnVarLen { softmax_scale, max_seqlen_q, max_seqlen_k, seqlens_q: seqlens_q.clone(), seqlens_k: seqlens_k.clone(), alibi_slopes: None, window_size_left, window_size_right, softcap: None, }; q.apply_op3(k, v, op) } #[allow(clippy::too_many_arguments)] /// Flash-attention v2 layer with variable-length batching. /// /// This implements scaled dot-product attention, `softmax(Q @ K^T . softmax_scale) @ V`. /// Multi-query and grouped-query attention are supported by using tensors k and v with fewer heads /// than q, the number of heads in k and v has to be divisible by the number of heads in q. /// /// # Arguments /// /// * `q` - Query tensor with shape `(total_q, num_heads_q, head_size)`. /// * `k` - Key tensor with shape `(total_kv, num_heads_kv, head_size)`. /// * `v` - Value tensor with shape `(total_kv, num_heads_kv, head_size)`. /// * `alibi_slopes` - Alibi slopes tensor with shape `(num_heads_q)`. /// * `seqlens_q` - The cumulative lengths of the sequences in the batch, used to index in q. /// * `seqlens_k` - The cumulative lengths of the sequences in the batch, used to index in k and v. /// * `max_seqlen_q` - The maximum query sequence length for q in the batch. /// * `max_seqlen_k` - The maximum query sequence length for k and v in the batch. /// /// `seqlens_q` and `seqlens_k` contain `batch_size + 1` elements, typically `0`, `seqlen_1`, /// `seqlen_1 + seqlen_2`, etc. /// /// The resulting tensor has dimensions `(total_q, num_heads_q, head_size)`. pub fn flash_attn_varlen_alibi( q: &Tensor, k: &Tensor, v: &Tensor, alibi_slopes: &Tensor, seqlens_q: &Tensor, seqlens_k: &Tensor, max_seqlen_q: usize, max_seqlen_k: usize, softmax_scale: f32, causal: bool, ) -> Result<Tensor> { let window_size_left = None; let window_size_right = if causal { Some(0) } else { None }; let op = FlashAttnVarLen { softmax_scale, max_seqlen_q, max_seqlen_k, seqlens_q: seqlens_q.clone(), seqlens_k: seqlens_k.clone(), alibi_slopes: Some(alibi_slopes.clone()), window_size_left, window_size_right, softcap: None, }; q.apply_op3(k, v, op) } #[allow(clippy::too_many_arguments)] /// Flash-attention v2 layer with variable-length batching. /// /// This implements scaled dot-product attention, `softmax(Q @ K^T . softmax_scale) @ V`. /// Multi-query and grouped-query attention are supported by using tensors k and v with fewer heads /// than q, the number of heads in k and v has to be divisible by the number of heads in q. /// /// # Arguments /// /// * `q` - Query tensor with shape `(total_q, num_heads_q, head_size)`. /// * `k` - Key tensor with shape `(total_kv, num_heads_kv, head_size)`. /// * `v` - Value tensor with shape `(total_kv, num_heads_kv, head_size)`. /// * `alibi_slopes` - Alibi slopes tensor with shape `(num_heads_q)`. /// * `seqlens_q` - The cumulative lengths of the sequences in the batch, used to index in q. /// * `seqlens_k` - The cumulative lengths of the sequences in the batch, used to index in k and v. /// * `max_seqlen_q` - The maximum query sequence length for q in the batch. /// * `max_seqlen_k` - The maximum query sequence length for k and v in the batch. /// * `window_size_left` - Limit left attention to value tokens. /// * `window_size_right` - Limit right attention to value tokens. /// /// `seqlens_q` and `seqlens_k` contain `batch_size + 1` elements, typically `0`, `seqlen_1`, /// `seqlen_1 + seqlen_2`, etc. /// /// The resulting tensor has dimensions `(total_q, num_heads_q, head_size)`. /// /// # Causal mask /// /// `window_size_left=None` with `window_size_right=Some(0)` applies a causal mask to the result /// of `Q @ K^T` pub fn flash_attn_varlen_alibi_windowed( q: &Tensor, k: &Tensor, v: &Tensor, alibi_slopes: &Tensor, seqlens_q: &Tensor, seqlens_k: &Tensor, max_seqlen_q: usize, max_seqlen_k: usize, softmax_scale: f32, window_size_left: Option<usize>, window_size_right: Option<usize>, ) -> Result<Tensor> { let op = FlashAttnVarLen { softmax_scale, max_seqlen_q, max_seqlen_k, seqlens_q: seqlens_q.clone(), seqlens_k: seqlens_k.clone(), alibi_slopes: Some(alibi_slopes.clone()), window_size_left, window_size_right, softcap: None, }; q.apply_op3(k, v, op) } #[allow(clippy::too_many_arguments)] /// Flash-attention v2 layer with variable-length batching. /// /// This implements scaled dot-product attention, `softmax(Q @ K^T . softmax_scale) @ V`. /// Multi-query and grouped-query attention are supported by using tensors k and v with fewer heads /// than q, the number of heads in k and v has to be divisible by the number of heads in q. /// /// # Arguments /// /// * `q` - Query tensor with shape `(total_q, num_heads_q, head_size)`. /// * `k` - Key tensor with shape `(total_kv, num_heads_kv, head_size)`. /// * `v` - Value tensor with shape `(total_kv, num_heads_kv, head_size)`. /// * `alibi_slopes` - Option, alibi slopes tensor with shape `(num_heads_q)`. /// * `seqlens_q` - The cumulative lengths of the sequences in the batch, used to index in q. /// * `seqlens_k` - The cumulative lengths of the sequences in the batch, used to index in k and v. /// * `max_seqlen_q` - The maximum query sequence length for q in the batch. /// * `max_seqlen_k` - The maximum query sequence length for k and v in the batch. /// * `window_size_left` - Option, limit left attention to value tokens. /// * `window_size_right` - Option, limit right attention to value tokens. /// * `softcap` - Gemma style softcap the attention logits before the softmax. /// /// `seqlens_q` and `seqlens_k` contain `batch_size + 1` elements, typically `0`, `seqlen_1`, /// `seqlen_1 + seqlen_2`, etc. /// /// The resulting tensor has dimensions `(total_q, num_heads_q, head_size)`. /// /// # Causal mask /// /// `window_size_left=None` with `window_size_right=Some(0)` applies a causal mask to the result /// of `Q @ K^T` pub fn flash_attn_varlen_alibi_windowed_softcap( q: &Tensor, k: &Tensor, v: &Tensor, alibi_slopes: Option<&Tensor>, seqlens_q: &Tensor, seqlens_k: &Tensor, max_seqlen_q: usize, max_seqlen_k: usize, softmax_scale: f32, window_size_left: Option<usize>, window_size_right: Option<usize>, softcap: f32, ) -> Result<Tensor> { let op = FlashAttnVarLen { softmax_scale, max_seqlen_q, max_seqlen_k, seqlens_q: seqlens_q.clone(), seqlens_k: seqlens_k.clone(), alibi_slopes: alibi_slopes.cloned(), window_size_left, window_size_right, softcap: Some(softcap), }; q.apply_op3(k, v, op) }
candle/candle-flash-attn/src/lib.rs/0
{ "file_path": "candle/candle-flash-attn/src/lib.rs", "repo_id": "candle", "token_count": 17883 }
47
// Kernels adapted from llama.cpp ggml-cuda.cu // https://github.com/ggerganov/llama.cpp/blob/master/ggml-cuda.cu #include "cuda_fp16.h" #include "cuda_bf16.h" #include<stdint.h> #define GGML_UNUSED(x) (void)(x) #define GGML_CUDA_ASSUME(x) #ifdef GGML_QKK_64 #define QK_K 64 #define K_SCALE_SIZE 4 #else #define QK_K 256 #define K_SCALE_SIZE 12 #endif #undef GGML_CUDA_F16 #define GGML_CUDA_DMMV_X 32 #define CUDA_QUANTIZE_BLOCK_SIZE 256 #define CUDA_DEQUANTIZE_BLOCK_SIZE 256 #define K_QUANTS_PER_ITERATION 2 typedef uint16_t ggml_fp16_t; typedef float dfloat; // dequantize float typedef float2 dfloat2; typedef void (*dequantize_kernel_t)(const void * vx, const int ib, const int iqs, dfloat2 & v); static __device__ __forceinline__ float warp_reduce_sum(float x) { #pragma unroll for (int mask = 16; mask > 0; mask >>= 1) { x += __shfl_xor_sync(0xffffffff, x, mask, 32); } return x; } static __device__ __forceinline__ float warp_reduce_max(float x) { #pragma unroll for (int mask = 16; mask > 0; mask >>= 1) { x = fmaxf(x, __shfl_xor_sync(0xffffffff, x, mask, 32)); } return x; } static __device__ __forceinline__ int get_int_from_int8(const int8_t * x8, const int & i32) { const uint16_t * x16 = (const uint16_t *) (x8 + sizeof(int) * i32); // assume at least 2 byte alignment int x32 = 0; x32 |= x16[0] << 0; x32 |= x16[1] << 16; return x32; } static __device__ __forceinline__ int get_int_from_uint8(const uint8_t * x8, const int & i32) { const uint16_t * x16 = (const uint16_t *) (x8 + sizeof(int) * i32); // assume at least 2 byte alignment int x32 = 0; x32 |= x16[0] << 0; x32 |= x16[1] << 16; return x32; } static __device__ __forceinline__ int get_int_from_int8_aligned(const int8_t * x8, const int & i32) { return *((const int *) (x8 + sizeof(int) * i32)); // assume at least 4 byte alignment } static __device__ __forceinline__ int get_int_from_uint8_aligned(const uint8_t * x8, const int & i32) { return *((const int *) (x8 + sizeof(int) * i32)); // assume at least 4 byte alignment } #define WARP_SIZE 32 #define CUDART_HMAX 11070 // CUDA 11.7, min. ver. for which __hmax and __hmax2 are known to work (may be higher than needed) #define CC_PASCAL 600 #define MIN_CC_DP4A 610 // minimum compute capability for __dp4a, an intrinsic for byte-wise dot products #define CC_VOLTA 700 #define CC_OFFSET_AMD 1000000 #define CC_RDNA1 (CC_OFFSET_AMD + 1010) #define CC_RDNA2 (CC_OFFSET_AMD + 1030) #define CC_RDNA3 (CC_OFFSET_AMD + 1100) static __device__ __forceinline__ int ggml_cuda_dp4a(const int a, const int b, int c) { #if __CUDA_ARCH__ >= MIN_CC_DP4A return __dp4a(a, b, c); #else // __CUDA_ARCH__ >= MIN_CC_DP4A const int8_t * a8 = (const int8_t *) &a; const int8_t * b8 = (const int8_t *) &b; return c + a8[0]*b8[0] + a8[1]*b8[1] + a8[2]*b8[2] + a8[3]*b8[3]; #endif // __CUDA_ARCH__ >= MIN_CC_DP4A } #define MMQ_X_Q4_0_RDNA2 64 #define MMQ_Y_Q4_0_RDNA2 128 #define NWARPS_Q4_0_RDNA2 8 #define MMQ_X_Q4_0_RDNA1 64 #define MMQ_Y_Q4_0_RDNA1 64 #define NWARPS_Q4_0_RDNA1 8 #if defined(CUDA_USE_TENSOR_CORES) #define MMQ_X_Q4_0_AMPERE 4 #define MMQ_Y_Q4_0_AMPERE 32 #define NWARPS_Q4_0_AMPERE 4 #else #define MMQ_X_Q4_0_AMPERE 64 #define MMQ_Y_Q4_0_AMPERE 128 #define NWARPS_Q4_0_AMPERE 4 #endif #define MMQ_X_Q4_0_PASCAL 64 #define MMQ_Y_Q4_0_PASCAL 64 #define NWARPS_Q4_0_PASCAL 8 #define MMQ_X_Q4_1_RDNA2 64 #define MMQ_Y_Q4_1_RDNA2 128 #define NWARPS_Q4_1_RDNA2 8 #define MMQ_X_Q4_1_RDNA1 64 #define MMQ_Y_Q4_1_RDNA1 64 #define NWARPS_Q4_1_RDNA1 8 #if defined(CUDA_USE_TENSOR_CORES) #define MMQ_X_Q4_1_AMPERE 4 #define MMQ_Y_Q4_1_AMPERE 32 #define NWARPS_Q4_1_AMPERE 4 #else #define MMQ_X_Q4_1_AMPERE 64 #define MMQ_Y_Q4_1_AMPERE 128 #define NWARPS_Q4_1_AMPERE 4 #endif #define MMQ_X_Q4_1_PASCAL 64 #define MMQ_Y_Q4_1_PASCAL 64 #define NWARPS_Q4_1_PASCAL 8 #define MMQ_X_Q5_0_RDNA2 64 #define MMQ_Y_Q5_0_RDNA2 128 #define NWARPS_Q5_0_RDNA2 8 #define MMQ_X_Q5_0_RDNA1 64 #define MMQ_Y_Q5_0_RDNA1 64 #define NWARPS_Q5_0_RDNA1 8 #if defined(CUDA_USE_TENSOR_CORES) #define MMQ_X_Q5_0_AMPERE 4 #define MMQ_Y_Q5_0_AMPERE 32 #define NWARPS_Q5_0_AMPERE 4 #else #define MMQ_X_Q5_0_AMPERE 128 #define MMQ_Y_Q5_0_AMPERE 64 #define NWARPS_Q5_0_AMPERE 4 #endif #define MMQ_X_Q5_0_PASCAL 64 #define MMQ_Y_Q5_0_PASCAL 64 #define NWARPS_Q5_0_PASCAL 8 #define MMQ_X_Q5_1_RDNA2 64 #define MMQ_Y_Q5_1_RDNA2 128 #define NWARPS_Q5_1_RDNA2 8 #define MMQ_X_Q5_1_RDNA1 64 #define MMQ_Y_Q5_1_RDNA1 64 #define NWARPS_Q5_1_RDNA1 8 #if defined(CUDA_USE_TENSOR_CORES) #define MMQ_X_Q5_1_AMPERE 4 #define MMQ_Y_Q5_1_AMPERE 32 #define NWARPS_Q5_1_AMPERE 4 #else #define MMQ_X_Q5_1_AMPERE 128 #define MMQ_Y_Q5_1_AMPERE 64 #define NWARPS_Q5_1_AMPERE 4 #endif #define MMQ_X_Q5_1_PASCAL 64 #define MMQ_Y_Q5_1_PASCAL 64 #define NWARPS_Q5_1_PASCAL 8 #define MMQ_X_Q8_0_RDNA2 64 #define MMQ_Y_Q8_0_RDNA2 128 #define NWARPS_Q8_0_RDNA2 8 #define MMQ_X_Q8_0_RDNA1 64 #define MMQ_Y_Q8_0_RDNA1 64 #define NWARPS_Q8_0_RDNA1 8 #if defined(CUDA_USE_TENSOR_CORES) #define MMQ_X_Q8_0_AMPERE 4 #define MMQ_Y_Q8_0_AMPERE 32 #define NWARPS_Q8_0_AMPERE 4 #else #define MMQ_X_Q8_0_AMPERE 128 #define MMQ_Y_Q8_0_AMPERE 64 #define NWARPS_Q8_0_AMPERE 4 #endif #define MMQ_X_Q8_0_PASCAL 64 #define MMQ_Y_Q8_0_PASCAL 64 #define NWARPS_Q8_0_PASCAL 8 #define MMQ_X_Q2_K_RDNA2 64 #define MMQ_Y_Q2_K_RDNA2 128 #define NWARPS_Q2_K_RDNA2 8 #define MMQ_X_Q2_K_RDNA1 128 #define MMQ_Y_Q2_K_RDNA1 32 #define NWARPS_Q2_K_RDNA1 8 #if defined(CUDA_USE_TENSOR_CORES) #define MMQ_X_Q2_K_AMPERE 4 #define MMQ_Y_Q2_K_AMPERE 32 #define NWARPS_Q2_K_AMPERE 4 #else #define MMQ_X_Q2_K_AMPERE 64 #define MMQ_Y_Q2_K_AMPERE 128 #define NWARPS_Q2_K_AMPERE 4 #endif #define MMQ_X_Q2_K_PASCAL 64 #define MMQ_Y_Q2_K_PASCAL 64 #define NWARPS_Q2_K_PASCAL 8 #define MMQ_X_Q3_K_RDNA2 128 #define MMQ_Y_Q3_K_RDNA2 64 #define NWARPS_Q3_K_RDNA2 8 #define MMQ_X_Q3_K_RDNA1 32 #define MMQ_Y_Q3_K_RDNA1 128 #define NWARPS_Q3_K_RDNA1 8 #if defined(CUDA_USE_TENSOR_CORES) #define MMQ_X_Q3_K_AMPERE 4 #define MMQ_Y_Q3_K_AMPERE 32 #define NWARPS_Q3_K_AMPERE 4 #else #define MMQ_X_Q3_K_AMPERE 128 #define MMQ_Y_Q3_K_AMPERE 128 #define NWARPS_Q3_K_AMPERE 4 #endif #define MMQ_X_Q3_K_PASCAL 64 #define MMQ_Y_Q3_K_PASCAL 64 #define NWARPS_Q3_K_PASCAL 8 #define MMQ_X_Q4_K_RDNA2 64 #define MMQ_Y_Q4_K_RDNA2 128 #define NWARPS_Q4_K_RDNA2 8 #define MMQ_X_Q4_K_RDNA1 32 #define MMQ_Y_Q4_K_RDNA1 64 #define NWARPS_Q4_K_RDNA1 8 #if defined(CUDA_USE_TENSOR_CORES) #define MMQ_X_Q4_K_AMPERE 4 #define MMQ_Y_Q4_K_AMPERE 32 #define NWARPS_Q4_K_AMPERE 4 #else #define MMQ_X_Q4_K_AMPERE 64 #define MMQ_Y_Q4_K_AMPERE 128 #define NWARPS_Q4_K_AMPERE 4 #endif #define MMQ_X_Q4_K_PASCAL 64 #define MMQ_Y_Q4_K_PASCAL 64 #define NWARPS_Q4_K_PASCAL 8 #define MMQ_X_Q5_K_RDNA2 64 #define MMQ_Y_Q5_K_RDNA2 128 #define NWARPS_Q5_K_RDNA2 8 #define MMQ_X_Q5_K_RDNA1 32 #define MMQ_Y_Q5_K_RDNA1 64 #define NWARPS_Q5_K_RDNA1 8 #if defined(CUDA_USE_TENSOR_CORES) #define MMQ_X_Q5_K_AMPERE 4 #define MMQ_Y_Q5_K_AMPERE 32 #define NWARPS_Q5_K_AMPERE 4 #else #define MMQ_X_Q5_K_AMPERE 64 #define MMQ_Y_Q5_K_AMPERE 128 #define NWARPS_Q5_K_AMPERE 4 #endif #define MMQ_X_Q5_K_PASCAL 64 #define MMQ_Y_Q5_K_PASCAL 64 #define NWARPS_Q5_K_PASCAL 8 #define MMQ_X_Q6_K_RDNA2 64 #define MMQ_Y_Q6_K_RDNA2 128 #define NWARPS_Q6_K_RDNA2 8 #define MMQ_X_Q6_K_RDNA1 32 #define MMQ_Y_Q6_K_RDNA1 64 #define NWARPS_Q6_K_RDNA1 8 #if defined(CUDA_USE_TENSOR_CORES) #define MMQ_X_Q6_K_AMPERE 4 #define MMQ_Y_Q6_K_AMPERE 32 #define NWARPS_Q6_K_AMPERE 4 #else #define MMQ_X_Q6_K_AMPERE 64 #define MMQ_Y_Q6_K_AMPERE 64 #define NWARPS_Q6_K_AMPERE 4 #endif #define MMQ_X_Q6_K_PASCAL 64 #define MMQ_Y_Q6_K_PASCAL 64 #define NWARPS_Q6_K_PASCAL 8 // QK = number of values after dequantization // QR = QK / number of values before dequantization // QI = number of 32 bit integers before dequantization #define QK4_0 32 #define QR4_0 2 #define QI4_0 (QK4_0 / (4 * QR4_0)) typedef struct { half d; // delta uint8_t qs[QK4_0 / 2]; // nibbles / quants } block_q4_0; static_assert(sizeof(block_q4_0) == sizeof(ggml_fp16_t) + QK4_0 / 2, "wrong q4_0 block size/padding"); #define QK4_1 32 #define QR4_1 2 #define QI4_1 (QK4_1 / (4 * QR4_1)) typedef struct { half2 dm; // dm.x = delta, dm.y = min uint8_t qs[QK4_1 / 2]; // nibbles / quants } block_q4_1; static_assert(sizeof(block_q4_1) == sizeof(ggml_fp16_t) * 2 + QK4_1 / 2, "wrong q4_1 block size/padding"); #define QK5_0 32 #define QR5_0 2 #define QI5_0 (QK5_0 / (4 * QR5_0)) typedef struct { half d; // delta uint8_t qh[4]; // 5-th bit of quants uint8_t qs[QK5_0 / 2]; // nibbles / quants } block_q5_0; static_assert(sizeof(block_q5_0) == sizeof(ggml_fp16_t) + sizeof(uint32_t) + QK5_0 / 2, "wrong q5_0 block size/padding"); #define QK5_1 32 #define QR5_1 2 #define QI5_1 (QK5_1 / (4 * QR5_1)) typedef struct { half2 dm; // dm.x = delta, dm.y = min uint8_t qh[4]; // 5-th bit of quants uint8_t qs[QK5_1 / 2]; // nibbles / quants } block_q5_1; static_assert(sizeof(block_q5_1) == 2 * sizeof(ggml_fp16_t) + sizeof(uint32_t) + QK5_1 / 2, "wrong q5_1 block size/padding"); #define QK8_0 32 #define QR8_0 1 #define QI8_0 (QK8_0 / (4 * QR8_0)) typedef struct { half d; // delta int8_t qs[QK8_0]; // quants } block_q8_0; static_assert(sizeof(block_q8_0) == sizeof(ggml_fp16_t) + QK8_0, "wrong q8_0 block size/padding"); #define QK8_1 32 #define QR8_1 1 #define QI8_1 (QK8_1 / (4 * QR8_1)) typedef struct { half2 ds; // ds.x = delta, ds.y = sum int8_t qs[QK8_0]; // quants } block_q8_1; static_assert(sizeof(block_q8_1) == 2*sizeof(ggml_fp16_t) + QK8_0, "wrong q8_1 block size/padding"); typedef float (*vec_dot_q_cuda_t)(const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs); typedef void (*allocate_tiles_cuda_t)(int ** x_ql, half2 ** x_dm, int ** x_qh, int ** x_sc); typedef void (*load_tiles_cuda_t)( const void * __restrict__ vx, int * __restrict__ x_ql, half2 * __restrict__ x_dm, int * __restrict__ x_qh, int * __restrict__ x_sc, const int & i_offset, const int & i_max, const int & k, const int & blocks_per_row); typedef float (*vec_dot_q_mul_mat_cuda_t)( const int * __restrict__ x_ql, const half2 * __restrict__ x_dm, const int * __restrict__ x_qh, const int * __restrict__ x_sc, const int * __restrict__ y_qs, const half2 * __restrict__ y_ms, const int & i, const int & j, const int & k); #define QR2_K 4 #define QI2_K (QK_K / (4*QR2_K)) typedef struct { uint8_t scales[QK_K/16]; // scales and mins, quantized with 4 bits uint8_t qs[QK_K/4]; // quants half2 dm; // super-block scale for quantized scales/mins } block_q2_K; static_assert(sizeof(block_q2_K) == 2*sizeof(ggml_fp16_t) + QK_K/16 + QK_K/4, "wrong q2_K block size/padding"); #define QR3_K 4 #define QI3_K (QK_K / (4*QR3_K)) typedef struct { uint8_t hmask[QK_K/8]; // quants - high bit uint8_t qs[QK_K/4]; // quants - low 2 bits #ifdef GGML_QKK_64 uint8_t scales[2]; // scales, quantized with 8 bits #else uint8_t scales[K_SCALE_SIZE]; // scales, quantized with 6 bits #endif half d; // super-block scale } block_q3_K; //static_assert(sizeof(block_q3_K) == sizeof(ggml_fp16_t) + QK_K / 4 + QK_K / 8 + K_SCALE_SIZE, "wrong q3_K block size/padding"); #define QR4_K 2 #define QI4_K (QK_K / (4*QR4_K)) #ifdef GGML_QKK_64 typedef struct { half dm[2]; // super-block scales/mins uint8_t scales[2]; // 4-bit block scales/mins uint8_t qs[QK_K/2]; // 4--bit quants } block_q4_K; static_assert(sizeof(block_q4_K) == sizeof(half2) + QK_K/2 + 2, "wrong q4_K block size/padding"); #else typedef struct { half2 dm; // super-block scale for quantized scales/mins uint8_t scales[3*QK_K/64]; // scales, quantized with 6 bits uint8_t qs[QK_K/2]; // 4--bit quants } block_q4_K; static_assert(sizeof(block_q4_K) == 2*sizeof(ggml_fp16_t) + 3*QK_K/64 + QK_K/2, "wrong q4_K block size/padding"); #endif #define QR5_K 2 #define QI5_K (QK_K / (4*QR5_K)) #ifdef GGML_QKK_64 typedef struct { half d; // super-block scale int8_t scales[QK_K/16]; // block scales uint8_t qh[QK_K/8]; // quants, high bit uint8_t qs[QK_K/2]; // quants, low 4 bits } block_q5_K; static_assert(sizeof(block_q5_K) == sizeof(ggml_fp16_t) + QK_K/2 + QK_K/8 + QK_K/16, "wrong q5_K block size/padding"); #else typedef struct { half2 dm; // super-block scale for quantized scales/mins uint8_t scales[K_SCALE_SIZE]; // scales and mins, quantized with 6 bits uint8_t qh[QK_K/8]; // quants, high bit uint8_t qs[QK_K/2]; // quants, low 4 bits } block_q5_K; static_assert(sizeof(block_q5_K) == 2*sizeof(ggml_fp16_t) + K_SCALE_SIZE + QK_K/2 + QK_K/8, "wrong q5_K block size/padding"); #endif #define QR6_K 2 #define QI6_K (QK_K / (4*QR6_K)) typedef struct { uint8_t ql[QK_K/2]; // quants, lower 4 bits uint8_t qh[QK_K/4]; // quants, upper 2 bits int8_t scales[QK_K/16]; // scales half d; // delta } block_q6_K; static_assert(sizeof(block_q6_K) == sizeof(ggml_fp16_t) + 13*QK_K/16, "wrong q6_K block size/padding"); // In llama.cpp this is only used for intermediate quantization and dot products typedef struct { float d; // delta int8_t qs[QK_K]; // quants int16_t bsums[QK_K/16]; // sum of quants in groups of 16 } block_q8_K; static_assert(sizeof(block_q8_K) == sizeof(float) + QK_K + QK_K/16*sizeof(int16_t), "wrong q8_K block size/padding"); template <int qk, int qr, int qi, bool need_sum, typename block_q_t, int mmq_x, int mmq_y, int nwarps, allocate_tiles_cuda_t allocate_tiles, load_tiles_cuda_t load_tiles, int vdr, vec_dot_q_mul_mat_cuda_t vec_dot> static __device__ __forceinline__ void mul_mat_q( const void * __restrict__ vx, const void * __restrict__ vy, float * __restrict__ dst, const int ncols_x, const int nrows_x, const int ncols_y, const int nrows_y, const int nrows_dst) { const block_q_t * x = (const block_q_t *) vx; const block_q8_1 * y = (const block_q8_1 *) vy; const int blocks_per_row_x = ncols_x / qk; const int blocks_per_col_y = nrows_y / QK8_1; const int blocks_per_warp = WARP_SIZE / qi; const int & ncols_dst = ncols_y; const int row_dst_0 = blockIdx.x*mmq_y; const int & row_x_0 = row_dst_0; const int col_dst_0 = blockIdx.y*mmq_x; const int & col_y_0 = col_dst_0; int * tile_x_ql = nullptr; half2 * tile_x_dm = nullptr; int * tile_x_qh = nullptr; int * tile_x_sc = nullptr; allocate_tiles(&tile_x_ql, &tile_x_dm, &tile_x_qh, &tile_x_sc); __shared__ int tile_y_qs[mmq_x * WARP_SIZE]; __shared__ half2 tile_y_ds[mmq_x * WARP_SIZE/QI8_1]; float sum[mmq_y/WARP_SIZE][mmq_x/nwarps] = {{0.0f}}; for (int ib0 = 0; ib0 < blocks_per_row_x; ib0 += blocks_per_warp) { load_tiles(x + row_x_0*blocks_per_row_x + ib0, tile_x_ql, tile_x_dm, tile_x_qh, tile_x_sc, threadIdx.y, nrows_x-row_x_0-1, threadIdx.x, blocks_per_row_x); #pragma unroll for (int ir = 0; ir < qr; ++ir) { const int kqs = ir*WARP_SIZE + threadIdx.x; const int kbxd = kqs / QI8_1; #pragma unroll for (int i = 0; i < mmq_x; i += nwarps) { const int col_y_eff = min(col_y_0 + threadIdx.y + i, ncols_y-1); // to prevent out-of-bounds memory accesses const block_q8_1 * by0 = &y[col_y_eff*blocks_per_col_y + ib0 * (qk/QK8_1) + kbxd]; const int index_y = (threadIdx.y + i) * WARP_SIZE + kqs % WARP_SIZE; tile_y_qs[index_y] = get_int_from_int8_aligned(by0->qs, threadIdx.x % QI8_1); } #pragma unroll for (int ids0 = 0; ids0 < mmq_x; ids0 += nwarps * QI8_1) { const int ids = (ids0 + threadIdx.y * QI8_1 + threadIdx.x / (WARP_SIZE/QI8_1)) % mmq_x; const int kby = threadIdx.x % (WARP_SIZE/QI8_1); const int col_y_eff = min(col_y_0 + ids, ncols_y-1); // if the sum is not needed it's faster to transform the scale to f32 ahead of time const half2 * dsi_src = &y[col_y_eff*blocks_per_col_y + ib0 * (qk/QK8_1) + ir*(WARP_SIZE/QI8_1) + kby].ds; half2 * dsi_dst = &tile_y_ds[ids * (WARP_SIZE/QI8_1) + kby]; if (need_sum) { *dsi_dst = *dsi_src; } else { float * dfi_dst = (float *) dsi_dst; *dfi_dst = __low2half(*dsi_src); } } __syncthreads(); // #pragma unroll // unrolling this loop causes too much register pressure for (int k = ir*WARP_SIZE/qr; k < (ir+1)*WARP_SIZE/qr; k += vdr) { #pragma unroll for (int j = 0; j < mmq_x; j += nwarps) { #pragma unroll for (int i = 0; i < mmq_y; i += WARP_SIZE) { sum[i/WARP_SIZE][j/nwarps] += vec_dot( tile_x_ql, tile_x_dm, tile_x_qh, tile_x_sc, tile_y_qs, tile_y_ds, threadIdx.x + i, threadIdx.y + j, k); } } } __syncthreads(); } } #pragma unroll for (int j = 0; j < mmq_x; j += nwarps) { const int col_dst = col_dst_0 + j + threadIdx.y; if (col_dst >= ncols_dst) { return; } #pragma unroll for (int i = 0; i < mmq_y; i += WARP_SIZE) { const int row_dst = row_dst_0 + threadIdx.x + i; if (row_dst >= nrows_dst) { continue; } dst[col_dst*nrows_dst + row_dst] = sum[i/WARP_SIZE][j/nwarps]; } } } template <int mmq_y, int nwarps, bool need_check> static __device__ __forceinline__ void load_tiles_q4_0( const void * __restrict__ vx, int * __restrict__ x_ql, half2 * __restrict__ x_dm, int * __restrict__ x_qh, int * __restrict__ x_sc, const int & i_offset, const int & i_max, const int & k, const int & blocks_per_row) { (void)x_qh; (void)x_sc; const int kbx = k / QI4_0; const int kqsx = k % QI4_0; const block_q4_0 * bx0 = (const block_q4_0 *) vx; float * x_dmf = (float *) x_dm; #pragma unroll for (int i0 = 0; i0 < mmq_y; i0 += nwarps) { int i = i0 + i_offset; if (need_check) { i = min(i, i_max); } const block_q4_0 * bxi = bx0 + i*blocks_per_row + kbx; x_ql[i * (WARP_SIZE + 1) + k] = get_int_from_uint8(bxi->qs, kqsx); // x_dmf[i * (WARP_SIZE/QI4_0) + i / QI4_0 + kbx] = bxi->d; } const int blocks_per_tile_x_row = WARP_SIZE / QI4_0; const int kbxd = k % blocks_per_tile_x_row; #pragma unroll for (int i0 = 0; i0 < mmq_y; i0 += nwarps * QI4_0) { int i = i0 + i_offset * QI4_0 + k / blocks_per_tile_x_row; if (need_check) { i = min(i, i_max); } const block_q4_0 * bxi = bx0 + i*blocks_per_row + kbxd; x_dmf[i * (WARP_SIZE/QI4_0) + i / QI4_0 + kbxd] = bxi->d; } } template <int mmq_y, int nwarps, bool need_check> static __device__ __forceinline__ void load_tiles_q4_1( const void * __restrict__ vx, int * __restrict__ x_ql, half2 * __restrict__ x_dm, int * __restrict__ x_qh, int * __restrict__ x_sc, const int & i_offset, const int & i_max, const int & k, const int & blocks_per_row) { GGML_UNUSED(x_qh); GGML_UNUSED(x_sc); GGML_CUDA_ASSUME(i_offset >= 0); GGML_CUDA_ASSUME(i_offset < nwarps); GGML_CUDA_ASSUME(k >= 0); GGML_CUDA_ASSUME(k < WARP_SIZE); const int kbx = k / QI4_1; const int kqsx = k % QI4_1; const block_q4_1 * bx0 = (const block_q4_1 *) vx; #pragma unroll for (int i0 = 0; i0 < mmq_y; i0 += nwarps) { int i = i0 + i_offset; if (need_check) { i = min(i, i_max); } const block_q4_1 * bxi = bx0 + i*blocks_per_row + kbx; x_ql[i * (WARP_SIZE + 1) + k] = get_int_from_uint8_aligned(bxi->qs, kqsx); } const int blocks_per_tile_x_row = WARP_SIZE / QI4_1; const int kbxd = k % blocks_per_tile_x_row; #pragma unroll for (int i0 = 0; i0 < mmq_y; i0 += nwarps * QI4_1) { int i = i0 + i_offset * QI4_1 + k / blocks_per_tile_x_row; if (need_check) { i = min(i, i_max); } const block_q4_1 * bxi = bx0 + i*blocks_per_row + kbxd; x_dm[i * (WARP_SIZE/QI4_1) + i / QI4_1 + kbxd] = bxi->dm; } } template <int mmq_y> static __device__ __forceinline__ void allocate_tiles_q4_0(int ** x_ql, half2 ** x_dm, int ** x_qh, int ** x_sc) { (void)x_qh; (void)x_sc; __shared__ int tile_x_qs[mmq_y * (WARP_SIZE) + mmq_y]; __shared__ float tile_x_d[mmq_y * (WARP_SIZE/QI4_0) + mmq_y/QI4_0]; *x_ql = tile_x_qs; *x_dm = (half2 *) tile_x_d; } template <int mmq_y> static __device__ __forceinline__ void allocate_tiles_q4_1(int ** x_ql, half2 ** x_dm, int ** x_qh, int ** x_sc) { GGML_UNUSED(x_qh); GGML_UNUSED(x_sc); __shared__ int tile_x_qs[mmq_y * (WARP_SIZE) + + mmq_y]; __shared__ half2 tile_x_dm[mmq_y * (WARP_SIZE/QI4_1) + mmq_y/QI4_1]; *x_ql = tile_x_qs; *x_dm = tile_x_dm; } static __device__ __forceinline__ void dequantize_q4_0(const void * vx, const int ib, const int iqs, dfloat2 & v){ const block_q4_0 * x = (const block_q4_0 *) vx; const dfloat d = x[ib].d; const int vui = x[ib].qs[iqs]; v.x = vui & 0xF; v.y = vui >> 4; #ifdef GGML_CUDA_F16 v = __hsub2(v, {8.0f, 8.0f}); v = __hmul2(v, {d, d}); #else v.x = (v.x - 8.0f) * d; v.y = (v.y - 8.0f) * d; #endif // GGML_CUDA_F16 } static __device__ __forceinline__ void dequantize_q4_1(const void * vx, const int ib, const int iqs, dfloat2 & v){ const block_q4_1 * x = (const block_q4_1 *) vx; const dfloat d = __low2half(x[ib].dm); const dfloat m = __high2half(x[ib].dm); const int vui = x[ib].qs[iqs]; v.x = vui & 0xF; v.y = vui >> 4; #ifdef GGML_CUDA_F16 v = __hmul2(v, {d, d}); v = __hadd2(v, {m, m}); #else v.x = (v.x * d) + m; v.y = (v.y * d) + m; #endif // GGML_CUDA_F16 } static __device__ __forceinline__ void dequantize_q5_0(const void * vx, const int ib, const int iqs, dfloat2 & v){ const block_q5_0 * x = (const block_q5_0 *) vx; const dfloat d = x[ib].d; uint32_t qh; memcpy(&qh, x[ib].qh, sizeof(qh)); const int xh_0 = ((qh >> (iqs + 0)) << 4) & 0x10; const int xh_1 = ((qh >> (iqs + 12)) ) & 0x10; v.x = ((x[ib].qs[iqs] & 0xf) | xh_0); v.y = ((x[ib].qs[iqs] >> 4) | xh_1); #ifdef GGML_CUDA_F16 v = __hsub2(v, {16.0f, 16.0f}); v = __hmul2(v, {d, d}); #else v.x = (v.x - 16.0f) * d; v.y = (v.y - 16.0f) * d; #endif // GGML_CUDA_F16 } static __device__ __forceinline__ void dequantize_q5_1(const void * vx, const int ib, const int iqs, dfloat2 & v){ const block_q5_1 * x = (const block_q5_1 *) vx; const dfloat d = __low2half(x[ib].dm); const dfloat m = __high2half(x[ib].dm); uint32_t qh; memcpy(&qh, x[ib].qh, sizeof(qh)); const int xh_0 = ((qh >> (iqs + 0)) << 4) & 0x10; const int xh_1 = ((qh >> (iqs + 12)) ) & 0x10; v.x = ((x[ib].qs[iqs] & 0xf) | xh_0); v.y = ((x[ib].qs[iqs] >> 4) | xh_1); #ifdef GGML_CUDA_F16 v = __hmul2(v, {d, d}); v = __hadd2(v, {m, m}); #else v.x = (v.x * d) + m; v.y = (v.y * d) + m; #endif // GGML_CUDA_F16 } static __device__ __forceinline__ void dequantize_q8_0(const void * vx, const int ib, const int iqs, dfloat2 & v){ const block_q8_0 * x = (const block_q8_0 *) vx; const dfloat d = x[ib].d; v.x = x[ib].qs[iqs + 0]; v.y = x[ib].qs[iqs + 1]; #ifdef GGML_CUDA_F16 v = __hmul2(v, {d, d}); #else v.x *= d; v.y *= d; #endif // GGML_CUDA_F16 } template <int qk, int qr, dequantize_kernel_t dequantize_kernel, typename dst_t> static __device__ void dequantize_block(const void * __restrict__ vx, dst_t * __restrict__ y, const int k) { const int i = 2*(blockDim.x*blockIdx.x + threadIdx.x); if (i >= k) { return; } const int ib = i/qk; // block index const int iqs = (i%qk)/qr; // quant index const int iybs = i - i%qk; // y block start index const int y_offset = qr == 1 ? 1 : qk/2; // dequantize dfloat2 v; dequantize_kernel(vx, ib, iqs, v); y[iybs + iqs + 0] = v.x; y[iybs + iqs + y_offset] = v.y; } template<typename dst_t> static __device__ void dequantize_block_q4_0(const void * __restrict__ vx, dst_t * __restrict__ yy, int nb32) { const int64_t i = blockIdx.x; // assume 32 threads const int tid = threadIdx.x; const int il = tid/8; const int ir = tid%8; const int64_t ib = 8*i + ir; if (ib >= nb32) { return; } dst_t * y = yy + 256*i + 32*ir + 4*il; const block_q4_0 * x = (const block_q4_0 *)vx + ib; const float d = __half2float(x->d); const float dm = -8*d; const uint8_t * q = x->qs + 4*il; for (int l = 0; l < 4; ++l) { y[l+ 0] = d * (q[l] & 0xF) + dm; y[l+16] = d * (q[l] >> 4) + dm; } } template<typename dst_t> static __device__ void dequantize_block_q4_1(const void * __restrict__ vx, dst_t * __restrict__ yy, int nb32) { const int64_t i = blockIdx.x; // assume 32 threads const int tid = threadIdx.x; const int il = tid/8; const int ir = tid%8; const int64_t ib = 8*i + ir; if (ib >= nb32) { return; } dst_t * y = yy + 256*i + 32*ir + 4*il; const block_q4_1 * x = (const block_q4_1 *)vx + ib; const float2 d = __half22float2(x->dm); const uint8_t * q = x->qs + 4*il; for (int l = 0; l < 4; ++l) { y[l+ 0] = d.x * (q[l] & 0xF) + d.y; y[l+16] = d.x * (q[l] >> 4) + d.y; } } //================================== k-quants template<typename dst_t> static __device__ void dequantize_block_q2_K(const void * __restrict__ vx, dst_t * __restrict__ yy) { const int i = blockIdx.x; const block_q2_K * x = (const block_q2_K *) vx; const int tid = threadIdx.x; #if QK_K == 256 const int n = tid/32; const int l = tid - 32*n; const int is = 8*n + l/16; const uint8_t q = x[i].qs[32*n + l]; dst_t * y = yy + i*QK_K + 128*n; float dall = __low2half(x[i].dm); float dmin = __high2half(x[i].dm); y[l+ 0] = dall * (x[i].scales[is+0] & 0xF) * ((q >> 0) & 3) - dmin * (x[i].scales[is+0] >> 4); y[l+32] = dall * (x[i].scales[is+2] & 0xF) * ((q >> 2) & 3) - dmin * (x[i].scales[is+2] >> 4); y[l+64] = dall * (x[i].scales[is+4] & 0xF) * ((q >> 4) & 3) - dmin * (x[i].scales[is+4] >> 4); y[l+96] = dall * (x[i].scales[is+6] & 0xF) * ((q >> 6) & 3) - dmin * (x[i].scales[is+6] >> 4); #else const int is = tid/16; // 0 or 1 const int il = tid%16; // 0...15 const uint8_t q = x[i].qs[il] >> (2*is); dst_t * y = yy + i*QK_K + 16*is + il; float dall = __low2half(x[i].dm); float dmin = __high2half(x[i].dm); y[ 0] = dall * (x[i].scales[is+0] & 0xF) * ((q >> 0) & 3) - dmin * (x[i].scales[is+0] >> 4); y[32] = dall * (x[i].scales[is+2] & 0xF) * ((q >> 4) & 3) - dmin * (x[i].scales[is+2] >> 4); #endif } template<typename dst_t> static __device__ void dequantize_block_q3_K(const void * __restrict__ vx, dst_t * __restrict__ yy) { const int i = blockIdx.x; const block_q3_K * x = (const block_q3_K *) vx; #if QK_K == 256 const int r = threadIdx.x/4; const int tid = r/2; const int is0 = r%2; const int l0 = 16*is0 + 4*(threadIdx.x%4); const int n = tid / 4; const int j = tid - 4*n; uint8_t m = 1 << (4*n + j); int is = 8*n + 2*j + is0; int shift = 2*j; int8_t us = is < 4 ? (x[i].scales[is-0] & 0xF) | (((x[i].scales[is+8] >> 0) & 3) << 4) : is < 8 ? (x[i].scales[is-0] & 0xF) | (((x[i].scales[is+4] >> 2) & 3) << 4) : is < 12 ? (x[i].scales[is-8] >> 4) | (((x[i].scales[is+0] >> 4) & 3) << 4) : (x[i].scales[is-8] >> 4) | (((x[i].scales[is-4] >> 6) & 3) << 4); float d_all = x[i].d; float dl = d_all * (us - 32); dst_t * y = yy + i*QK_K + 128*n + 32*j; const uint8_t * q = x[i].qs + 32*n; const uint8_t * hm = x[i].hmask; for (int l = l0; l < l0+4; ++l) y[l] = dl * ((int8_t)((q[l] >> shift) & 3) - ((hm[l] & m) ? 0 : 4)); #else const int tid = threadIdx.x; const int is = tid/16; // 0 or 1 const int il = tid%16; // 0...15 const int im = il/8; // 0...1 const int in = il%8; // 0...7 dst_t * y = yy + i*QK_K + 16*is + il; const uint8_t q = x[i].qs[il] >> (2*is); const uint8_t h = x[i].hmask[in] >> (2*is + im); const float d = (float)x[i].d; if (is == 0) { y[ 0] = d * ((x[i].scales[0] & 0xF) - 8) * ((int8_t)((q >> 0) & 3) - ((h >> 0) & 1 ? 0 : 4)); y[32] = d * ((x[i].scales[1] & 0xF) - 8) * ((int8_t)((q >> 4) & 3) - ((h >> 4) & 1 ? 0 : 4)); } else { y[ 0] = d * ((x[i].scales[0] >> 4) - 8) * ((int8_t)((q >> 0) & 3) - ((h >> 0) & 1 ? 0 : 4)); y[32] = d * ((x[i].scales[1] >> 4) - 8) * ((int8_t)((q >> 4) & 3) - ((h >> 4) & 1 ? 0 : 4)); } #endif } #if QK_K == 256 static inline __device__ void get_scale_min_k4(int j, const uint8_t * q, uint8_t & d, uint8_t & m) { if (j < 4) { d = q[j] & 63; m = q[j + 4] & 63; } else { d = (q[j+4] & 0xF) | ((q[j-4] >> 6) << 4); m = (q[j+4] >> 4) | ((q[j-0] >> 6) << 4); } } #endif template<typename dst_t> static __device__ void dequantize_block_q4_K(const void * __restrict__ vx, dst_t * __restrict__ yy) { const block_q4_K * x = (const block_q4_K *) vx; const int i = blockIdx.x; #if QK_K == 256 // assume 32 threads const int tid = threadIdx.x; const int il = tid/8; const int ir = tid%8; const int is = 2*il; const int n = 4; dst_t * y = yy + i*QK_K + 64*il + n*ir; const float dall = __low2half(x[i].dm); const float dmin = __high2half(x[i].dm); const uint8_t * q = x[i].qs + 32*il + n*ir; uint8_t sc, m; get_scale_min_k4(is + 0, x[i].scales, sc, m); const float d1 = dall * sc; const float m1 = dmin * m; get_scale_min_k4(is + 1, x[i].scales, sc, m); const float d2 = dall * sc; const float m2 = dmin * m; for (int l = 0; l < n; ++l) { y[l + 0] = d1 * (q[l] & 0xF) - m1; y[l +32] = d2 * (q[l] >> 4) - m2; } #else const int tid = threadIdx.x; const uint8_t * q = x[i].qs; dst_t * y = yy + i*QK_K; const float d = (float)x[i].dm[0]; const float m = (float)x[i].dm[1]; y[tid+ 0] = d * (x[i].scales[0] & 0xF) * (q[tid] & 0xF) - m * (x[i].scales[0] >> 4); y[tid+32] = d * (x[i].scales[1] & 0xF) * (q[tid] >> 4) - m * (x[i].scales[1] >> 4); #endif } template<typename dst_t> static __device__ void dequantize_block_q5_K(const void * __restrict__ vx, dst_t * __restrict__ yy) { const block_q5_K * x = (const block_q5_K *) vx; const int i = blockIdx.x; #if QK_K == 256 // assume 64 threads - this is very slightly better than the one below const int tid = threadIdx.x; const int il = tid/16; // il is in 0...3 const int ir = tid%16; // ir is in 0...15 const int is = 2*il; // is is in 0...6 dst_t * y = yy + i*QK_K + 64*il + 2*ir; const float dall = __low2half(x[i].dm); const float dmin = __high2half(x[i].dm); const uint8_t * ql = x[i].qs + 32*il + 2*ir; const uint8_t * qh = x[i].qh + 2*ir; uint8_t sc, m; get_scale_min_k4(is + 0, x[i].scales, sc, m); const float d1 = dall * sc; const float m1 = dmin * m; get_scale_min_k4(is + 1, x[i].scales, sc, m); const float d2 = dall * sc; const float m2 = dmin * m; uint8_t hm = 1 << (2*il); y[ 0] = d1 * ((ql[ 0] & 0xF) + (qh[ 0] & hm ? 16 : 0)) - m1; y[ 1] = d1 * ((ql[ 1] & 0xF) + (qh[ 1] & hm ? 16 : 0)) - m1; hm <<= 1; y[32] = d2 * ((ql[ 0] >> 4) + (qh[ 0] & hm ? 16 : 0)) - m2; y[33] = d2 * ((ql[ 1] >> 4) + (qh[ 1] & hm ? 16 : 0)) - m2; #else const int tid = threadIdx.x; const uint8_t q = x[i].qs[tid]; const int im = tid/8; // 0...3 const int in = tid%8; // 0...7 const int is = tid/16; // 0 or 1 const uint8_t h = x[i].qh[in] >> im; const float d = x[i].d; dst_t * y = yy + i*QK_K + tid; y[ 0] = d * x[i].scales[is+0] * ((q & 0xF) - ((h >> 0) & 1 ? 0 : 16)); y[32] = d * x[i].scales[is+2] * ((q >> 4) - ((h >> 4) & 1 ? 0 : 16)); #endif } template<typename dst_t> static __device__ void dequantize_block_q6_K(const void * __restrict__ vx, dst_t * __restrict__ yy) { const block_q6_K * x = (const block_q6_K *) vx; const int64_t i = blockIdx.x; #if QK_K == 256 // assume 64 threads - this is very slightly better than the one below const int64_t tid = threadIdx.x; const int64_t ip = tid/32; // ip is 0 or 1 const int64_t il = tid - 32*ip; // 0...32 const int64_t is = 8*ip + il/16; dst_t * y = yy + i*QK_K + 128*ip + il; const float d = x[i].d; const uint8_t * ql = x[i].ql + 64*ip + il; const uint8_t qh = x[i].qh[32*ip + il]; const int8_t * sc = x[i].scales + is; y[ 0] = d * sc[0] * ((int8_t)((ql[ 0] & 0xF) | (((qh >> 0) & 3) << 4)) - 32); y[32] = d * sc[2] * ((int8_t)((ql[32] & 0xF) | (((qh >> 2) & 3) << 4)) - 32); y[64] = d * sc[4] * ((int8_t)((ql[ 0] >> 4) | (((qh >> 4) & 3) << 4)) - 32); y[96] = d * sc[6] * ((int8_t)((ql[32] >> 4) | (((qh >> 6) & 3) << 4)) - 32); #else // assume 32 threads const int64_t tid = threadIdx.x; const int64_t ip = tid/16; // 0 or 1 const int64_t il = tid - 16*ip; // 0...15 dst_t * y = yy + i*QK_K + 16*ip + il; const float d = x[i].d; const uint8_t ql = x[i].ql[16*ip + il]; const uint8_t qh = x[i].qh[il] >> (2*ip); const int8_t * sc = x[i].scales; y[ 0] = d * sc[ip+0] * ((int8_t)((ql & 0xF) | (((qh >> 0) & 3) << 4)) - 32); y[32] = d * sc[ip+2] * ((int8_t)((ql >> 4) | (((qh >> 4) & 3) << 4)) - 32); #endif } template<typename dst_t> static __device__ void dequantize_block_q8_0(const void * __restrict__ vx, dst_t * __restrict__ yy, int nb32) { const int i = blockIdx.x; // assume 32 threads const int tid = threadIdx.x; const int il = tid/8; const int ir = tid%8; const int ib = 8*i + ir; if (ib >= nb32) { return; } dst_t * y = yy + 256*i + 32*ir + 8*il; const block_q8_0 * x = (const block_q8_0 *)vx + ib; const float d = __half2float(x->d); const int8_t * q = x->qs + 8*il; for (int l = 0; l < 8; ++l) { y[l] = d * q[l]; } } template<typename dst_t> static __device__ void dequantize_block_q8_K(const void * __restrict__ vx, dst_t * __restrict__ yy) { const block_q8_K * x = (const block_q8_K *) vx; const int i = blockIdx.x; #if QK_K == 256 // assume 32 threads const int tid = threadIdx.x; const int il = tid/8; const int ir = tid%8; const int n = 8; dst_t * y = yy + i*QK_K + 64*il + n*ir; const int8_t * q = x[i].qs + 64*il + n*ir; for (int l = 0; l < n; ++l) { y[l] = q[l] * x[i].d; } #else const int tid = threadIdx.x; const uint8_t * q = x[i].qs; float * y = yy + i*QK_K; y[tid] = x[i].d * x[i].scales[0]; #endif } template<typename dst_t> static __device__ void dequantize_block_q5_0(const void * __restrict__ vx, dst_t * __restrict__ yy, int nb32) { return dequantize_block<QK5_0, QR5_0, dequantize_q5_0>(vx, yy, nb32); } template<typename dst_t> static __device__ void dequantize_block_q5_1(const void * __restrict__ vx, dst_t * __restrict__ yy, int nb32) { return dequantize_block<QK5_1, QR5_1, dequantize_q5_1>(vx, yy, nb32); } #define DEQUANTIZE_K(QNAME) \ extern "C" __global__ void dequantize_block_##QNAME##_f32(const void * __restrict__ vx, float * __restrict__ y) { \ dequantize_block_##QNAME(vx, y); \ } \ extern "C" __global__ void dequantize_block_##QNAME##_f16(const void * __restrict__ vx, half * __restrict__ y) { \ dequantize_block_##QNAME(vx, y); \ } \ #define DEQUANTIZE(QNAME) \ extern "C" __global__ void dequantize_block_##QNAME##_f32(const void * __restrict__ vx, float * __restrict__ y, const int k) { \ dequantize_block_##QNAME(vx, y, k); \ } \ extern "C" __global__ void dequantize_block_##QNAME##_f16(const void * __restrict__ vx, half * __restrict__ y, const int k) { \ dequantize_block_##QNAME(vx, y, k); \ } \ DEQUANTIZE_K(q2_K) DEQUANTIZE_K(q3_K) DEQUANTIZE_K(q4_K) DEQUANTIZE_K(q5_K) DEQUANTIZE_K(q6_K) DEQUANTIZE_K(q8_K) DEQUANTIZE(q4_0) DEQUANTIZE(q4_1) DEQUANTIZE(q5_0) DEQUANTIZE(q5_1) DEQUANTIZE(q8_0) template <int qk, int qr, dequantize_kernel_t dequantize_kernel> static __device__ void dequantize_mul_mat_vec(const void * __restrict__ vx, const dfloat * __restrict__ y, float * __restrict__ dst, const int ncols, const int nrows) { // qk = quantized weights per x block // qr = number of quantized weights per data value in x block const int row = blockIdx.x*blockDim.y + threadIdx.y; if (row >= nrows) { return; } const int tid = threadIdx.x; const int iter_stride = 2*GGML_CUDA_DMMV_X; const int vals_per_iter = iter_stride / WARP_SIZE; // num quantized vals per thread and i iter const int y_offset = qr == 1 ? 1 : qk/2; // partial sum for each thread #ifdef GGML_CUDA_F16 half2 tmp = {0.0f, 0.0f}; // two sums for f16 to take advantage of half2 intrinsics #else float tmp = 0.0f; #endif // GGML_CUDA_F16 for (int i = 0; i < ncols; i += iter_stride) { const int col = i + vals_per_iter*tid; const int ib = (row*ncols + col)/qk; // x block index const int iqs = (col%qk)/qr; // x quant index const int iybs = col - col%qk; // y block start index // processing >2 values per i iter is faster for fast GPUs #pragma unroll for (int j = 0; j < vals_per_iter; j += 2) { // process 2 vals per j iter // dequantize // for qr = 2 the iqs needs to increase by 1 per j iter because 2 weights per data val dfloat2 v; dequantize_kernel(vx, ib, iqs + j/qr, v); // matrix multiplication // for qr = 2 the y index needs to increase by 1 per j iter because of y_offset = qk/2 #ifdef GGML_CUDA_F16 tmp += __hmul2(v, { y[iybs + iqs + j/qr + 0], y[iybs + iqs + j/qr + y_offset] }); #else tmp += v.x * y[iybs + iqs + j/qr + 0]; tmp += v.y * y[iybs + iqs + j/qr + y_offset]; #endif // GGML_CUDA_F16 } } // sum up partial sums and write back result #pragma unroll for (int mask = 16; mask > 0; mask >>= 1) { tmp += __shfl_xor_sync(0xffffffff, tmp, mask, 32); } if (tid == 0) { #ifdef GGML_CUDA_F16 dst[row] = tmp.x + tmp.y; #else dst[row] = tmp; #endif // GGML_CUDA_F16 } } extern "C" __global__ void dequantize_mul_mat_vec_q4_0_cuda(const void * vx, const dfloat * y, float * dst, const int ncols, const int nrows) { dequantize_mul_mat_vec<QK4_0, QR4_0, dequantize_q4_0>(vx, y, dst, ncols, nrows); } extern "C" __global__ void dequantize_mul_mat_vec_q4_1_cuda(const void * vx, const dfloat * y, float * dst, const int ncols, const int nrows) { dequantize_mul_mat_vec<QK4_1, QR4_1, dequantize_q4_1>(vx, y, dst, ncols, nrows); } extern "C" __global__ void dequantize_mul_mat_vec_q5_0_cuda(const void * vx, const dfloat * y, float * dst, const int ncols, const int nrows) { dequantize_mul_mat_vec<QK5_0, QR5_0, dequantize_q5_0>(vx, y, dst, ncols, nrows); } extern "C" __global__ void dequantize_mul_mat_vec_q5_1_cuda(const void * vx, const dfloat * y, float * dst, const int ncols, const int nrows) { dequantize_mul_mat_vec<QK5_1, QR5_1, dequantize_q5_1>(vx, y, dst, ncols, nrows); } extern "C" __global__ void dequantize_mul_mat_vec_q8_0_cuda(const void * vx, const dfloat * y, float * dst, const int ncols, const int nrows) { dequantize_mul_mat_vec<QK8_0, QR8_0, dequantize_q8_0>(vx, y, dst, ncols, nrows); } extern "C" __global__ void dequantize_mul_mat_vec_q2_k(const void * __restrict__ vx, const float * __restrict__ yy, float * __restrict__ dst, const int ncols, int nrows) { static_assert(16%K_QUANTS_PER_ITERATION == 0, "16 must be divisible by K_QUANTS_PER_ITERATION"); const int row = blockIdx.x*blockDim.y + threadIdx.y; if (row > nrows) return; const int num_blocks_per_row = ncols / QK_K; const int ib0 = row*num_blocks_per_row; const block_q2_K * x = (const block_q2_K *)vx + ib0; float tmp = 0; // partial sum for thread in warp #if QK_K == 256 const int tid = threadIdx.x/K_QUANTS_PER_ITERATION; // 0...31 or 0...15 const int ix = threadIdx.x%K_QUANTS_PER_ITERATION; // 0 or 0,1 const int step = 16/K_QUANTS_PER_ITERATION; const int im = tid/step; // 0 or 1. 0 computes 0..., 1 computes 128... const int in = tid - step*im; // 0...15 or 0...7 const int l0 = K_QUANTS_PER_ITERATION*in; // 0...15 or 0...14 in steps of 2 const int q_offset = 32*im + l0; const int s_offset = 8*im; const int y_offset = 128*im + l0; uint32_t aux[4]; const uint8_t * d = (const uint8_t *)aux; const uint8_t * m = (const uint8_t *)(aux + 2); for (int i = ix; i < num_blocks_per_row; i += K_QUANTS_PER_ITERATION) { const float * y = yy + i * QK_K + y_offset; const uint8_t * q = x[i].qs + q_offset; const float dall = __low2half(x[i].dm); const float dmin = __high2half(x[i].dm); const uint32_t * a = (const uint32_t *)(x[i].scales + s_offset); aux[0] = a[0] & 0x0f0f0f0f; aux[1] = a[1] & 0x0f0f0f0f; aux[2] = (a[0] >> 4) & 0x0f0f0f0f; aux[3] = (a[1] >> 4) & 0x0f0f0f0f; float sum1 = 0, sum2 = 0; for (int l = 0; l < K_QUANTS_PER_ITERATION; ++l) { sum1 += y[l+ 0] * d[0] * ((q[l+ 0] >> 0) & 3) + y[l+32] * d[2] * ((q[l+ 0] >> 2) & 3) + y[l+64] * d[4] * ((q[l+ 0] >> 4) & 3) + y[l+96] * d[6] * ((q[l+ 0] >> 6) & 3) + y[l+16] * d[1] * ((q[l+16] >> 0) & 3) + y[l+48] * d[3] * ((q[l+16] >> 2) & 3) + y[l+80] * d[5] * ((q[l+16] >> 4) & 3) +y[l+112] * d[7] * ((q[l+16] >> 6) & 3); sum2 += y[l+ 0] * m[0] + y[l+32] * m[2] + y[l+64] * m[4] + y[ l+96] * m[6] + y[l+16] * m[1] + y[l+48] * m[3] + y[l+80] * m[5] + y[l+112] * m[7]; } tmp += dall * sum1 - dmin * sum2; } #else const int tid = threadIdx.x/(2*K_QUANTS_PER_ITERATION); // 0...15 or 0...7 const int ix = threadIdx.x%(2*K_QUANTS_PER_ITERATION); // 0....1 or 0...3 const int offset = tid * K_QUANTS_PER_ITERATION; uint32_t uaux[2]; const uint8_t * d = (const uint8_t *)uaux; for (int i = ix; i < num_blocks_per_row; i += 2*K_QUANTS_PER_ITERATION) { const float * y = yy + i * QK_K + offset; const uint8_t * q = x[i].qs + offset; const uint32_t * s = (const uint32_t *)x[i].scales; uaux[0] = s[0] & 0x0f0f0f0f; uaux[1] = (s[0] >> 4) & 0x0f0f0f0f; const float2 dall = __half22float2(x[i].dm); float sum1 = 0, sum2 = 0; for (int l = 0; l < K_QUANTS_PER_ITERATION; ++l) { const uint8_t ql = q[l]; sum1 += y[l+ 0] * d[0] * ((ql >> 0) & 3) + y[l+16] * d[1] * ((ql >> 2) & 3) + y[l+32] * d[2] * ((ql >> 4) & 3) + y[l+48] * d[3] * ((ql >> 6) & 3); sum2 += y[l+0] * d[4] + y[l+16] * d[5] + y[l+32] * d[6] + y[l+48] * d[7]; } tmp += dall.x * sum1 - dall.y * sum2; } #endif // sum up partial sums and write back result #pragma unroll for (int mask = 16; mask > 0; mask >>= 1) { tmp += __shfl_xor_sync(0xffffffff, tmp, mask, 32); } if (threadIdx.x == 0) { dst[row] = tmp; } } extern "C" __global__ void dequantize_mul_mat_vec_q3_k(const void * __restrict__ vx, const float * __restrict__ yy, float * __restrict__ dst, const int ncols, int nrows) { const int row = blockIdx.x*blockDim.y + threadIdx.y; if (row > nrows) return; const int num_blocks_per_row = ncols / QK_K; const int ib0 = row*num_blocks_per_row; const block_q3_K * x = (const block_q3_K *)vx + ib0; float tmp = 0; // partial sum for thread in warp #if QK_K == 256 const uint16_t kmask1 = 0x0303; const uint16_t kmask2 = 0x0f0f; const int tid = threadIdx.x/K_QUANTS_PER_ITERATION; // 0...31 or 0...16 const int ix = threadIdx.x%K_QUANTS_PER_ITERATION; // 0 or 0,1 const int n = K_QUANTS_PER_ITERATION; // iterations in the inner loop const int step = 16/K_QUANTS_PER_ITERATION; const int im = tid/step; // 0 or 1. 0 computes 0..., 1 computes 128... const int in = tid - step*im; // 0....15 or 0...7 const uint8_t m = 1 << (4*im); const int l0 = n*in; // 0...15 or 0...14 in steps of 2 const int q_offset = 32*im + l0; const int y_offset = 128*im + l0; uint16_t utmp[4]; const int8_t * s = (const int8_t *)utmp; const uint16_t s_shift = 4*im; for (int i = ix; i < num_blocks_per_row; i += K_QUANTS_PER_ITERATION) { const float * y = yy + i * QK_K + y_offset; const uint8_t * q = x[i].qs + q_offset; const uint8_t * h = x[i].hmask + l0; const uint16_t * a = (const uint16_t *)x[i].scales; utmp[0] = ((a[0] >> s_shift) & kmask2) | (((a[4] >> (s_shift + 0)) & kmask1) << 4); utmp[1] = ((a[1] >> s_shift) & kmask2) | (((a[5] >> (s_shift + 0)) & kmask1) << 4); utmp[2] = ((a[2] >> s_shift) & kmask2) | (((a[4] >> (s_shift + 2)) & kmask1) << 4); utmp[3] = ((a[3] >> s_shift) & kmask2) | (((a[5] >> (s_shift + 2)) & kmask1) << 4); const float d = x[i].d; float sum = 0; for (int l = 0; l < n; ++l) { sum += y[l+ 0] * (s[0] - 32) * (((q[l] >> 0) & 3) - (h[l] & (m << 0) ? 0 : 4)) + y[l+32] * (s[2] - 32) * (((q[l] >> 2) & 3) - (h[l] & (m << 1) ? 0 : 4)) + y[l+64] * (s[4] - 32) * (((q[l] >> 4) & 3) - (h[l] & (m << 2) ? 0 : 4)) + y[l+96] * (s[6] - 32) * (((q[l] >> 6) & 3) - (h[l] & (m << 3) ? 0 : 4)); sum += y[l+16] * (s[1] - 32) * (((q[l+16] >> 0) & 3) - (h[l+16] & (m << 0) ? 0 : 4)) + y[l+48] * (s[3] - 32) * (((q[l+16] >> 2) & 3) - (h[l+16] & (m << 1) ? 0 : 4)) + y[l+80] * (s[5] - 32) * (((q[l+16] >> 4) & 3) - (h[l+16] & (m << 2) ? 0 : 4)) + y[l+112] * (s[7] - 32) * (((q[l+16] >> 6) & 3) - (h[l+16] & (m << 3) ? 0 : 4)); } tmp += d * sum; } #else const int tid = threadIdx.x/(2*K_QUANTS_PER_ITERATION); // 0...15 or 0...7 const int ix = threadIdx.x%(2*K_QUANTS_PER_ITERATION); // 0....1 or 0...3 const int offset = tid * K_QUANTS_PER_ITERATION; // 0...15 or 0...14 const int in = offset/8; // 0 or 1 const int im = offset%8; // 0...7 for (int i = ix; i < num_blocks_per_row; i += 2*K_QUANTS_PER_ITERATION) { const float * y = yy + i * QK_K + offset; const uint8_t * q = x[i].qs + offset; const uint8_t * s = x[i].scales; const float dall = (float)x[i].d; float sum = 0; for (int l = 0; l < K_QUANTS_PER_ITERATION; ++l) { const uint8_t hl = x[i].hmask[im+l] >> in; const uint8_t ql = q[l]; sum += y[l+ 0] * dall * ((s[0] & 0xF) - 8) * ((int8_t)((ql >> 0) & 3) - ((hl >> 0) & 1 ? 0 : 4)) + y[l+16] * dall * ((s[0] >> 4) - 8) * ((int8_t)((ql >> 2) & 3) - ((hl >> 2) & 1 ? 0 : 4)) + y[l+32] * dall * ((s[1] & 0xF) - 8) * ((int8_t)((ql >> 4) & 3) - ((hl >> 4) & 1 ? 0 : 4)) + y[l+48] * dall * ((s[1] >> 4) - 8) * ((int8_t)((ql >> 6) & 3) - ((hl >> 6) & 1 ? 0 : 4)); } tmp += sum; } #endif // sum up partial sums and write back result #pragma unroll for (int mask = 16; mask > 0; mask >>= 1) { tmp += __shfl_xor_sync(0xffffffff, tmp, mask, 32); } if (threadIdx.x == 0) { dst[row] = tmp; } } extern "C" __global__ void dequantize_mul_mat_vec_q4_k(const void * __restrict__ vx, const float * __restrict__ yy, float * __restrict__ dst, const int ncols, int nrows) { const int row = blockIdx.x*blockDim.y + threadIdx.y; if (row > nrows) return; const int num_blocks_per_row = ncols / QK_K; const int ib0 = row*num_blocks_per_row; const block_q4_K * x = (const block_q4_K *)vx + ib0; #if QK_K == 256 const uint16_t kmask1 = 0x3f3f; const uint16_t kmask2 = 0x0f0f; const uint16_t kmask3 = 0xc0c0; const int tid = threadIdx.x/K_QUANTS_PER_ITERATION; // 0...31 or 0...16 const int ix = threadIdx.x%K_QUANTS_PER_ITERATION; // 0 or 0,1 const int step = 8/K_QUANTS_PER_ITERATION; // 8 or 4 const int il = tid/step; // 0...3 const int ir = tid - step*il; // 0...7 or 0...3 const int n = 2 * K_QUANTS_PER_ITERATION; // 2 or 4 const int im = il/2; // 0 or 1. 0 computes 0,32 + 128,160, 1 computes 64,96 + 192,224 const int in = il%2; const int l0 = n*(2*ir + in); const int q_offset = 32*im + l0; const int y_offset = 64*im + l0; uint16_t aux[4]; const uint8_t * sc = (const uint8_t *)aux; #if K_QUANTS_PER_ITERATION == 2 uint32_t q32[4]; const uint8_t * q4 = (const uint8_t *)q32; #else uint16_t q16[4]; const uint8_t * q4 = (const uint8_t *)q16; #endif float tmp = 0; // partial sum for thread in warp for (int i = ix; i < num_blocks_per_row; i += K_QUANTS_PER_ITERATION) { const float * y1 = yy + i*QK_K + y_offset; const float * y2 = y1 + 128; const float dall = __low2half(x[i].dm); const float dmin = __high2half(x[i].dm); const uint16_t * a = (const uint16_t *)x[i].scales; aux[0] = a[im+0] & kmask1; aux[1] = a[im+2] & kmask1; aux[2] = ((a[im+4] >> 0) & kmask2) | ((a[im+0] & kmask3) >> 2); aux[3] = ((a[im+4] >> 4) & kmask2) | ((a[im+2] & kmask3) >> 2); #if K_QUANTS_PER_ITERATION == 2 const uint32_t * q1 = (const uint32_t *)(x[i].qs + q_offset); const uint32_t * q2 = q1 + 16; q32[0] = q1[0] & 0x0f0f0f0f; q32[1] = q1[0] & 0xf0f0f0f0; q32[2] = q2[0] & 0x0f0f0f0f; q32[3] = q2[0] & 0xf0f0f0f0; float4 s = {0.f, 0.f, 0.f, 0.f}; float smin = 0; for (int l = 0; l < 4; ++l) { s.x += y1[l] * q4[l+0]; s.y += y1[l+32] * q4[l+ 4]; s.z += y2[l] * q4[l+8]; s.w += y2[l+32] * q4[l+12]; smin += y1[l] * sc[2] + y1[l+32] * sc[3] + y2[l] * sc[6] + y2[l+32] * sc[7]; } tmp += dall * (s.x * sc[0] + s.y * sc[1] * 1.f/16.f + s.z * sc[4] + s.w * sc[5] * 1.f/16.f) - dmin * smin; #else const uint16_t * q1 = (const uint16_t *)(x[i].qs + q_offset); const uint16_t * q2 = q1 + 32; q16[0] = q1[0] & 0x0f0f; q16[1] = q1[0] & 0xf0f0; q16[2] = q2[0] & 0x0f0f; q16[3] = q2[0] & 0xf0f0; float4 s = {0.f, 0.f, 0.f, 0.f}; float smin = 0; for (int l = 0; l < 2; ++l) { s.x += y1[l] * q4[l+0]; s.y += y1[l+32] * q4[l+2]; s.z += y2[l] * q4[l+4]; s.w += y2[l+32] * q4[l+6]; smin += y1[l] * sc[2] + y1[l+32] * sc[3] + y2[l] * sc[6] + y2[l+32] * sc[7]; } tmp += dall * (s.x * sc[0] + s.y * sc[1] * 1.f/16.f + s.z * sc[4] + s.w * sc[5] * 1.f/16.f) - dmin * smin; #endif } #else const int tid = threadIdx.x/(2*K_QUANTS_PER_ITERATION); // 0...15 const int ix = threadIdx.x%(2*K_QUANTS_PER_ITERATION); const int step = tid * K_QUANTS_PER_ITERATION; uint16_t aux16[2]; const uint8_t * s = (const uint8_t *)aux16; float tmp = 0; for (int i = ix; i < num_blocks_per_row; i += 2*K_QUANTS_PER_ITERATION) { const uint8_t * q = x[i].qs + step; const float * y = yy + i*QK_K + step; const uint16_t * a = (const uint16_t *)x[i].scales; aux16[0] = a[0] & 0x0f0f; aux16[1] = (a[0] >> 4) & 0x0f0f; const float d = (float)x[i].dm[0]; const float m = (float)x[i].dm[1]; float sum = 0.f; for (int j = 0; j < K_QUANTS_PER_ITERATION; ++j) { sum += y[j+ 0] * (d * s[0] * (q[j+ 0] & 0xF) - m * s[2]) + y[j+16] * (d * s[0] * (q[j+16] & 0xF) - m * s[2]) + y[j+32] * (d * s[1] * (q[j+ 0] >> 4) - m * s[3]) + y[j+48] * (d * s[1] * (q[j+16] >> 4) - m * s[3]); } tmp += sum; } #endif // sum up partial sums and write back result #pragma unroll for (int mask = 16; mask > 0; mask >>= 1) { tmp += __shfl_xor_sync(0xffffffff, tmp, mask, 32); } if (tid == 0) { dst[row] = tmp; } } extern "C" __global__ void dequantize_mul_mat_vec_q5_k(const void * __restrict__ vx, const float * __restrict__ yy, float * __restrict__ dst, const int ncols) { const int row = blockIdx.x; const int num_blocks_per_row = ncols / QK_K; const int ib0 = row*num_blocks_per_row; const block_q5_K * x = (const block_q5_K *)vx + ib0; float tmp = 0; // partial sum for thread in warp #if QK_K == 256 const uint16_t kmask1 = 0x3f3f; const uint16_t kmask2 = 0x0f0f; const uint16_t kmask3 = 0xc0c0; const int tid = threadIdx.x/2; // 0...15 const int ix = threadIdx.x%2; const int il = tid/4; // 0...3 const int ir = tid - 4*il;// 0...3 const int n = 2; const int im = il/2; // 0 or 1. 0 computes 0,32 + 128,160, 1 computes 64,96 + 192,224 const int in = il%2; const int l0 = n*(2*ir + in); const int q_offset = 32*im + l0; const int y_offset = 64*im + l0; const uint8_t hm1 = 1 << (2*im); const uint8_t hm2 = hm1 << 4; uint16_t aux[4]; const uint8_t * sc = (const uint8_t *)aux; uint16_t q16[8]; const uint8_t * q4 = (const uint8_t *)q16; for (int i = ix; i < num_blocks_per_row; i += 2) { const uint8_t * ql1 = x[i].qs + q_offset; const uint8_t * qh = x[i].qh + l0; const float * y1 = yy + i*QK_K + y_offset; const float * y2 = y1 + 128; const float dall = __low2half(x[i].dm); const float dmin = __high2half(x[i].dm); const uint16_t * a = (const uint16_t *)x[i].scales; aux[0] = a[im+0] & kmask1; aux[1] = a[im+2] & kmask1; aux[2] = ((a[im+4] >> 0) & kmask2) | ((a[im+0] & kmask3) >> 2); aux[3] = ((a[im+4] >> 4) & kmask2) | ((a[im+2] & kmask3) >> 2); float4 sum = {0.f, 0.f, 0.f, 0.f}; float smin = 0; const uint16_t * q1 = (const uint16_t *)ql1; const uint16_t * q2 = q1 + 32; q16[0] = q1[0] & 0x0f0f; q16[1] = q1[8] & 0x0f0f; q16[2] = (q1[0] >> 4) & 0x0f0f; q16[3] = (q1[8] >> 4) & 0x0f0f; q16[4] = q2[0] & 0x0f0f; q16[5] = q2[8] & 0x0f0f; q16[6] = (q2[0] >> 4) & 0x0f0f; q16[7] = (q2[8] >> 4) & 0x0f0f; for (int l = 0; l < n; ++l) { sum.x += y1[l+ 0] * (q4[l +0] + (qh[l+ 0] & (hm1 << 0) ? 16 : 0)) + y1[l+16] * (q4[l +2] + (qh[l+16] & (hm1 << 0) ? 16 : 0)); sum.y += y1[l+32] * (q4[l +4] + (qh[l+ 0] & (hm1 << 1) ? 16 : 0)) + y1[l+48] * (q4[l +6] + (qh[l+16] & (hm1 << 1) ? 16 : 0)); sum.z += y2[l+ 0] * (q4[l +8] + (qh[l+ 0] & (hm2 << 0) ? 16 : 0)) + y2[l+16] * (q4[l+10] + (qh[l+16] & (hm2 << 0) ? 16 : 0)); sum.w += y2[l+32] * (q4[l+12] + (qh[l+ 0] & (hm2 << 1) ? 16 : 0)) + y2[l+48] * (q4[l+14] + (qh[l+16] & (hm2 << 1) ? 16 : 0)); smin += (y1[l] + y1[l+16]) * sc[2] + (y1[l+32] + y1[l+48]) * sc[3] + (y2[l] + y2[l+16]) * sc[6] + (y2[l+32] + y2[l+48]) * sc[7]; } tmp += dall * (sum.x * sc[0] + sum.y * sc[1] + sum.z * sc[4] + sum.w * sc[5]) - dmin * smin; } #else const int tid = threadIdx.x/(2*K_QUANTS_PER_ITERATION); // 0...15 const int ix = threadIdx.x%(2*K_QUANTS_PER_ITERATION); const int step = tid * K_QUANTS_PER_ITERATION; const int im = step/8; const int in = step%8; for (int i = ix; i < num_blocks_per_row; i += 2*K_QUANTS_PER_ITERATION) { const uint8_t * q = x[i].qs + step; const int8_t * s = x[i].scales; const float * y = yy + i*QK_K + step; const float d = x[i].d; float sum = 0.f; for (int j = 0; j < K_QUANTS_PER_ITERATION; ++j) { const uint8_t h = x[i].qh[in+j] >> im; sum += y[j+ 0] * d * s[0] * ((q[j+ 0] & 0xF) - ((h >> 0) & 1 ? 0 : 16)) + y[j+16] * d * s[1] * ((q[j+16] & 0xF) - ((h >> 2) & 1 ? 0 : 16)) + y[j+32] * d * s[2] * ((q[j+ 0] >> 4) - ((h >> 4) & 1 ? 0 : 16)) + y[j+48] * d * s[3] * ((q[j+16] >> 4) - ((h >> 6) & 1 ? 0 : 16)); } tmp += sum; } #endif // sum up partial sums and write back result #pragma unroll for (int mask = 16; mask > 0; mask >>= 1) { tmp += __shfl_xor_sync(0xffffffff, tmp, mask, 32); } if (threadIdx.x == 0) { dst[row] = tmp; } } extern "C" __global__ void dequantize_mul_mat_vec_q6_k(const void * __restrict__ vx, const float * __restrict__ yy, float * __restrict__ dst, const int ncols, int nrows) { static_assert(16%K_QUANTS_PER_ITERATION == 0, "16 must be divisible by K_QUANTS_PER_ITERATION"); const int row = blockIdx.x*blockDim.y + threadIdx.y; if (row > nrows) return; const int num_blocks_per_row = ncols / QK_K; const int ib0 = row*num_blocks_per_row; const block_q6_K * x = (const block_q6_K *)vx + ib0; #if QK_K == 256 const int tid = threadIdx.x/K_QUANTS_PER_ITERATION; // 0...31 or 0...16 const int ix = threadIdx.x%K_QUANTS_PER_ITERATION; // 0 or 0, 1 const int step = 16/K_QUANTS_PER_ITERATION; // 16 or 8 const int im = tid/step; // 0 or 1. 0 computes 0..., 1 computes 128... const int in = tid - step*im; // 0...15 or 0...7 #if K_QUANTS_PER_ITERATION == 1 const int l0 = K_QUANTS_PER_ITERATION*in; // 0...15 const int is = 0; #else const int l0 = 4 * in; // 0, 4, 8, ..., 28 const int is = in / 4; #endif const int ql_offset = 64*im + l0; const int qh_offset = 32*im + l0; const int s_offset = 8*im + is; const int y_offset = 128*im + l0; float tmp = 0; // partial sum for thread in warp for (int i = ix; i < num_blocks_per_row; i += K_QUANTS_PER_ITERATION) { const float * y = yy + i * QK_K + y_offset; const uint8_t * ql = x[i].ql + ql_offset; const uint8_t * qh = x[i].qh + qh_offset; const int8_t * s = x[i].scales + s_offset; const float d = x[i].d; #if K_QUANTS_PER_ITERATION == 1 float sum = y[ 0] * s[0] * d * ((int8_t)((ql[ 0] & 0xF) | ((qh[ 0] & 0x03) << 4)) - 32) + y[16] * s[1] * d * ((int8_t)((ql[16] & 0xF) | ((qh[16] & 0x03) << 4)) - 32) + y[32] * s[2] * d * ((int8_t)((ql[32] & 0xF) | ((qh[ 0] & 0x0c) << 2)) - 32) + y[48] * s[3] * d * ((int8_t)((ql[48] & 0xF) | ((qh[16] & 0x0c) << 2)) - 32) + y[64] * s[4] * d * ((int8_t)((ql[ 0] >> 4) | ((qh[ 0] & 0x30) >> 0)) - 32) + y[80] * s[5] * d * ((int8_t)((ql[16] >> 4) | ((qh[16] & 0x30) >> 0)) - 32) + y[96] * s[6] * d * ((int8_t)((ql[32] >> 4) | ((qh[ 0] & 0xc0) >> 2)) - 32) +y[112] * s[7] * d * ((int8_t)((ql[48] >> 4) | ((qh[16] & 0xc0) >> 2)) - 32); tmp += sum; #else float sum = 0; for (int l = 0; l < 4; ++l) { sum += y[l+ 0] * s[0] * d * ((int8_t)((ql[l+ 0] & 0xF) | (((qh[l] >> 0) & 3) << 4)) - 32) + y[l+32] * s[2] * d * ((int8_t)((ql[l+32] & 0xF) | (((qh[l] >> 2) & 3) << 4)) - 32) + y[l+64] * s[4] * d * ((int8_t)((ql[l+ 0] >> 4) | (((qh[l] >> 4) & 3) << 4)) - 32) + y[l+96] * s[6] * d * ((int8_t)((ql[l+32] >> 4) | (((qh[l] >> 6) & 3) << 4)) - 32); } tmp += sum; #endif } #else const int tid = threadIdx.x/(2*K_QUANTS_PER_ITERATION); // 0...7 const int ix = threadIdx.x%(2*K_QUANTS_PER_ITERATION); // 0...3 const int step = tid * K_QUANTS_PER_ITERATION; float tmp = 0; // partial sum for thread in warp for (int i = ix; i < num_blocks_per_row; i += 2*K_QUANTS_PER_ITERATION) { const float * y = yy + i * QK_K + step; const uint8_t * ql = x[i].ql + step; const uint8_t * qh = x[i].qh + step; const int8_t * s = x[i].scales; const float d = x[i+0].d; float sum = 0; for (int j = 0; j < K_QUANTS_PER_ITERATION; ++j) { sum += y[j+ 0] * s[0] * d * ((int8_t)((ql[j+ 0] & 0xF) | ((qh[j] & 0x03) << 4)) - 32) + y[j+16] * s[1] * d * ((int8_t)((ql[j+16] & 0xF) | ((qh[j] & 0x0c) << 2)) - 32) + y[j+32] * s[2] * d * ((int8_t)((ql[j+ 0] >> 4) | ((qh[j] & 0x30) >> 0)) - 32) + y[j+48] * s[3] * d * ((int8_t)((ql[j+16] >> 4) | ((qh[j] & 0xc0) >> 2)) - 32); } tmp += sum; } #endif // sum up partial sums and write back result #pragma unroll for (int mask = 16; mask > 0; mask >>= 1) { tmp += __shfl_xor_sync(0xffffffff, tmp, mask, 32); } if (tid == 0) { dst[row] = tmp; } } // VDR = vec dot ratio, how many contiguous integers each thread processes when the vec dot kernel is called // MMVQ = mul_mat_vec_q, MMQ = mul_mat_q #define VDR_Q4_0_Q8_1_MMVQ 2 #define VDR_Q4_0_Q8_1_MMQ 4 template <int vdr> static __device__ __forceinline__ float vec_dot_q4_0_q8_1_impl( const int * v, const int * u, const float & d4, const half2 & ds8) { int sumi = 0; #pragma unroll for (int i = 0; i < vdr; ++i) { const int vi0 = (v[i] >> 0) & 0x0F0F0F0F; const int vi1 = (v[i] >> 4) & 0x0F0F0F0F; // SIMD dot product of quantized values sumi = ggml_cuda_dp4a(vi0, u[2*i+0], sumi); sumi = ggml_cuda_dp4a(vi1, u[2*i+1], sumi); } const float2 ds8f = __half22float2(ds8); // second part effectively subtracts 8 from each quant value return d4 * (sumi * ds8f.x - (8*vdr/QI4_0) * ds8f.y); } #define VDR_Q4_1_Q8_1_MMVQ 2 #define VDR_Q4_1_Q8_1_MMQ 4 template <int vdr> static __device__ __forceinline__ float vec_dot_q4_1_q8_1_impl( const int * v, const int * u, const half2 & dm4, const half2 & ds8) { int sumi = 0; #pragma unroll for (int i = 0; i < vdr; ++i) { const int vi0 = (v[i] >> 0) & 0x0F0F0F0F; const int vi1 = (v[i] >> 4) & 0x0F0F0F0F; // SIMD dot product of quantized values sumi = ggml_cuda_dp4a(vi0, u[2*i+0], sumi); sumi = ggml_cuda_dp4a(vi1, u[2*i+1], sumi); } #ifdef GGML_CUDA_F16 const float2 tmp = __half22float2(__hmul2(dm4, ds8)); const float d4d8 = tmp.x; const float m4s8 = tmp.y; #else const float2 dm4f = __half22float2(dm4); const float2 ds8f = __half22float2(ds8); const float d4d8 = dm4f.x * ds8f.x; const float m4s8 = dm4f.y * ds8f.y; #endif // GGML_CUDA_F16 // scale second part of sum by QI8_1/(vdr * QR4_1) to compensate for multiple threads adding it return sumi * d4d8 + m4s8 / (QI8_1 / (vdr * QR4_1)); } #define VDR_Q5_0_Q8_1_MMVQ 2 #define VDR_Q5_0_Q8_1_MMQ 4 template <int vdr> static __device__ __forceinline__ float vec_dot_q5_0_q8_1_impl( const int * vl, const int * vh, const int * u, const float & d5, const half2 & ds8) { int sumi = 0; #pragma unroll for (int i = 0; i < vdr; ++i) { int vi0 = (vl[i] >> 0) & 0x0F0F0F0F; // lower 4 qs bits, still need qh as 5th bits vi0 |= (vh[i] << 4) & 0x00000010; // 0 -> 4 vi0 |= (vh[i] << 11) & 0x00001000; // 1 -> 12 vi0 |= (vh[i] << 18) & 0x00100000; // 2 -> 20 vi0 |= (vh[i] << 25) & 0x10000000; // 3 -> 28 sumi = ggml_cuda_dp4a(vi0, u[2*i+0], sumi); // SIMD dot product of quantized values int vi1 = (vl[i] >> 4) & 0x0F0F0F0F; // upper 4 qs bits, still need qh as 5th bits vi1 |= (vh[i] >> 12) & 0x00000010; // 16 -> 4 vi1 |= (vh[i] >> 5) & 0x00001000; // 17 -> 12 vi1 |= (vh[i] << 2) & 0x00100000; // 18 -> 20 vi1 |= (vh[i] << 9) & 0x10000000; // 19 -> 28 sumi = ggml_cuda_dp4a(vi1, u[2*i+1], sumi); // SIMD dot product of quantized values } const float2 ds8f = __half22float2(ds8); // second part effectively subtracts 16 from each quant value return d5 * (sumi * ds8f.x - (16*vdr/QI5_0) * ds8f.y); } #define VDR_Q5_1_Q8_1_MMVQ 2 #define VDR_Q5_1_Q8_1_MMQ 4 template <int vdr> static __device__ __forceinline__ float vec_dot_q5_1_q8_1_impl( const int * vl, const int * vh, const int * u, const half2 & dm5, const half2 & ds8) { int sumi = 0; #pragma unroll for (int i = 0; i < vdr; ++i) { int vi0 = (vl[i] >> 0) & 0x0F0F0F0F; // lower 4 qs bits, still need qh as 5th bits vi0 |= (vh[i] << 4) & 0x00000010; // 0 -> 4 vi0 |= (vh[i] << 11) & 0x00001000; // 1 -> 12 vi0 |= (vh[i] << 18) & 0x00100000; // 2 -> 20 vi0 |= (vh[i] << 25) & 0x10000000; // 3 -> 28 sumi = ggml_cuda_dp4a(vi0, u[2*i+0], sumi); // SIMD dot product of quantized values int vi1 = (vl[i] >> 4) & 0x0F0F0F0F; // upper 4 qs bits, still need qh as 5th bits vi1 |= (vh[i] >> 12) & 0x00000010; // 16 -> 4 vi1 |= (vh[i] >> 5) & 0x00001000; // 17 -> 12 vi1 |= (vh[i] << 2) & 0x00100000; // 18 -> 20 vi1 |= (vh[i] << 9) & 0x10000000; // 19 -> 28 sumi = ggml_cuda_dp4a(vi1, u[2*i+1], sumi); // SIMD dot product of quantized values } #ifdef GGML_CUDA_F16 const float2 tmp = __half22float2(__hmul2(dm5, ds8)); const float d5d8 = tmp.x; const float m5s8 = tmp.y; #else const float2 dm5f = __half22float2(dm5); const float2 ds8f = __half22float2(ds8); const float d5d8 = dm5f.x * ds8f.x; const float m5s8 = dm5f.y * ds8f.y; #endif // GGML_CUDA_F16 // scale second part of sum by QI5_1 / vdr to compensate for multiple threads adding it return sumi*d5d8 + m5s8 / (QI5_1 / vdr); } #define VDR_Q8_0_Q8_1_MMVQ 2 #define VDR_Q8_0_Q8_1_MMQ 8 template <int vdr> static __device__ __forceinline__ float vec_dot_q8_0_q8_1_impl( const int * v, const int * u, const float & d8_0, const float & d8_1) { int sumi = 0; #pragma unroll for (int i = 0; i < vdr; ++i) { // SIMD dot product of quantized values sumi = ggml_cuda_dp4a(v[i], u[i], sumi); } return d8_0*d8_1 * sumi; } template <int vdr> static __device__ __forceinline__ float vec_dot_q8_1_q8_1_impl( const int * v, const int * u, const half2 & dm8, const half2 & ds8) { int sumi = 0; #pragma unroll for (int i = 0; i < vdr; ++i) { // SIMD dot product of quantized values sumi = ggml_cuda_dp4a(v[i], u[i], sumi); } #ifdef GGML_CUDA_F16 const float2 tmp = __half22float2(__hmul2(dm8, ds8)); const float d8d8 = tmp.x; const float m8s8 = tmp.y; #else const float2 dm8f = __half22float2(dm8); const float2 ds8f = __half22float2(ds8); const float d8d8 = dm8f.x * ds8f.x; const float m8s8 = dm8f.y * ds8f.y; #endif // GGML_CUDA_F16 // scale second part of sum by QI8_1/ vdr to compensate for multiple threads adding it return sumi*d8d8 + m8s8 / (QI8_1 / vdr); } #define VDR_Q2_K_Q8_1_MMVQ 1 #define VDR_Q2_K_Q8_1_MMQ 2 // contiguous v/x values static __device__ __forceinline__ float vec_dot_q2_K_q8_1_impl_mmvq( const int & v, const int * __restrict__ u, const uint8_t * __restrict__ scales, const half2 & dm2, const float * __restrict__ d8) { float sumf_d = 0.0f; float sumf_m = 0.0f; #pragma unroll for (int i = 0; i < QR2_K; ++i) { const int sc = scales[2*i]; const int vi = (v >> (2*i)) & 0x03030303; sumf_d += d8[i] * (ggml_cuda_dp4a(vi, u[i], 0) * (sc & 0xF)); // SIMD dot product // fill int with 4x m int m = sc >> 4; m |= m << 8; m |= m << 16; sumf_m += d8[i] * ggml_cuda_dp4a(m, u[i], 0); // multiply constant q2_K part with sum of q8_1 values } const float2 dm2f = __half22float2(dm2); return dm2f.x*sumf_d - dm2f.y*sumf_m; } // contiguous u/y values static __device__ __forceinline__ float vec_dot_q2_K_q8_1_impl_mmq( const int * __restrict__ v, const int * __restrict__ u, const uint8_t * __restrict__ scales, const half2 & dm2, const float & d8) { int sumi_d = 0; int sumi_m = 0; #pragma unroll for (int i0 = 0; i0 < QI8_1; i0 += QI8_1/2) { int sumi_d_sc = 0; const int sc = scales[i0 / (QI8_1/2)]; // fill int with 4x m int m = sc >> 4; m |= m << 8; m |= m << 16; #pragma unroll for (int i = i0; i < i0 + QI8_1/2; ++i) { sumi_d_sc = ggml_cuda_dp4a(v[i], u[i], sumi_d_sc); // SIMD dot product sumi_m = ggml_cuda_dp4a(m, u[i], sumi_m); // multiply sum of q8_1 values with m } sumi_d += sumi_d_sc * (sc & 0xF); } const float2 dm2f = __half22float2(dm2); return d8 * (dm2f.x*sumi_d - dm2f.y*sumi_m); } #define VDR_Q3_K_Q8_1_MMVQ 1 #define VDR_Q3_K_Q8_1_MMQ 2 // contiguous v/x values static __device__ __forceinline__ float vec_dot_q3_K_q8_1_impl_mmvq( const int & vl, const int & vh, const int * __restrict__ u, const uint8_t * __restrict__ scales, const int & scale_offset, const float & d3, const float * __restrict__ d8) { float sumf = 0.0f; #pragma unroll for (int i = 0; i < QR3_K; ++i) { const int isc = scale_offset + 2*i; const int isc_low = isc % (QK_K/32); const int sc_shift_low = 4 * (isc / (QK_K/32)); const int sc_low = (scales[isc_low] >> sc_shift_low) & 0xF; const int isc_high = isc % (QK_K/64); const int sc_shift_high = 2 * (isc / (QK_K/64)); const int sc_high = ((scales[(QK_K/32) + isc_high] >> sc_shift_high) & 3) << 4; const int sc = (sc_low | sc_high) - 32; const int vil = (vl >> (2*i)) & 0x03030303; const int vih = ((vh >> i) << 2) & 0x04040404; const int vi = __vsubss4(vil, vih); sumf += d8[i] * (ggml_cuda_dp4a(vi, u[i], 0) * sc); // SIMD dot product } return d3 * sumf; } // contiguous u/y values static __device__ __forceinline__ float vec_dot_q3_K_q8_1_impl_mmq( const int * __restrict__ v, const int * __restrict__ u, const int8_t * __restrict__ scales, const float & d3, const float & d8) { int sumi = 0; #pragma unroll for (int i0 = 0; i0 < QR3_K*VDR_Q3_K_Q8_1_MMQ; i0 += QI8_1/2) { int sumi_sc = 0; for (int i = i0; i < i0 + QI8_1/2; ++i) { sumi_sc = ggml_cuda_dp4a(v[i], u[i], sumi_sc); // SIMD dot product } sumi += sumi_sc * scales[i0 / (QI8_1/2)]; } return d3*d8 * sumi; } #define VDR_Q4_K_Q8_1_MMVQ 2 #define VDR_Q4_K_Q8_1_MMQ 8 // contiguous v/x values static __device__ __forceinline__ float vec_dot_q4_K_q8_1_impl_vmmq( const int * __restrict__ v, const int * __restrict__ u, const uint8_t * __restrict__ sc, const uint8_t * __restrict__ m, const half2 & dm4, const float * __restrict__ d8) { float sumf_d = 0.0f; float sumf_m = 0.0f; #pragma unroll for (int i = 0; i < QR4_K; ++i) { const int v0i = (v[0] >> (4*i)) & 0x0F0F0F0F; const int v1i = (v[1] >> (4*i)) & 0x0F0F0F0F; const int dot1 = ggml_cuda_dp4a(v1i, u[2*i+1], ggml_cuda_dp4a(v0i, u[2*i+0], 0)); // SIMD dot product const int dot2 = ggml_cuda_dp4a(0x01010101, u[2*i+1], ggml_cuda_dp4a(0x01010101, u[2*i+0], 0)); // sum of u sumf_d += d8[i] * (dot1 * sc[i]); sumf_m += d8[i] * (dot2 * m[i]); // multiply constant part of q4_K with sum of q8_1 values } const float2 dm4f = __half22float2(dm4); return dm4f.x*sumf_d - dm4f.y*sumf_m; } // contiguous u/y values static __device__ __forceinline__ float vec_dot_q4_K_q8_1_impl_mmq( const int * __restrict__ v, const int * __restrict__ u, const uint8_t * __restrict__ sc, const uint8_t * __restrict__ m, const half2 & dm4, const half2 * __restrict__ ds8) { float sumf_d = 0.0f; float sumf_m = 0.0f; #pragma unroll for (int i = 0; i < QR4_K*VDR_Q4_K_Q8_1_MMQ/QI8_1; ++i) { int sumi_d = 0; #pragma unroll for (int j = 0; j < QI8_1; ++j) { sumi_d = ggml_cuda_dp4a((v[j] >> (4*i)) & 0x0F0F0F0F, u[i*QI8_1 + j], sumi_d); // SIMD dot product } const float2 ds8f = __half22float2(ds8[i]); sumf_d += ds8f.x * (sc[i] * sumi_d); sumf_m += ds8f.y * m[i]; // sum of q8_1 block * q4_K min val } const float2 dm4f = __half22float2(dm4); return dm4f.x*sumf_d - dm4f.y*sumf_m; } #define VDR_Q5_K_Q8_1_MMVQ 2 #define VDR_Q5_K_Q8_1_MMQ 8 // contiguous v/x values static __device__ __forceinline__ float vec_dot_q5_K_q8_1_impl_vmmq( const int * __restrict__ vl, const int * __restrict__ vh, const int * __restrict__ u, const uint8_t * __restrict__ sc, const uint8_t * __restrict__ m, const half2 & dm5, const float * __restrict__ d8) { float sumf_d = 0.0f; float sumf_m = 0.0f; #pragma unroll for (int i = 0; i < QR5_K; ++i) { const int vl0i = (vl[0] >> (4*i)) & 0x0F0F0F0F; const int vl1i = (vl[1] >> (4*i)) & 0x0F0F0F0F; const int vh0i = ((vh[0] >> i) << 4) & 0x10101010; const int vh1i = ((vh[1] >> i) << 4) & 0x10101010; const int v0i = vl0i | vh0i; const int v1i = vl1i | vh1i; const int dot1 = ggml_cuda_dp4a(v0i, u[2*i+0], ggml_cuda_dp4a(v1i, u[2*i+1], 0)); // SIMD dot product const int dot2 = ggml_cuda_dp4a(0x01010101, u[2*i+0], ggml_cuda_dp4a(0x01010101, u[2*i+1], 0)); // sum of u sumf_d += d8[i] * (dot1 * sc[i]); sumf_m += d8[i] * (dot2 * m[i]); } const float2 dm5f = __half22float2(dm5); return dm5f.x*sumf_d - dm5f.y*sumf_m; } // contiguous u/y values static __device__ __forceinline__ float vec_dot_q5_K_q8_1_impl_mmq( const int * __restrict__ v, const int * __restrict__ u, const uint8_t * __restrict__ sc, const uint8_t * __restrict__ m, const half2 & dm4, const half2 * __restrict__ ds8) { float sumf_d = 0.0f; float sumf_m = 0.0f; #pragma unroll for (int i = 0; i < QR5_K*VDR_Q5_K_Q8_1_MMQ/QI8_1; ++i) { int sumi_d = 0; #pragma unroll for (int j = 0; j < QI8_1; ++j) { sumi_d = ggml_cuda_dp4a(v[i*QI8_1 + j], u[i*QI8_1 + j], sumi_d); // SIMD dot product } const float2 ds8f = __half22float2(ds8[i]); sumf_d += ds8f.x * (sc[i] * sumi_d); sumf_m += ds8f.y * m[i]; // sum of q8_1 block * q4_K min val } const float2 dm4f = __half22float2(dm4); return dm4f.x*sumf_d - dm4f.y*sumf_m; } #define VDR_Q6_K_Q8_1_MMVQ 1 #define VDR_Q6_K_Q8_1_MMQ 8 // contiguous v/x values static __device__ __forceinline__ float vec_dot_q6_K_q8_1_impl_mmvq( const int & vl, const int & vh, const int * __restrict__ u, const int8_t * __restrict__ scales, const float & d, const float * __restrict__ d8) { float sumf = 0.0f; #pragma unroll for (int i = 0; i < QR6_K; ++i) { const int sc = scales[4*i]; const int vil = (vl >> (4*i)) & 0x0F0F0F0F; const int vih = ((vh >> (4*i)) << 4) & 0x30303030; const int vi = __vsubss4((vil | vih), 0x20202020); // vi = (vil | vih) - 32 sumf += d8[i] * (ggml_cuda_dp4a(vi, u[i], 0) * sc); // SIMD dot product } return d*sumf; } // contiguous u/y values static __device__ __forceinline__ float vec_dot_q6_K_q8_1_impl_mmq( const int * __restrict__ v, const int * __restrict__ u, const int8_t * __restrict__ sc, const float & d6, const float * __restrict__ d8) { float sumf_d = 0.0f; #pragma unroll for (int i0 = 0; i0 < VDR_Q6_K_Q8_1_MMQ; i0 += 4) { int2 sumi_d = {0, 0}; // 2 q6_K scales per q8_1 scale #pragma unroll for (int i = i0; i < i0 + 2; ++i) { sumi_d.x = ggml_cuda_dp4a(v[2*i+0], u[2*i+0], sumi_d.x); // SIMD dot product sumi_d.x = ggml_cuda_dp4a(v[2*i+1], u[2*i+1], sumi_d.x); // SIMD dot product sumi_d.y = ggml_cuda_dp4a(v[2*i+4], u[2*i+4], sumi_d.y); // SIMD dot product sumi_d.y = ggml_cuda_dp4a(v[2*i+5], u[2*i+5], sumi_d.y); // SIMD dot product } sumf_d += d8[i0/4] * (sc[i0/2+0]*sumi_d.x + sc[i0/2+1]*sumi_d.y); } return d6 * sumf_d; } static __device__ __forceinline__ float vec_dot_q4_0_q8_1( const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { const block_q4_0 * bq4_0 = (const block_q4_0 *) vbq; int v[VDR_Q4_0_Q8_1_MMVQ]; int u[2*VDR_Q4_0_Q8_1_MMVQ]; #pragma unroll for (int i = 0; i < VDR_Q4_0_Q8_1_MMVQ; ++i) { v[i] = get_int_from_uint8(bq4_0->qs, iqs + i); u[2*i+0] = get_int_from_int8_aligned(bq8_1->qs, iqs + i); u[2*i+1] = get_int_from_int8_aligned(bq8_1->qs, iqs + i + QI4_0); } return vec_dot_q4_0_q8_1_impl<VDR_Q4_0_Q8_1_MMVQ>(v, u, bq4_0->d, bq8_1->ds); } static __device__ __forceinline__ float vec_dot_q4_1_q8_1( const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { const block_q4_1 * bq4_1 = (const block_q4_1 *) vbq; int v[VDR_Q4_1_Q8_1_MMVQ]; int u[2*VDR_Q4_1_Q8_1_MMVQ]; #pragma unroll for (int i = 0; i < VDR_Q4_1_Q8_1_MMVQ; ++i) { v[i] = get_int_from_uint8_aligned(bq4_1->qs, iqs + i); u[2*i+0] = get_int_from_int8_aligned(bq8_1->qs, iqs + i); u[2*i+1] = get_int_from_int8_aligned(bq8_1->qs, iqs + i + QI4_1); } return vec_dot_q4_1_q8_1_impl<VDR_Q4_1_Q8_1_MMVQ>(v, u, bq4_1->dm, bq8_1->ds); } static __device__ __forceinline__ float vec_dot_q5_0_q8_1( const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { const block_q5_0 * bq5_0 = (const block_q5_0 *) vbq; int vl[VDR_Q5_0_Q8_1_MMVQ]; int vh[VDR_Q5_0_Q8_1_MMVQ]; int u[2*VDR_Q5_0_Q8_1_MMVQ]; #pragma unroll for (int i = 0; i < VDR_Q5_0_Q8_1_MMVQ; ++i) { vl[i] = get_int_from_uint8(bq5_0->qs, iqs + i); vh[i] = get_int_from_uint8(bq5_0->qh, 0) >> (4 * (iqs + i)); u[2*i+0] = get_int_from_int8_aligned(bq8_1->qs, iqs + i); u[2*i+1] = get_int_from_int8_aligned(bq8_1->qs, iqs + i + QI5_0); } return vec_dot_q5_0_q8_1_impl<VDR_Q5_0_Q8_1_MMVQ>(vl, vh, u, bq5_0->d, bq8_1->ds); } static __device__ __forceinline__ float vec_dot_q5_1_q8_1( const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { const block_q5_1 * bq5_1 = (const block_q5_1 *) vbq; int vl[VDR_Q5_1_Q8_1_MMVQ]; int vh[VDR_Q5_1_Q8_1_MMVQ]; int u[2*VDR_Q5_1_Q8_1_MMVQ]; #pragma unroll for (int i = 0; i < VDR_Q5_1_Q8_1_MMVQ; ++i) { vl[i] = get_int_from_uint8_aligned(bq5_1->qs, iqs + i); vh[i] = get_int_from_uint8_aligned(bq5_1->qh, 0) >> (4 * (iqs + i)); u[2*i+0] = get_int_from_int8_aligned(bq8_1->qs, iqs + i); u[2*i+1] = get_int_from_int8_aligned(bq8_1->qs, iqs + i + QI5_1); } return vec_dot_q5_1_q8_1_impl<VDR_Q5_1_Q8_1_MMVQ>(vl, vh, u, bq5_1->dm, bq8_1->ds); } static __device__ __forceinline__ float vec_dot_q8_0_q8_1( const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { const block_q8_0 * bq8_0 = (const block_q8_0 *) vbq; int v[VDR_Q8_0_Q8_1_MMVQ]; int u[VDR_Q8_0_Q8_1_MMVQ]; #pragma unroll for (int i = 0; i < VDR_Q8_0_Q8_1_MMVQ; ++i) { v[i] = get_int_from_int8(bq8_0->qs, iqs + i); u[i] = get_int_from_int8_aligned(bq8_1->qs, iqs + i); } return vec_dot_q8_0_q8_1_impl<VDR_Q8_0_Q8_1_MMVQ>(v, u, bq8_0->d, __low2half(bq8_1->ds)); } static __device__ __forceinline__ float vec_dot_q2_K_q8_1( const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { const block_q2_K * bq2_K = (const block_q2_K *) vbq; const int bq8_offset = QR2_K * (iqs / QI8_1); const int scale_offset = iqs - iqs % QI8_1 + (iqs % QI8_1) / (QI8_1/2); const uint8_t * scales = bq2_K->scales + scale_offset; const int v = get_int_from_uint8_aligned(bq2_K->qs, iqs); int u[QR2_K]; float d8[QR2_K]; #pragma unroll for (int i = 0; i < QR2_K; ++ i) { u[i] = get_int_from_int8_aligned(bq8_1[bq8_offset + i].qs, iqs % QI8_1); d8[i] = __low2float(bq8_1[bq8_offset + i].ds); } return vec_dot_q2_K_q8_1_impl_mmvq(v, u, scales, bq2_K->dm, d8); } static __device__ __forceinline__ float vec_dot_q3_K_q8_1( const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { const block_q3_K * bq3_K = (const block_q3_K *) vbq; const int bq8_offset = QR3_K * (iqs / (QI3_K/2)); const int scale_offset = iqs - iqs % QI8_1 + (iqs % QI8_1) / (QI8_1/2); const float d = bq3_K->d; const int vl = get_int_from_uint8(bq3_K->qs, iqs); // invert the mask with ~ so that a 0/1 results in 4/0 being subtracted const int vh = ~get_int_from_uint8(bq3_K->hmask, iqs % (QI3_K/2)) >> bq8_offset; int u[QR3_K]; float d8[QR3_K]; #pragma unroll for (int i = 0; i < QR3_K; ++i) { u[i] = get_int_from_int8_aligned(bq8_1[bq8_offset + i].qs, iqs % QI8_1); d8[i] = __low2float(bq8_1[bq8_offset + i].ds); } return vec_dot_q3_K_q8_1_impl_mmvq(vl, vh, u, bq3_K->scales, scale_offset, d, d8); } static __device__ __forceinline__ float vec_dot_q4_K_q8_1( const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { #ifndef GGML_QKK_64 const block_q4_K * bq4_K = (const block_q4_K *) vbq; int v[2]; int u[2*QR4_K]; float d8[QR4_K]; // iqs is in 0,2..30. bq8_offset = iqs/4 -> bq8_offset = 0, 2, 4, 6 const int bq8_offset = QR4_K * ((iqs/2) / (QI8_1/2)); // iqs = 0....3 -> bq8_offset = 0, want q4_offset = 0, 4, 8, 12 // iqs = 4....7 -> bq8_offset = 2, want q4_offset = 32, 36, 40, 44 // iqs = 8...11 -> bq8_offset = 4, want q4_offset = 64, 68, 72, 76 // iqs = 12..15 -> bq8_offset = 6, want q4_offset = 96, 100, 104, 108 const int * q4 = (const int *)(bq4_K->qs + 16 * bq8_offset + 4 * ((iqs/2)%4)); v[0] = q4[0]; v[1] = q4[4]; const uint16_t * scales = (const uint16_t *)bq4_K->scales; uint16_t aux[2]; const int j = bq8_offset/2; if (j < 2) { aux[0] = scales[j+0] & 0x3f3f; aux[1] = scales[j+2] & 0x3f3f; } else { aux[0] = ((scales[j+2] >> 0) & 0x0f0f) | ((scales[j-2] & 0xc0c0) >> 2); aux[1] = ((scales[j+2] >> 4) & 0x0f0f) | ((scales[j-0] & 0xc0c0) >> 2); } const uint8_t * sc = (const uint8_t *)aux; const uint8_t * m = sc + 2; for (int i = 0; i < QR4_K; ++i) { const block_q8_1 * bq8i = bq8_1 + bq8_offset + i; d8[i] = __low2float(bq8i->ds); const int * q8 = (const int *)bq8i->qs + ((iqs/2)%4); u[2*i+0] = q8[0]; u[2*i+1] = q8[4]; } return vec_dot_q4_K_q8_1_impl_vmmq(v, u, sc, m, bq4_K->dm, d8); #else const block_q4_K * bq4_K = (const block_q4_K *) vbq; float sumf_d = 0.0f; float sumf_m = 0.0f; uint16_t aux16[2]; const uint8_t * s = (const uint8_t *)aux16; const uint16_t * a = (const uint16_t *)bq4_K->scales; aux16[0] = a[0] & 0x0f0f; aux16[1] = (a[0] >> 4) & 0x0f0f; const float dall = bq4_K->dm[0]; const float dmin = bq4_K->dm[1]; const float d8_1 = __low2float(bq8_1[0].ds); const float d8_2 = __low2float(bq8_1[1].ds); const int ui1 = *((const int *)bq8_1[0].qs + (iqs/2)); const int ui2 = *((const int *)bq8_1[0].qs + (iqs/2) + 4); const int ui3 = *((const int *)bq8_1[1].qs + (iqs/2)); const int ui4 = *((const int *)bq8_1[1].qs + (iqs/2) + 4); const int * q4 = (const int *)bq4_K->qs + (iqs/2); const int v1 = q4[0]; const int v2 = q4[4]; const int dot1 = ggml_cuda_dp4a(ui2, v2 & 0x0f0f0f0f, ggml_cuda_dp4a(ui1, v1 & 0x0f0f0f0f, 0)); const int dot2 = ggml_cuda_dp4a(ui4, (v2 >> 4) & 0x0f0f0f0f, ggml_cuda_dp4a(ui3, (v1 >> 4) & 0x0f0f0f0f, 0)); const int dot3 = ggml_cuda_dp4a(0x01010101, ui2, ggml_cuda_dp4a(0x01010101, ui1, 0)); const int dot4 = ggml_cuda_dp4a(0x01010101, ui4, ggml_cuda_dp4a(0x01010101, ui3, 0)); sumf_d += d8_1 * (dot1 * s[0]) + d8_2 * (dot2 * s[1]); sumf_m += d8_1 * (dot3 * s[2]) + d8_2 * (dot4 * s[3]); return dall * sumf_d - dmin * sumf_m; #endif } static __device__ __forceinline__ float vec_dot_q5_K_q8_1( const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { #ifndef GGML_QKK_64 const block_q5_K * bq5_K = (const block_q5_K *) vbq; int vl[2]; int vh[2]; int u[2*QR5_K]; float d8[QR5_K]; const int bq8_offset = QR5_K * ((iqs/2) / (QI8_1/2)); const int * ql = (const int *)(bq5_K->qs + 16 * bq8_offset + 4 * ((iqs/2)%4)); const int * qh = (const int *)(bq5_K->qh + 4 * ((iqs/2)%4)); vl[0] = ql[0]; vl[1] = ql[4]; vh[0] = qh[0] >> bq8_offset; vh[1] = qh[4] >> bq8_offset; const uint16_t * scales = (const uint16_t *)bq5_K->scales; uint16_t aux[2]; const int j = bq8_offset/2; if (j < 2) { aux[0] = scales[j+0] & 0x3f3f; aux[1] = scales[j+2] & 0x3f3f; } else { aux[0] = ((scales[j+2] >> 0) & 0x0f0f) | ((scales[j-2] & 0xc0c0) >> 2); aux[1] = ((scales[j+2] >> 4) & 0x0f0f) | ((scales[j-0] & 0xc0c0) >> 2); } const uint8_t * sc = (const uint8_t *)aux; const uint8_t * m = sc + 2; #pragma unroll for (int i = 0; i < QR5_K; ++i) { const block_q8_1 * bq8i = bq8_1 + bq8_offset + i; d8[i] = __low2float(bq8i->ds); const int * q8 = (const int *)bq8i->qs + ((iqs/2)%4); u[2*i+0] = q8[0]; u[2*i+1] = q8[4]; } return vec_dot_q5_K_q8_1_impl_vmmq(vl, vh, u, sc, m, bq5_K->dm, d8); #else const block_q5_K * bq5_K = (const block_q5_K *) vbq; const int8_t * s = bq5_K->scales; const float d = bq5_K->d; const float d8_1 = __low2half(bq8_1[0].ds); const float d8_2 = __low2half(bq8_1[1].ds); const int ui1 = *((const int *)bq8_1[0].qs + (iqs/2)); const int ui2 = *((const int *)bq8_1[0].qs + (iqs/2) + 4); const int ui3 = *((const int *)bq8_1[1].qs + (iqs/2)); const int ui4 = *((const int *)bq8_1[1].qs + (iqs/2) + 4); const int * ql = (const int *)bq5_K->qs + (iqs/2); const int vl1 = ql[0]; const int vl2 = ql[4]; const int step = 4 * (iqs/2); // 0, 4, 8, 12 const int im = step/8; // = 0 for iqs = 0, 2, = 1 for iqs = 4, 6 const int in = step%8; // 0, 4, 0, 4 const int vh = (*((const int *)(bq5_K->qh + in))) >> im; const int v1 = (((vh << 4) & 0x10101010) ^ 0x10101010) | ((vl1 >> 0) & 0x0f0f0f0f); const int v2 = (((vh << 2) & 0x10101010) ^ 0x10101010) | ((vl2 >> 0) & 0x0f0f0f0f); const int v3 = (((vh >> 0) & 0x10101010) ^ 0x10101010) | ((vl1 >> 4) & 0x0f0f0f0f); const int v4 = (((vh >> 2) & 0x10101010) ^ 0x10101010) | ((vl2 >> 4) & 0x0f0f0f0f); const float sumf_d = d8_1 * (ggml_cuda_dp4a(ui1, v1, 0) * s[0] + ggml_cuda_dp4a(ui2, v2, 0) * s[1]) + d8_2 * (ggml_cuda_dp4a(ui3, v3, 0) * s[2] + ggml_cuda_dp4a(ui4, v4, 0) * s[3]); return d * sumf_d; #endif } static __device__ __forceinline__ float vec_dot_q6_K_q8_1( const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs) { const block_q6_K * bq6_K = (const block_q6_K *) vbq; const int bq8_offset = 2 * QR6_K * (iqs / (QI6_K/2)) + (iqs % (QI6_K/2)) / (QI6_K/4); const int scale_offset = (QI6_K/4) * (iqs / (QI6_K/2)) + (iqs % (QI6_K/2)) / (QI6_K/8); const int vh_shift = 2 * ((iqs % (QI6_K/2)) / (QI6_K/4)); const int vl = get_int_from_uint8(bq6_K->ql, iqs); const int vh = get_int_from_uint8(bq6_K->qh, (QI6_K/4) * (iqs / (QI6_K/2)) + iqs % (QI6_K/4)) >> vh_shift; const int8_t * scales = bq6_K->scales + scale_offset; int u[QR6_K]; float d8[QR6_K]; #pragma unroll for (int i = 0; i < QR6_K; ++i) { u[i] = get_int_from_int8_aligned(bq8_1[bq8_offset + 2*i].qs, iqs % QI8_1); d8[i] = __low2float(bq8_1[bq8_offset + 2*i].ds); } return vec_dot_q6_K_q8_1_impl_mmvq(vl, vh, u, scales, bq6_K->d, d8); } // https://github.com/ggerganov/llama.cpp/blob/c50a82ce0f71558cbb8e555146ba124251504b38/ggml-cuda/mmvq.cu#L4 typedef float (*vec_dot_q_cuda_t)(const void * __restrict__ vbq, const block_q8_1 * __restrict__ bq8_1, const int & iqs); template <int ncols_y, int qk, int qi, typename block_q_t, int vdr, vec_dot_q_cuda_t vec_dot_q_cuda> static __device__ void mul_mat_vec_q( const void * __restrict__ vx, const void * __restrict__ vy, float * __restrict__ dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { #if defined(GGML_USE_HIPBLAS) && defined(__HIP_PLATFORM_AMD__) && (defined(RDNA2) || defined(RDNA3)) constexpr int nwarps = 1; constexpr int rows_per_cuda_block = 1; #else constexpr int nwarps = ncols_y <= 4 ? 4 : 2; constexpr int rows_per_cuda_block = ncols_y == 1 ? 1 : 2; #endif // defined(GGML_USE_HIPBLAS) && defined(__HIP_PLATFORM_AMD__) && !defined(RDNA2) && !defined(RDNA3) const int tid = WARP_SIZE*threadIdx.y + threadIdx.x; const int row0 = rows_per_cuda_block*blockIdx.x; const int blocks_per_row_x = ncols_x / qk; const int blocks_per_col_y = nrows_y / QK8_1; constexpr int blocks_per_iter = vdr * nwarps*WARP_SIZE / qi; // partial sum for each thread float tmp[ncols_y][rows_per_cuda_block] = {0.0f}; const block_q_t * x = (const block_q_t *) vx; const block_q8_1 * y = (const block_q8_1 *) vy; for (int kbx = tid / (qi/vdr); kbx < blocks_per_row_x; kbx += blocks_per_iter) { const int kby = kbx * (qk/QK8_1); // y block index that aligns with kbx // x block quant index when casting the quants to int const int kqs = vdr * (tid % (qi/vdr)); #pragma unroll for (int j = 0; j < ncols_y; ++j) { #pragma unroll for (int i = 0; i < rows_per_cuda_block; ++i) { tmp[j][i] += vec_dot_q_cuda( &x[kbx + (row0 + i)*blocks_per_row_x], &y[j*blocks_per_col_y + kby], kqs); } } } __shared__ float tmp_shared[nwarps-1 > 0 ? nwarps-1 : 1][ncols_y][rows_per_cuda_block][WARP_SIZE]; if (threadIdx.y > 0) { #pragma unroll for (int j = 0; j < ncols_y; ++j) { #pragma unroll for (int i = 0; i < rows_per_cuda_block; ++i) { tmp_shared[threadIdx.y-1][j][i][threadIdx.x] = tmp[j][i]; } } } __syncthreads(); if (threadIdx.y > 0) { return; } // sum up partial sums and write back result #pragma unroll for (int j = 0; j < ncols_y; ++j) { #pragma unroll for (int i = 0; i < rows_per_cuda_block; ++i) { #pragma unroll for (int l = 0; l < nwarps-1; ++l) { tmp[j][i] += tmp_shared[l][j][i][threadIdx.x]; } tmp[j][i] = warp_reduce_sum(tmp[j][i]); } if (threadIdx.x < rows_per_cuda_block) { dst[j*nrows_dst + row0 + threadIdx.x] = tmp[j][threadIdx.x]; } } } // batch size = 1 extern "C" __global__ void mul_mat_vec_q4_0_q8_1_cuda1( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<1, QK4_0, QI4_0, block_q4_0, VDR_Q4_0_Q8_1_MMVQ, vec_dot_q4_0_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q4_1_q8_1_cuda1( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<1, QK4_1, QI4_1, block_q4_1, VDR_Q4_1_Q8_1_MMVQ, vec_dot_q4_1_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q5_0_q8_1_cuda1( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<1, QK5_0, QI5_0, block_q5_0, VDR_Q5_0_Q8_1_MMVQ, vec_dot_q5_0_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q5_1_q8_1_cuda1( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<1, QK5_1, QI5_1, block_q5_1, VDR_Q5_1_Q8_1_MMVQ, vec_dot_q5_1_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q8_0_q8_1_cuda1( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<1, QK8_0, QI8_0, block_q8_0, VDR_Q8_0_Q8_1_MMVQ, vec_dot_q8_0_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q2_K_q8_1_cuda1( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<1, QK_K, QI2_K, block_q2_K, VDR_Q2_K_Q8_1_MMVQ, vec_dot_q2_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q3_K_q8_1_cuda1( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<1, QK_K, QI3_K, block_q3_K, VDR_Q3_K_Q8_1_MMVQ, vec_dot_q3_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q4_K_q8_1_cuda1( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<1, QK_K, QI4_K, block_q4_K, VDR_Q4_K_Q8_1_MMVQ, vec_dot_q4_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q5_K_q8_1_cuda1( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<1, QK_K, QI5_K, block_q5_K, VDR_Q5_K_Q8_1_MMVQ, vec_dot_q5_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q6_K_q8_1_cuda1( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<1, QK_K, QI6_K, block_q6_K, VDR_Q6_K_Q8_1_MMVQ, vec_dot_q6_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } // batch size = 2 extern "C" __global__ void mul_mat_vec_q4_0_q8_1_cuda2( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<2, QK4_0, QI4_0, block_q4_0, VDR_Q4_0_Q8_1_MMVQ, vec_dot_q4_0_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q4_1_q8_1_cuda2( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<2, QK4_1, QI4_1, block_q4_1, VDR_Q4_1_Q8_1_MMVQ, vec_dot_q4_1_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q5_0_q8_1_cuda2( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<2, QK5_0, QI5_0, block_q5_0, VDR_Q5_0_Q8_1_MMVQ, vec_dot_q5_0_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q5_1_q8_1_cuda2( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<2, QK5_1, QI5_1, block_q5_1, VDR_Q5_1_Q8_1_MMVQ, vec_dot_q5_1_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q8_0_q8_1_cuda2( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<2, QK8_0, QI8_0, block_q8_0, VDR_Q8_0_Q8_1_MMVQ, vec_dot_q8_0_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q2_K_q8_1_cuda2( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<2, QK_K, QI2_K, block_q2_K, VDR_Q2_K_Q8_1_MMVQ, vec_dot_q2_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q3_K_q8_1_cuda2( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<2, QK_K, QI3_K, block_q3_K, VDR_Q3_K_Q8_1_MMVQ, vec_dot_q3_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q4_K_q8_1_cuda2( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<2, QK_K, QI4_K, block_q4_K, VDR_Q4_K_Q8_1_MMVQ, vec_dot_q4_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q5_K_q8_1_cuda2( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<2, QK_K, QI5_K, block_q5_K, VDR_Q5_K_Q8_1_MMVQ, vec_dot_q5_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q6_K_q8_1_cuda2( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<2, QK_K, QI6_K, block_q6_K, VDR_Q6_K_Q8_1_MMVQ, vec_dot_q6_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } // batch size = 3 extern "C" __global__ void mul_mat_vec_q4_0_q8_1_cuda3( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<3, QK4_0, QI4_0, block_q4_0, VDR_Q4_0_Q8_1_MMVQ, vec_dot_q4_0_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q4_1_q8_1_cuda3( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<3, QK4_1, QI4_1, block_q4_1, VDR_Q4_1_Q8_1_MMVQ, vec_dot_q4_1_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q5_0_q8_1_cuda3( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<3, QK5_0, QI5_0, block_q5_0, VDR_Q5_0_Q8_1_MMVQ, vec_dot_q5_0_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q5_1_q8_1_cuda3( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<3, QK5_1, QI5_1, block_q5_1, VDR_Q5_1_Q8_1_MMVQ, vec_dot_q5_1_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q8_0_q8_1_cuda3( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<3, QK8_0, QI8_0, block_q8_0, VDR_Q8_0_Q8_1_MMVQ, vec_dot_q8_0_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q2_K_q8_1_cuda3( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<3, QK_K, QI2_K, block_q2_K, VDR_Q2_K_Q8_1_MMVQ, vec_dot_q2_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q3_K_q8_1_cuda3( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<3, QK_K, QI3_K, block_q3_K, VDR_Q3_K_Q8_1_MMVQ, vec_dot_q3_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q4_K_q8_1_cuda3( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<3, QK_K, QI4_K, block_q4_K, VDR_Q4_K_Q8_1_MMVQ, vec_dot_q4_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q5_K_q8_1_cuda3( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<3, QK_K, QI5_K, block_q5_K, VDR_Q5_K_Q8_1_MMVQ, vec_dot_q5_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q6_K_q8_1_cuda3( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<3, QK_K, QI6_K, block_q6_K, VDR_Q6_K_Q8_1_MMVQ, vec_dot_q6_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } // batch size = 4 extern "C" __global__ void mul_mat_vec_q4_0_q8_1_cuda4( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<4, QK4_0, QI4_0, block_q4_0, VDR_Q4_0_Q8_1_MMVQ, vec_dot_q4_0_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q4_1_q8_1_cuda4( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<4, QK4_1, QI4_1, block_q4_1, VDR_Q4_1_Q8_1_MMVQ, vec_dot_q4_1_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q5_0_q8_1_cuda4( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<4, QK5_0, QI5_0, block_q5_0, VDR_Q5_0_Q8_1_MMVQ, vec_dot_q5_0_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q5_1_q8_1_cuda4( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<4, QK5_1, QI5_1, block_q5_1, VDR_Q5_1_Q8_1_MMVQ, vec_dot_q5_1_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q8_0_q8_1_cuda4( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<4, QK8_0, QI8_0, block_q8_0, VDR_Q8_0_Q8_1_MMVQ, vec_dot_q8_0_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q2_K_q8_1_cuda4( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<4, QK_K, QI2_K, block_q2_K, VDR_Q2_K_Q8_1_MMVQ, vec_dot_q2_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q3_K_q8_1_cuda4( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<4, QK_K, QI3_K, block_q3_K, VDR_Q3_K_Q8_1_MMVQ, vec_dot_q3_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q4_K_q8_1_cuda4( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<4, QK_K, QI4_K, block_q4_K, VDR_Q4_K_Q8_1_MMVQ, vec_dot_q4_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q5_K_q8_1_cuda4( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<4, QK_K, QI5_K, block_q5_K, VDR_Q5_K_Q8_1_MMVQ, vec_dot_q5_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q6_K_q8_1_cuda4( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<4, QK_K, QI6_K, block_q6_K, VDR_Q6_K_Q8_1_MMVQ, vec_dot_q6_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } // batch size = 5 extern "C" __global__ void mul_mat_vec_q4_0_q8_1_cuda5( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<5, QK4_0, QI4_0, block_q4_0, VDR_Q4_0_Q8_1_MMVQ, vec_dot_q4_0_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q4_1_q8_1_cuda5( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<5, QK4_1, QI4_1, block_q4_1, VDR_Q4_1_Q8_1_MMVQ, vec_dot_q4_1_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q5_0_q8_1_cuda5( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<5, QK5_0, QI5_0, block_q5_0, VDR_Q5_0_Q8_1_MMVQ, vec_dot_q5_0_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q5_1_q8_1_cuda5( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<5, QK5_1, QI5_1, block_q5_1, VDR_Q5_1_Q8_1_MMVQ, vec_dot_q5_1_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q8_0_q8_1_cuda5( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<5, QK8_0, QI8_0, block_q8_0, VDR_Q8_0_Q8_1_MMVQ, vec_dot_q8_0_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q2_K_q8_1_cuda5( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<5, QK_K, QI2_K, block_q2_K, VDR_Q2_K_Q8_1_MMVQ, vec_dot_q2_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q3_K_q8_1_cuda5( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<5, QK_K, QI3_K, block_q3_K, VDR_Q3_K_Q8_1_MMVQ, vec_dot_q3_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q4_K_q8_1_cuda5( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<5, QK_K, QI4_K, block_q4_K, VDR_Q4_K_Q8_1_MMVQ, vec_dot_q4_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q5_K_q8_1_cuda5( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<5, QK_K, QI5_K, block_q5_K, VDR_Q5_K_Q8_1_MMVQ, vec_dot_q5_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q6_K_q8_1_cuda5( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<5, QK_K, QI6_K, block_q6_K, VDR_Q6_K_Q8_1_MMVQ, vec_dot_q6_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } // batch size = 6 extern "C" __global__ void mul_mat_vec_q4_0_q8_1_cuda6( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<6, QK4_0, QI4_0, block_q4_0, VDR_Q4_0_Q8_1_MMVQ, vec_dot_q4_0_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q4_1_q8_1_cuda6( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<6, QK4_1, QI4_1, block_q4_1, VDR_Q4_1_Q8_1_MMVQ, vec_dot_q4_1_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q5_0_q8_1_cuda6( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<6, QK5_0, QI5_0, block_q5_0, VDR_Q5_0_Q8_1_MMVQ, vec_dot_q5_0_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q5_1_q8_1_cuda6( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<6, QK5_1, QI5_1, block_q5_1, VDR_Q5_1_Q8_1_MMVQ, vec_dot_q5_1_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q8_0_q8_1_cuda6( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<6, QK8_0, QI8_0, block_q8_0, VDR_Q8_0_Q8_1_MMVQ, vec_dot_q8_0_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q2_K_q8_1_cuda6( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<6, QK_K, QI2_K, block_q2_K, VDR_Q2_K_Q8_1_MMVQ, vec_dot_q2_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q3_K_q8_1_cuda6( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<6, QK_K, QI3_K, block_q3_K, VDR_Q3_K_Q8_1_MMVQ, vec_dot_q3_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q4_K_q8_1_cuda6( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<6, QK_K, QI4_K, block_q4_K, VDR_Q4_K_Q8_1_MMVQ, vec_dot_q4_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q5_K_q8_1_cuda6( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<6, QK_K, QI5_K, block_q5_K, VDR_Q5_K_Q8_1_MMVQ, vec_dot_q5_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q6_K_q8_1_cuda6( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<6, QK_K, QI6_K, block_q6_K, VDR_Q6_K_Q8_1_MMVQ, vec_dot_q6_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } // batch size = 7 extern "C" __global__ void mul_mat_vec_q4_0_q8_1_cuda7( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<7, QK4_0, QI4_0, block_q4_0, VDR_Q4_0_Q8_1_MMVQ, vec_dot_q4_0_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q4_1_q8_1_cuda7( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<7, QK4_1, QI4_1, block_q4_1, VDR_Q4_1_Q8_1_MMVQ, vec_dot_q4_1_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q5_0_q8_1_cuda7( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<7, QK5_0, QI5_0, block_q5_0, VDR_Q5_0_Q8_1_MMVQ, vec_dot_q5_0_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q5_1_q8_1_cuda7( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<7, QK5_1, QI5_1, block_q5_1, VDR_Q5_1_Q8_1_MMVQ, vec_dot_q5_1_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q8_0_q8_1_cuda7( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<7, QK8_0, QI8_0, block_q8_0, VDR_Q8_0_Q8_1_MMVQ, vec_dot_q8_0_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q2_K_q8_1_cuda7( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<7, QK_K, QI2_K, block_q2_K, VDR_Q2_K_Q8_1_MMVQ, vec_dot_q2_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q3_K_q8_1_cuda7( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<7, QK_K, QI3_K, block_q3_K, VDR_Q3_K_Q8_1_MMVQ, vec_dot_q3_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q4_K_q8_1_cuda7( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<7, QK_K, QI4_K, block_q4_K, VDR_Q4_K_Q8_1_MMVQ, vec_dot_q4_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q5_K_q8_1_cuda7( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<7, QK_K, QI5_K, block_q5_K, VDR_Q5_K_Q8_1_MMVQ, vec_dot_q5_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q6_K_q8_1_cuda7( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<7, QK_K, QI6_K, block_q6_K, VDR_Q6_K_Q8_1_MMVQ, vec_dot_q6_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } // batch size = 8 extern "C" __global__ void mul_mat_vec_q4_0_q8_1_cuda8( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<8, QK4_0, QI4_0, block_q4_0, VDR_Q4_0_Q8_1_MMVQ, vec_dot_q4_0_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q4_1_q8_1_cuda8( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<8, QK4_1, QI4_1, block_q4_1, VDR_Q4_1_Q8_1_MMVQ, vec_dot_q4_1_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q5_0_q8_1_cuda8( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<8, QK5_0, QI5_0, block_q5_0, VDR_Q5_0_Q8_1_MMVQ, vec_dot_q5_0_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q5_1_q8_1_cuda8( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<8, QK5_1, QI5_1, block_q5_1, VDR_Q5_1_Q8_1_MMVQ, vec_dot_q5_1_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q8_0_q8_1_cuda8( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<8, QK8_0, QI8_0, block_q8_0, VDR_Q8_0_Q8_1_MMVQ, vec_dot_q8_0_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q2_K_q8_1_cuda8( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<8, QK_K, QI2_K, block_q2_K, VDR_Q2_K_Q8_1_MMVQ, vec_dot_q2_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q3_K_q8_1_cuda8( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<8, QK_K, QI3_K, block_q3_K, VDR_Q3_K_Q8_1_MMVQ, vec_dot_q3_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q4_K_q8_1_cuda8( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<8, QK_K, QI4_K, block_q4_K, VDR_Q4_K_Q8_1_MMVQ, vec_dot_q4_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q5_K_q8_1_cuda8( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<8, QK_K, QI5_K, block_q5_K, VDR_Q5_K_Q8_1_MMVQ, vec_dot_q5_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_vec_q6_K_q8_1_cuda8( const void * vx, const void * vy, float * dst, const int ncols_x, const int nrows_x, const int nrows_y, const int nrows_dst) { mul_mat_vec_q<8, QK_K, QI6_K, block_q6_K, VDR_Q6_K_Q8_1_MMVQ, vec_dot_q6_K_q8_1> (vx, vy, dst, ncols_x, nrows_x, nrows_y, nrows_dst); } extern "C" __global__ void quantize_q8_1(const float * __restrict__ x, void * __restrict__ vy, const int kx, const int kx_padded) { const int ix = blockDim.x*blockIdx.x + threadIdx.x; if (ix >= kx_padded) { return; } const int iy = blockDim.y*blockIdx.y + threadIdx.y; const int i_padded = iy*kx_padded + ix; block_q8_1 * y = (block_q8_1 *) vy; const int ib = i_padded / QK8_1; // block index const int iqs = i_padded % QK8_1; // quant index const float xi = ix < kx ? x[iy*kx + ix] : 0.0f; float amax = fabsf(xi); float sum = xi; amax = warp_reduce_max(amax); sum = warp_reduce_sum(sum); const float d = amax / 127; const int8_t q = amax == 0.0f ? 0 : roundf(xi / d); y[ib].qs[iqs] = q; if (iqs > 0) { return; } reinterpret_cast<half&>(y[ib].ds.x) = d; reinterpret_cast<half&>(y[ib].ds.y) = sum; } // Kernels from https://github.com/ggerganov/llama.cpp/blob/master/ggml-cuda/mmq.cu template <int mmq_y> static __device__ __forceinline__ void allocate_tiles_q5_0(int ** x_ql, half2 ** x_dm, int ** x_qh, int ** x_sc) { GGML_UNUSED(x_qh); GGML_UNUSED(x_sc); __shared__ int tile_x_ql[mmq_y * (2*WARP_SIZE) + mmq_y]; __shared__ float tile_x_d[mmq_y * (WARP_SIZE/QI5_0) + mmq_y/QI5_0]; *x_ql = tile_x_ql; *x_dm = (half2 *) tile_x_d; } template <int mmq_y, int nwarps, bool need_check> static __device__ __forceinline__ void load_tiles_q5_0( const void * __restrict__ vx, int * __restrict__ x_ql, half2 * __restrict__ x_dm, int * __restrict__ x_qh, int * __restrict__ x_sc, const int & i_offset, const int & i_max, const int & k, const int & blocks_per_row) { GGML_UNUSED(x_qh); GGML_UNUSED(x_sc); GGML_CUDA_ASSUME(i_offset >= 0); GGML_CUDA_ASSUME(i_offset < nwarps); GGML_CUDA_ASSUME(k >= 0); GGML_CUDA_ASSUME(k < WARP_SIZE); const int kbx = k / QI5_0; const int kqsx = k % QI5_0; const block_q5_0 * bx0 = (const block_q5_0 *) vx; #pragma unroll for (int i0 = 0; i0 < mmq_y; i0 += nwarps) { int i = i0 + i_offset; if (need_check) { i = min(i, i_max); } const block_q5_0 * bxi = bx0 + i*blocks_per_row + kbx; const int ql = get_int_from_uint8(bxi->qs, kqsx); const int qh = get_int_from_uint8(bxi->qh, 0) >> (4 * (k % QI5_0)); int qs0 = (ql >> 0) & 0x0F0F0F0F; qs0 |= (qh << 4) & 0x00000010; // 0 -> 4 qs0 |= (qh << 11) & 0x00001000; // 1 -> 12 qs0 |= (qh << 18) & 0x00100000; // 2 -> 20 qs0 |= (qh << 25) & 0x10000000; // 3 -> 28 qs0 = __vsubss4(qs0, 0x10101010); // subtract 16 x_ql[i * (2*WARP_SIZE + 1) + 2*k+0] = qs0; int qs1 = (ql >> 4) & 0x0F0F0F0F; qs1 |= (qh >> 12) & 0x00000010; // 16 -> 4 qs1 |= (qh >> 5) & 0x00001000; // 17 -> 12 qs1 |= (qh << 2) & 0x00100000; // 18 -> 20 qs1 |= (qh << 9) & 0x10000000; // 19 -> 28 qs1 = __vsubss4(qs1, 0x10101010); // subtract 16 x_ql[i * (2*WARP_SIZE + 1) + 2*k+1] = qs1; } const int blocks_per_tile_x_row = WARP_SIZE / QI5_0; const int kbxd = k % blocks_per_tile_x_row; float * x_dmf = (float *) x_dm; #pragma unroll for (int i0 = 0; i0 < mmq_y; i0 += nwarps * QI5_0) { int i = i0 + i_offset * QI5_0 + k / blocks_per_tile_x_row; if (need_check) { i = min(i, i_max); } const block_q5_0 * bxi = bx0 + i*blocks_per_row + kbxd; x_dmf[i * (WARP_SIZE/QI5_0) + i / QI5_0 + kbxd] = bxi->d; } } static __device__ __forceinline__ float vec_dot_q5_0_q8_1_mul_mat( const int * __restrict__ x_ql, const half2 * __restrict__ x_dm, const int * __restrict__ x_qh, const int * __restrict__ x_sc, const int * __restrict__ y_qs, const half2 * __restrict__ y_ds, const int & i, const int & j, const int & k) { GGML_UNUSED(x_qh); GGML_UNUSED(x_sc); const int kyqs = k % (QI8_1/2) + QI8_1 * (k / (QI8_1/2)); const int index_bx = i * (WARP_SIZE/QI5_0) + i/QI5_0 + k/QI5_0; const float * x_dmf = (const float *) x_dm; const float * y_df = (const float *) y_ds; int u[2*VDR_Q5_0_Q8_1_MMQ]; #pragma unroll for (int l = 0; l < VDR_Q5_0_Q8_1_MMQ; ++l) { u[2*l+0] = y_qs[j * WARP_SIZE + (kyqs + l) % WARP_SIZE]; u[2*l+1] = y_qs[j * WARP_SIZE + (kyqs + l + QI5_0) % WARP_SIZE]; } return vec_dot_q8_0_q8_1_impl<QR5_0*VDR_Q5_0_Q8_1_MMQ> (&x_ql[i * (2*WARP_SIZE + 1) + 2 * k], u, x_dmf[index_bx], y_df[j * (WARP_SIZE/QI8_1) + (2*k/QI8_1) % (WARP_SIZE/QI8_1)]); } template <int mmq_y> static __device__ __forceinline__ void allocate_tiles_q5_1(int ** x_ql, half2 ** x_dm, int ** x_qh, int ** x_sc) { GGML_UNUSED(x_qh); GGML_UNUSED(x_sc); __shared__ int tile_x_ql[mmq_y * (2*WARP_SIZE) + mmq_y]; __shared__ half2 tile_x_dm[mmq_y * (WARP_SIZE/QI5_1) + mmq_y/QI5_1]; *x_ql = tile_x_ql; *x_dm = tile_x_dm; } template <int mmq_y, int nwarps, bool need_check> static __device__ __forceinline__ void load_tiles_q5_1( const void * __restrict__ vx, int * __restrict__ x_ql, half2 * __restrict__ x_dm, int * __restrict__ x_qh, int * __restrict__ x_sc, const int & i_offset, const int & i_max, const int & k, const int & blocks_per_row) { GGML_UNUSED(x_qh); GGML_UNUSED(x_sc); GGML_CUDA_ASSUME(i_offset >= 0); GGML_CUDA_ASSUME(i_offset < nwarps); GGML_CUDA_ASSUME(k >= 0); GGML_CUDA_ASSUME(k < WARP_SIZE); const int kbx = k / QI5_1; const int kqsx = k % QI5_1; const block_q5_1 * bx0 = (const block_q5_1 *) vx; #pragma unroll for (int i0 = 0; i0 < mmq_y; i0 += nwarps) { int i = i0 + i_offset; if (need_check) { i = min(i, i_max); } const block_q5_1 * bxi = bx0 + i*blocks_per_row + kbx; const int ql = get_int_from_uint8_aligned(bxi->qs, kqsx); const int qh = get_int_from_uint8_aligned(bxi->qh, 0) >> (4 * (k % QI5_1)); int qs0 = (ql >> 0) & 0x0F0F0F0F; qs0 |= (qh << 4) & 0x00000010; // 0 -> 4 qs0 |= (qh << 11) & 0x00001000; // 1 -> 12 qs0 |= (qh << 18) & 0x00100000; // 2 -> 20 qs0 |= (qh << 25) & 0x10000000; // 3 -> 28 x_ql[i * (2*WARP_SIZE + 1) + 2*k+0] = qs0; int qs1 = (ql >> 4) & 0x0F0F0F0F; qs1 |= (qh >> 12) & 0x00000010; // 16 -> 4 qs1 |= (qh >> 5) & 0x00001000; // 17 -> 12 qs1 |= (qh << 2) & 0x00100000; // 18 -> 20 qs1 |= (qh << 9) & 0x10000000; // 19 -> 28 x_ql[i * (2*WARP_SIZE + 1) + 2*k+1] = qs1; } const int blocks_per_tile_x_row = WARP_SIZE / QI5_1; const int kbxd = k % blocks_per_tile_x_row; #pragma unroll for (int i0 = 0; i0 < mmq_y; i0 += nwarps * QI5_1) { int i = i0 + i_offset * QI5_1 + k / blocks_per_tile_x_row; if (need_check) { i = min(i, i_max); } const block_q5_1 * bxi = bx0 + i*blocks_per_row + kbxd; x_dm[i * (WARP_SIZE/QI5_1) + i / QI5_1 + kbxd] = bxi->dm; } } static __device__ __forceinline__ float vec_dot_q5_1_q8_1_mul_mat( const int * __restrict__ x_ql, const half2 * __restrict__ x_dm, const int * __restrict__ x_qh, const int * __restrict__ x_sc, const int * __restrict__ y_qs, const half2 * __restrict__ y_ds, const int & i, const int & j, const int & k) { GGML_UNUSED(x_qh); GGML_UNUSED(x_sc); const int kyqs = k % (QI8_1/2) + QI8_1 * (k / (QI8_1/2)); const int index_bx = i * (WARP_SIZE/QI5_1) + + i/QI5_1 + k/QI5_1; int u[2*VDR_Q5_1_Q8_1_MMQ]; #pragma unroll for (int l = 0; l < VDR_Q5_1_Q8_1_MMQ; ++l) { u[2*l+0] = y_qs[j * WARP_SIZE + (kyqs + l) % WARP_SIZE]; u[2*l+1] = y_qs[j * WARP_SIZE + (kyqs + l + QI5_1) % WARP_SIZE]; } return vec_dot_q8_1_q8_1_impl<QR5_1*VDR_Q5_1_Q8_1_MMQ> (&x_ql[i * (2*WARP_SIZE + 1) + 2 * k], u, x_dm[index_bx], y_ds[j * (WARP_SIZE/QI8_1) + (2*k/QI8_1) % (WARP_SIZE/QI8_1)]); } template <int mmq_y> static __device__ __forceinline__ void allocate_tiles_q8_0(int ** x_ql, half2 ** x_dm, int ** x_qh, int ** x_sc) { GGML_UNUSED(x_qh); GGML_UNUSED(x_sc); __shared__ int tile_x_qs[mmq_y * (WARP_SIZE) + mmq_y]; __shared__ float tile_x_d[mmq_y * (WARP_SIZE/QI8_0) + mmq_y/QI8_0]; *x_ql = tile_x_qs; *x_dm = (half2 *) tile_x_d; } template <int mmq_y, int nwarps, bool need_check> static __device__ __forceinline__ void load_tiles_q8_0( const void * __restrict__ vx, int * __restrict__ x_ql, half2 * __restrict__ x_dm, int * __restrict__ x_qh, int * __restrict__ x_sc, const int & i_offset, const int & i_max, const int & k, const int & blocks_per_row) { GGML_UNUSED(x_qh); GGML_UNUSED(x_sc); GGML_CUDA_ASSUME(i_offset >= 0); GGML_CUDA_ASSUME(i_offset < nwarps); GGML_CUDA_ASSUME(k >= 0); GGML_CUDA_ASSUME(k < WARP_SIZE); const int kbx = k / QI8_0; const int kqsx = k % QI8_0; float * x_dmf = (float *) x_dm; const block_q8_0 * bx0 = (const block_q8_0 *) vx; #pragma unroll for (int i0 = 0; i0 < mmq_y; i0 += nwarps) { int i = i0 + i_offset; if (need_check) { i = min(i, i_max); } const block_q8_0 * bxi = bx0 + i*blocks_per_row + kbx; x_ql[i * (WARP_SIZE + 1) + k] = get_int_from_int8(bxi->qs, kqsx); } const int blocks_per_tile_x_row = WARP_SIZE / QI8_0; const int kbxd = k % blocks_per_tile_x_row; #pragma unroll for (int i0 = 0; i0 < mmq_y; i0 += nwarps * QI8_0) { int i = i0 + i_offset * QI8_0 + k / blocks_per_tile_x_row; if (need_check) { i = min(i, i_max); } const block_q8_0 * bxi = bx0 + i*blocks_per_row + kbxd; x_dmf[i * (WARP_SIZE/QI8_0) + i / QI8_0 + kbxd] = bxi->d; } } static __device__ __forceinline__ float vec_dot_q8_0_q8_1_mul_mat( const int * __restrict__ x_ql, const half2 * __restrict__ x_dm, const int * __restrict__ x_qh, const int * __restrict__ x_sc, const int * __restrict__ y_qs, const half2 * __restrict__ y_ds, const int & i, const int & j, const int & k) { GGML_UNUSED(x_qh); GGML_UNUSED(x_sc); const float * x_dmf = (const float *) x_dm; const float * y_df = (const float *) y_ds; return vec_dot_q8_0_q8_1_impl<VDR_Q8_0_Q8_1_MMQ> (&x_ql[i * (WARP_SIZE + 1) + k], &y_qs[j * WARP_SIZE + k], x_dmf[i * (WARP_SIZE/QI8_0) + i/QI8_0 + k/QI8_0], y_df[j * (WARP_SIZE/QI8_1) + k/QI8_1]); } template <int mmq_y> static __device__ __forceinline__ void allocate_tiles_q2_K(int ** x_ql, half2 ** x_dm, int ** x_qh, int ** x_sc) { GGML_UNUSED(x_qh); __shared__ int tile_x_ql[mmq_y * (WARP_SIZE) + mmq_y]; __shared__ half2 tile_x_dm[mmq_y * (WARP_SIZE/QI2_K) + mmq_y/QI2_K]; __shared__ int tile_x_sc[mmq_y * (WARP_SIZE/4) + mmq_y/4]; *x_ql = tile_x_ql; *x_dm = tile_x_dm; *x_sc = tile_x_sc; } template <int mmq_y, int nwarps, bool need_check> static __device__ __forceinline__ void load_tiles_q2_K( const void * __restrict__ vx, int * __restrict__ x_ql, half2 * __restrict__ x_dm, int * __restrict__ x_qh, int * __restrict__ x_sc, const int & i_offset, const int & i_max, const int & k, const int & blocks_per_row) { GGML_UNUSED(x_qh); GGML_CUDA_ASSUME(i_offset >= 0); GGML_CUDA_ASSUME(i_offset < nwarps); GGML_CUDA_ASSUME(k >= 0); GGML_CUDA_ASSUME(k < WARP_SIZE); const int kbx = k / QI2_K; const int kqsx = k % QI2_K; const block_q2_K * bx0 = (const block_q2_K *) vx; #pragma unroll for (int i0 = 0; i0 < mmq_y; i0 += nwarps) { int i = i0 + i_offset; if (need_check) { i = min(i, i_max); } const block_q2_K * bxi = bx0 + i*blocks_per_row + kbx; x_ql[i * (WARP_SIZE + 1) + k] = get_int_from_uint8_aligned(bxi->qs, kqsx); } const int blocks_per_tile_x_row = WARP_SIZE / QI2_K; const int kbxd = k % blocks_per_tile_x_row; #pragma unroll for (int i0 = 0; i0 < mmq_y; i0 += nwarps * QI2_K) { int i = (i0 + i_offset * QI2_K + k / blocks_per_tile_x_row) % mmq_y; if (need_check) { i = min(i, i_max); } const block_q2_K * bxi = bx0 + i*blocks_per_row + kbxd; x_dm[i * (WARP_SIZE/QI2_K) + i / QI2_K + kbxd] = bxi->dm; } #pragma unroll for (int i0 = 0; i0 < mmq_y; i0 += nwarps * 4) { int i = i0 + i_offset * 4 + k / (WARP_SIZE/4); if (need_check) { i = min(i, i_max); } const block_q2_K * bxi = bx0 + i*blocks_per_row + (k % (WARP_SIZE/4)) / (QI2_K/4); x_sc[i * (WARP_SIZE/4) + i / 4 + k % (WARP_SIZE/4)] = get_int_from_uint8_aligned(bxi->scales, k % (QI2_K/4)); } } static __device__ __forceinline__ float vec_dot_q2_K_q8_1_mul_mat( const int * __restrict__ x_ql, const half2 * __restrict__ x_dm, const int * __restrict__ x_qh, const int * __restrict__ x_sc, const int * __restrict__ y_qs, const half2 * __restrict__ y_ds, const int & i, const int & j, const int & k) { GGML_UNUSED(x_qh); const int kbx = k / QI2_K; const int ky = (k % QI2_K) * QR2_K; const float * y_df = (const float *) y_ds; int v[QR2_K*VDR_Q2_K_Q8_1_MMQ]; const int kqsx = i * (WARP_SIZE + 1) + kbx*QI2_K + (QI2_K/2) * (ky/(2*QI2_K)) + ky % (QI2_K/2); const int shift = 2 * ((ky % (2*QI2_K)) / (QI2_K/2)); #pragma unroll for (int l = 0; l < QR2_K*VDR_Q2_K_Q8_1_MMQ; ++l) { v[l] = (x_ql[kqsx + l] >> shift) & 0x03030303; } const uint8_t * scales = ((const uint8_t *) &x_sc[i * (WARP_SIZE/4) + i/4 + kbx*4]) + ky/4; const int index_y = j * WARP_SIZE + (QR2_K*k) % WARP_SIZE; return vec_dot_q2_K_q8_1_impl_mmq(v, &y_qs[index_y], scales, x_dm[i * (WARP_SIZE/QI2_K) + i/QI2_K + kbx], y_df[index_y/QI8_1]); } template <int mmq_y> static __device__ __forceinline__ void allocate_tiles_q3_K(int ** x_ql, half2 ** x_dm, int ** x_qh, int ** x_sc) { __shared__ int tile_x_ql[mmq_y * (WARP_SIZE) + mmq_y]; __shared__ half2 tile_x_dm[mmq_y * (WARP_SIZE/QI3_K) + mmq_y/QI3_K]; __shared__ int tile_x_qh[mmq_y * (WARP_SIZE/2) + mmq_y/2]; __shared__ int tile_x_sc[mmq_y * (WARP_SIZE/4) + mmq_y/4]; *x_ql = tile_x_ql; *x_dm = tile_x_dm; *x_qh = tile_x_qh; *x_sc = tile_x_sc; } template <int mmq_y, int nwarps, bool need_check> static __device__ __forceinline__ void load_tiles_q3_K( const void * __restrict__ vx, int * __restrict__ x_ql, half2 * __restrict__ x_dm, int * __restrict__ x_qh, int * __restrict__ x_sc, const int & i_offset, const int & i_max, const int & k, const int & blocks_per_row) { GGML_CUDA_ASSUME(i_offset >= 0); GGML_CUDA_ASSUME(i_offset < nwarps); GGML_CUDA_ASSUME(k >= 0); GGML_CUDA_ASSUME(k < WARP_SIZE); const int kbx = k / QI3_K; const int kqsx = k % QI3_K; const block_q3_K * bx0 = (const block_q3_K *) vx; #pragma unroll for (int i0 = 0; i0 < mmq_y; i0 += nwarps) { int i = i0 + i_offset; if (need_check) { i = min(i, i_max); } const block_q3_K * bxi = bx0 + i*blocks_per_row + kbx; x_ql[i * (WARP_SIZE + 1) + k] = get_int_from_uint8(bxi->qs, kqsx); } const int blocks_per_tile_x_row = WARP_SIZE / QI3_K; const int kbxd = k % blocks_per_tile_x_row; float * x_dmf = (float *) x_dm; #pragma unroll for (int i0 = 0; i0 < mmq_y; i0 += nwarps * QI3_K) { int i = (i0 + i_offset * QI3_K + k / blocks_per_tile_x_row) % mmq_y; if (need_check) { i = min(i, i_max); } const block_q3_K * bxi = bx0 + i*blocks_per_row + kbxd; x_dmf[i * (WARP_SIZE/QI3_K) + i / QI3_K + kbxd] = bxi->d; } #pragma unroll for (int i0 = 0; i0 < mmq_y; i0 += nwarps * 2) { int i = i0 + i_offset * 2 + k / (WARP_SIZE/2); if (need_check) { i = min(i, i_max); } const block_q3_K * bxi = bx0 + i*blocks_per_row + (k % (WARP_SIZE/2)) / (QI3_K/2); // invert the mask with ~ so that a 0/1 results in 4/0 being subtracted x_qh[i * (WARP_SIZE/2) + i / 2 + k % (WARP_SIZE/2)] = ~get_int_from_uint8(bxi->hmask, k % (QI3_K/2)); } #pragma unroll for (int i0 = 0; i0 < mmq_y; i0 += nwarps * 4) { int i = i0 + i_offset * 4 + k / (WARP_SIZE/4); if (need_check) { i = min(i, i_max); } const block_q3_K * bxi = bx0 + i*blocks_per_row + (k % (WARP_SIZE/4)) / (QI3_K/4); const int ksc = k % (QI3_K/4); const int ksc_low = ksc % (QI3_K/8); const int shift_low = 4 * (ksc / (QI3_K/8)); const int sc_low = (get_int_from_uint8(bxi->scales, ksc_low) >> shift_low) & 0x0F0F0F0F; const int ksc_high = QI3_K/8; const int shift_high = 2 * ksc; const int sc_high = ((get_int_from_uint8(bxi->scales, ksc_high) >> shift_high) << 4) & 0x30303030; const int sc = __vsubss4(sc_low | sc_high, 0x20202020); x_sc[i * (WARP_SIZE/4) + i / 4 + k % (WARP_SIZE/4)] = sc; } } static __device__ __forceinline__ float vec_dot_q3_K_q8_1_mul_mat( const int * __restrict__ x_ql, const half2 * __restrict__ x_dm, const int * __restrict__ x_qh, const int * __restrict__ x_sc, const int * __restrict__ y_qs, const half2 * __restrict__ y_ds, const int & i, const int & j, const int & k) { const int kbx = k / QI3_K; const int ky = (k % QI3_K) * QR3_K; const float * x_dmf = (const float *) x_dm; const float * y_df = (const float *) y_ds; const int8_t * scales = ((const int8_t *) (x_sc + i * (WARP_SIZE/4) + i/4 + kbx*4)) + ky/4; int v[QR3_K*VDR_Q3_K_Q8_1_MMQ]; #pragma unroll for (int l = 0; l < QR3_K*VDR_Q3_K_Q8_1_MMQ; ++l) { const int kqsx = i * (WARP_SIZE + 1) + kbx*QI3_K + (QI3_K/2) * (ky/(2*QI3_K)) + ky % (QI3_K/2); const int shift = 2 * ((ky % 32) / 8); const int vll = (x_ql[kqsx + l] >> shift) & 0x03030303; const int vh = x_qh[i * (WARP_SIZE/2) + i/2 + kbx * (QI3_K/2) + (ky+l)%8] >> ((ky+l) / 8); const int vlh = (vh << 2) & 0x04040404; v[l] = __vsubss4(vll, vlh); } const int index_y = j * WARP_SIZE + (k*QR3_K) % WARP_SIZE; return vec_dot_q3_K_q8_1_impl_mmq(v, &y_qs[index_y], scales, x_dmf[i * (WARP_SIZE/QI3_K) + i/QI3_K + kbx], y_df[index_y/QI8_1]); } template <int mmq_y> static __device__ __forceinline__ void allocate_tiles_q4_K(int ** x_ql, half2 ** x_dm, int ** x_qh, int ** x_sc) { GGML_UNUSED(x_qh); __shared__ int tile_x_ql[mmq_y * (WARP_SIZE) + mmq_y]; __shared__ half2 tile_x_dm[mmq_y * (WARP_SIZE/QI4_K) + mmq_y/QI4_K]; __shared__ int tile_x_sc[mmq_y * (WARP_SIZE/8) + mmq_y/8]; *x_ql = tile_x_ql; *x_dm = tile_x_dm; *x_sc = tile_x_sc; } template <int mmq_y, int nwarps, bool need_check> static __device__ __forceinline__ void load_tiles_q4_K( const void * __restrict__ vx, int * __restrict__ x_ql, half2 * __restrict__ x_dm, int * __restrict__ x_qh, int * __restrict__ x_sc, const int & i_offset, const int & i_max, const int & k, const int & blocks_per_row) { GGML_UNUSED(x_qh); GGML_CUDA_ASSUME(i_offset >= 0); GGML_CUDA_ASSUME(i_offset < nwarps); GGML_CUDA_ASSUME(k >= 0); GGML_CUDA_ASSUME(k < WARP_SIZE); const int kbx = k / QI4_K; // == 0 if QK_K == 256 const int kqsx = k % QI4_K; // == k if QK_K == 256 const block_q4_K * bx0 = (const block_q4_K *) vx; #pragma unroll for (int i0 = 0; i0 < mmq_y; i0 += nwarps) { int i = i0 + i_offset; if (need_check) { i = min(i, i_max); } const block_q4_K * bxi = bx0 + i*blocks_per_row + kbx; x_ql[i * (WARP_SIZE + 1) + k] = get_int_from_uint8_aligned(bxi->qs, kqsx); } const int blocks_per_tile_x_row = WARP_SIZE / QI4_K; // == 1 if QK_K == 256 const int kbxd = k % blocks_per_tile_x_row; // == 0 if QK_K == 256 #pragma unroll for (int i0 = 0; i0 < mmq_y; i0 += nwarps * QI4_K) { int i = (i0 + i_offset * QI4_K + k / blocks_per_tile_x_row) % mmq_y; if (need_check) { i = min(i, i_max); } const block_q4_K * bxi = bx0 + i*blocks_per_row + kbxd; #if QK_K == 256 x_dm[i * (WARP_SIZE/QI4_K) + i / QI4_K + kbxd] = bxi->dm; #else x_dm[i * (WARP_SIZE/QI4_K) + i / QI4_K + kbxd] = {bxi->dm[0], bxi->dm[1]}; #endif } #pragma unroll for (int i0 = 0; i0 < mmq_y; i0 += nwarps * 8) { int i = (i0 + i_offset * 8 + k / (WARP_SIZE/8)) % mmq_y; if (need_check) { i = min(i, i_max); } const block_q4_K * bxi = bx0 + i*blocks_per_row + (k % (WARP_SIZE/8)) / (QI4_K/8); const int * scales = (const int *) bxi->scales; const int ksc = k % (WARP_SIZE/8); // scale arrangement after the following two lines: sc0,...,sc3, sc4,...,sc7, m0,...,m3, m4,...,m8 int scales8 = (scales[(ksc%2) + (ksc!=0)] >> (4 * (ksc & (ksc/2)))) & 0x0F0F0F0F; // lower 4 bits scales8 |= (scales[ksc/2] >> (2 * (ksc % 2))) & 0x30303030; // upper 2 bits x_sc[i * (WARP_SIZE/8) + i / 8 + ksc] = scales8; } } static __device__ __forceinline__ float vec_dot_q4_K_q8_1_mul_mat( const int * __restrict__ x_ql, const half2 * __restrict__ x_dm, const int * __restrict__ x_qh, const int * __restrict__ x_sc, const int * __restrict__ y_qs, const half2 * __restrict__ y_ds, const int & i, const int & j, const int & k) { GGML_UNUSED(x_qh); const uint8_t * sc = ((const uint8_t *) &x_sc[i * (WARP_SIZE/8) + i/8 + k/16]) + 2*((k % 16) / 8); const int index_y = j * WARP_SIZE + (QR4_K*k) % WARP_SIZE; return vec_dot_q4_K_q8_1_impl_mmq(&x_ql[i * (WARP_SIZE + 1) + k], &y_qs[index_y], sc, sc+8, x_dm[i * (WARP_SIZE/QI4_K) + i/QI4_K], &y_ds[index_y/QI8_1]); } template <int mmq_y> static __device__ __forceinline__ void allocate_tiles_q5_K(int ** x_ql, half2 ** x_dm, int ** x_qh, int ** x_sc) { GGML_UNUSED(x_qh); __shared__ int tile_x_ql[mmq_y * (2*WARP_SIZE) + mmq_y]; __shared__ half2 tile_x_dm[mmq_y * (WARP_SIZE/QI5_K) + mmq_y/QI5_K]; __shared__ int tile_x_sc[mmq_y * (WARP_SIZE/8) + mmq_y/8]; *x_ql = tile_x_ql; *x_dm = tile_x_dm; *x_sc = tile_x_sc; } template <int mmq_y, int nwarps, bool need_check> static __device__ __forceinline__ void load_tiles_q5_K( const void * __restrict__ vx, int * __restrict__ x_ql, half2 * __restrict__ x_dm, int * __restrict__ x_qh, int * __restrict__ x_sc, const int & i_offset, const int & i_max, const int & k, const int & blocks_per_row) { GGML_UNUSED(x_qh); GGML_CUDA_ASSUME(i_offset >= 0); GGML_CUDA_ASSUME(i_offset < nwarps); GGML_CUDA_ASSUME(k >= 0); GGML_CUDA_ASSUME(k < WARP_SIZE); const int kbx = k / QI5_K; // == 0 if QK_K == 256 const int kqsx = k % QI5_K; // == k if QK_K == 256 const block_q5_K * bx0 = (const block_q5_K *) vx; #pragma unroll for (int i0 = 0; i0 < mmq_y; i0 += nwarps) { int i = i0 + i_offset; if (need_check) { i = min(i, i_max); } const block_q5_K * bxi = bx0 + i*blocks_per_row + kbx; const int ky = QR5_K*kqsx; const int ql = get_int_from_uint8_aligned(bxi->qs, kqsx); const int ql0 = (ql >> 0) & 0x0F0F0F0F; const int ql1 = (ql >> 4) & 0x0F0F0F0F; const int qh = get_int_from_uint8_aligned(bxi->qh, kqsx % (QI5_K/4)); const int qh0 = ((qh >> (2 * (kqsx / (QI5_K/4)) + 0)) << 4) & 0x10101010; const int qh1 = ((qh >> (2 * (kqsx / (QI5_K/4)) + 1)) << 4) & 0x10101010; const int kq0 = ky - ky % (QI5_K/2) + k % (QI5_K/4) + 0; const int kq1 = ky - ky % (QI5_K/2) + k % (QI5_K/4) + (QI5_K/4); x_ql[i * (2*WARP_SIZE + 1) + kq0] = ql0 | qh0; x_ql[i * (2*WARP_SIZE + 1) + kq1] = ql1 | qh1; } const int blocks_per_tile_x_row = WARP_SIZE / QI5_K; // == 1 if QK_K == 256 const int kbxd = k % blocks_per_tile_x_row; // == 0 if QK_K == 256 #pragma unroll for (int i0 = 0; i0 < mmq_y; i0 += nwarps * QI5_K) { int i = (i0 + i_offset * QI5_K + k / blocks_per_tile_x_row) % mmq_y; if (need_check) { i = min(i, i_max); } const block_q5_K * bxi = bx0 + i*blocks_per_row + kbxd; #if QK_K == 256 x_dm[i * (WARP_SIZE/QI5_K) + i / QI5_K + kbxd] = bxi->dm; #endif } #pragma unroll for (int i0 = 0; i0 < mmq_y; i0 += nwarps * 8) { int i = (i0 + i_offset * 8 + k / (WARP_SIZE/8)) % mmq_y; if (need_check) { i = min(i, i_max); } const block_q5_K * bxi = bx0 + i*blocks_per_row + (k % (WARP_SIZE/8)) / (QI5_K/8); const int * scales = (const int *) bxi->scales; const int ksc = k % (WARP_SIZE/8); // scale arrangement after the following two lines: sc0,...,sc3, sc4,...,sc7, m0,...,m3, m4,...,m8 int scales8 = (scales[(ksc%2) + (ksc!=0)] >> (4 * (ksc & (ksc/2)))) & 0x0F0F0F0F; // lower 4 bits scales8 |= (scales[ksc/2] >> (2 * (ksc % 2))) & 0x30303030; // upper 2 bits x_sc[i * (WARP_SIZE/8) + i / 8 + ksc] = scales8; } } static __device__ __forceinline__ float vec_dot_q5_K_q8_1_mul_mat( const int * __restrict__ x_ql, const half2 * __restrict__ x_dm, const int * __restrict__ x_qh, const int * __restrict__ x_sc, const int * __restrict__ y_qs, const half2 * __restrict__ y_ds, const int & i, const int & j, const int & k) { GGML_UNUSED(x_qh); const uint8_t * sc = ((const uint8_t *) &x_sc[i * (WARP_SIZE/8) + i/8 + k/16]) + 2 * ((k % 16) / 8); const int index_x = i * (QR5_K*WARP_SIZE + 1) + QR5_K*k; const int index_y = j * WARP_SIZE + (QR5_K*k) % WARP_SIZE; return vec_dot_q5_K_q8_1_impl_mmq(&x_ql[index_x], &y_qs[index_y], sc, sc+8, x_dm[i * (WARP_SIZE/QI5_K) + i/QI5_K], &y_ds[index_y/QI8_1]); } template <int mmq_y> static __device__ __forceinline__ void allocate_tiles_q6_K(int ** x_ql, half2 ** x_dm, int ** x_qh, int ** x_sc) { GGML_UNUSED(x_qh); __shared__ int tile_x_ql[mmq_y * (2*WARP_SIZE) + mmq_y]; __shared__ half2 tile_x_dm[mmq_y * (WARP_SIZE/QI6_K) + mmq_y/QI6_K]; __shared__ int tile_x_sc[mmq_y * (WARP_SIZE/8) + mmq_y/8]; *x_ql = tile_x_ql; *x_dm = tile_x_dm; *x_sc = tile_x_sc; } template <int mmq_y, int nwarps, bool need_check> static __device__ __forceinline__ void load_tiles_q6_K( const void * __restrict__ vx, int * __restrict__ x_ql, half2 * __restrict__ x_dm, int * __restrict__ x_qh, int * __restrict__ x_sc, const int & i_offset, const int & i_max, const int & k, const int & blocks_per_row) { GGML_UNUSED(x_qh); GGML_CUDA_ASSUME(i_offset >= 0); GGML_CUDA_ASSUME(i_offset < nwarps); GGML_CUDA_ASSUME(k >= 0); GGML_CUDA_ASSUME(k < WARP_SIZE); const int kbx = k / QI6_K; // == 0 if QK_K == 256 const int kqsx = k % QI6_K; // == k if QK_K == 256 const block_q6_K * bx0 = (const block_q6_K *) vx; #pragma unroll for (int i0 = 0; i0 < mmq_y; i0 += nwarps) { int i = i0 + i_offset; if (need_check) { i = min(i, i_max); } const block_q6_K * bxi = bx0 + i*blocks_per_row + kbx; const int ky = QR6_K*kqsx; const int ql = get_int_from_uint8(bxi->ql, kqsx); const int ql0 = (ql >> 0) & 0x0F0F0F0F; const int ql1 = (ql >> 4) & 0x0F0F0F0F; const int qh = get_int_from_uint8(bxi->qh, (QI6_K/4) * (kqsx / (QI6_K/2)) + kqsx % (QI6_K/4)); const int qh0 = ((qh >> (2 * ((kqsx % (QI6_K/2)) / (QI6_K/4)))) << 4) & 0x30303030; const int qh1 = (qh >> (2 * ((kqsx % (QI6_K/2)) / (QI6_K/4)))) & 0x30303030; const int kq0 = ky - ky % QI6_K + k % (QI6_K/2) + 0; const int kq1 = ky - ky % QI6_K + k % (QI6_K/2) + (QI6_K/2); x_ql[i * (2*WARP_SIZE + 1) + kq0] = __vsubss4(ql0 | qh0, 0x20202020); x_ql[i * (2*WARP_SIZE + 1) + kq1] = __vsubss4(ql1 | qh1, 0x20202020); } const int blocks_per_tile_x_row = WARP_SIZE / QI6_K; // == 1 if QK_K == 256 const int kbxd = k % blocks_per_tile_x_row; // == 0 if QK_K == 256 float * x_dmf = (float *) x_dm; #pragma unroll for (int i0 = 0; i0 < mmq_y; i0 += nwarps * QI6_K) { int i = (i0 + i_offset * QI6_K + k / blocks_per_tile_x_row) % mmq_y; if (need_check) { i = min(i, i_max); } const block_q6_K * bxi = bx0 + i*blocks_per_row + kbxd; x_dmf[i * (WARP_SIZE/QI6_K) + i / QI6_K + kbxd] = bxi->d; } #pragma unroll for (int i0 = 0; i0 < mmq_y; i0 += nwarps * 8) { int i = (i0 + i_offset * 8 + k / (WARP_SIZE/8)) % mmq_y; if (need_check) { i = min(i, i_max); } const block_q6_K * bxi = bx0 + i*blocks_per_row + (k % (WARP_SIZE/8)) / 4; x_sc[i * (WARP_SIZE/8) + i / 8 + k % (WARP_SIZE/8)] = get_int_from_int8(bxi->scales, k % (QI6_K/8)); } } static __device__ __forceinline__ float vec_dot_q6_K_q8_1_mul_mat( const int * __restrict__ x_ql, const half2 * __restrict__ x_dm, const int * __restrict__ x_qh, const int * __restrict__ x_sc, const int * __restrict__ y_qs, const half2 * __restrict__ y_ds, const int & i, const int & j, const int & k) { GGML_UNUSED(x_qh); const float * x_dmf = (const float *) x_dm; const float * y_df = (const float *) y_ds; const int8_t * sc = ((const int8_t *) &x_sc[i * (WARP_SIZE/8) + i/8 + k/8]); const int index_x = i * (QR6_K*WARP_SIZE + 1) + QR6_K*k; const int index_y = j * WARP_SIZE + (QR6_K*k) % WARP_SIZE; return vec_dot_q6_K_q8_1_impl_mmq(&x_ql[index_x], &y_qs[index_y], sc, x_dmf[i * (WARP_SIZE/QI6_K) + i/QI6_K], &y_df[index_y/QI8_1]); } static __device__ __forceinline__ float vec_dot_q4_0_q8_1_mul_mat( const int * __restrict__ x_ql, const half2 * __restrict__ x_dm, const int * __restrict__ x_qh, const int * __restrict__ x_sc, const int * __restrict__ y_qs, const half2 * __restrict__ y_ds, const int & i, const int & j, const int & k) { const int kyqs = k % (QI8_1/2) + QI8_1 * (k / (QI8_1/2)); const float * x_dmf = (const float *) x_dm; int u[2*VDR_Q4_0_Q8_1_MMQ]; #pragma unroll for (int l = 0; l < VDR_Q4_0_Q8_1_MMQ; ++l) { u[2*l+0] = y_qs[j * WARP_SIZE + (kyqs + l) % WARP_SIZE]; u[2*l+1] = y_qs[j * WARP_SIZE + (kyqs + l + QI4_0) % WARP_SIZE]; } return vec_dot_q4_0_q8_1_impl<VDR_Q4_0_Q8_1_MMQ> (&x_ql[i * (WARP_SIZE + 1) + k], u, x_dmf[i * (WARP_SIZE/QI4_0) + i/QI4_0 + k/QI4_0], y_ds[j * (WARP_SIZE/QI8_1) + (2*k/QI8_1) % (WARP_SIZE/QI8_1)]); } static __device__ __forceinline__ float vec_dot_q4_1_q8_1_mul_mat( const int * __restrict__ x_ql, const half2 * __restrict__ x_dm, const int * __restrict__ x_qh, const int * __restrict__ x_sc, const int * __restrict__ y_qs, const half2 * __restrict__ y_ds, const int & i, const int & j, const int & k) { GGML_UNUSED(x_qh); GGML_UNUSED(x_sc); const int kyqs = k % (QI8_1/2) + QI8_1 * (k / (QI8_1/2)); int u[2*VDR_Q4_1_Q8_1_MMQ]; #pragma unroll for (int l = 0; l < VDR_Q4_1_Q8_1_MMQ; ++l) { u[2*l+0] = y_qs[j * WARP_SIZE + (kyqs + l) % WARP_SIZE]; u[2*l+1] = y_qs[j * WARP_SIZE + (kyqs + l + QI4_1) % WARP_SIZE]; } return vec_dot_q4_1_q8_1_impl<VDR_Q4_1_Q8_1_MMQ> (&x_ql[i * (WARP_SIZE + 1) + k], u, x_dm[i * (WARP_SIZE/QI4_1) + i/QI4_1 + k/QI4_1], y_ds[j * (WARP_SIZE/QI8_1) + (2*k/QI8_1) % (WARP_SIZE/QI8_1)]); } extern "C" __global__ void mul_mat_q4_0( const void * __restrict__ vx, const void * __restrict__ vy, float * __restrict__ dst, const int ncols_x, const int nrows_x, const int ncols_y, const int nrows_y, const int nrows_dst) { const int mmq_x = MMQ_X_Q4_0_AMPERE; const int mmq_y = MMQ_Y_Q4_0_AMPERE; const int nwarps = NWARPS_Q4_0_AMPERE; mul_mat_q<QK4_0, QR4_0, QI4_0, true, block_q4_0, mmq_x, mmq_y, nwarps, allocate_tiles_q4_0<mmq_y>, load_tiles_q4_0<mmq_y, nwarps, true>, VDR_Q4_0_Q8_1_MMQ, vec_dot_q4_0_q8_1_mul_mat> (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_q4_1( const void * __restrict__ vx, const void * __restrict__ vy, float * __restrict__ dst, const int ncols_x, const int nrows_x, const int ncols_y, const int nrows_y, const int nrows_dst) { const int mmq_x = MMQ_X_Q4_1_AMPERE; const int mmq_y = MMQ_Y_Q4_1_AMPERE; const int nwarps = NWARPS_Q4_1_AMPERE; mul_mat_q<QK4_1, QR4_1, QI4_1, true, block_q4_1, mmq_x, mmq_y, nwarps, allocate_tiles_q4_1<mmq_y>, load_tiles_q4_1<mmq_y, nwarps, true>, VDR_Q4_1_Q8_1_MMQ, vec_dot_q4_1_q8_1_mul_mat> (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_q5_0( const void * __restrict__ vx, const void * __restrict__ vy, float * __restrict__ dst, const int ncols_x, const int nrows_x, const int ncols_y, const int nrows_y, const int nrows_dst) { const int mmq_x = MMQ_X_Q5_0_AMPERE; const int mmq_y = MMQ_Y_Q5_0_AMPERE; const int nwarps = NWARPS_Q5_0_AMPERE; mul_mat_q<QK5_0, QR5_0, QI5_0, false, block_q5_0, mmq_x, mmq_y, nwarps, allocate_tiles_q5_0<mmq_y>, load_tiles_q5_0<mmq_y, nwarps, true>, VDR_Q5_0_Q8_1_MMQ, vec_dot_q5_0_q8_1_mul_mat> (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_q5_1( const void * __restrict__ vx, const void * __restrict__ vy, float * __restrict__ dst, const int ncols_x, const int nrows_x, const int ncols_y, const int nrows_y, const int nrows_dst) { const int mmq_x = MMQ_X_Q5_1_AMPERE; const int mmq_y = MMQ_Y_Q5_1_AMPERE; const int nwarps = NWARPS_Q5_1_AMPERE; mul_mat_q<QK5_1, QR5_1, QI5_1, true, block_q5_1, mmq_x, mmq_y, nwarps, allocate_tiles_q5_1<mmq_y>, load_tiles_q5_1<mmq_y, nwarps, true>, VDR_Q5_1_Q8_1_MMQ, vec_dot_q5_1_q8_1_mul_mat> (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_q8_0( const void * __restrict__ vx, const void * __restrict__ vy, float * __restrict__ dst, const int ncols_x, const int nrows_x, const int ncols_y, const int nrows_y, const int nrows_dst) { const int mmq_x = MMQ_X_Q8_0_AMPERE; const int mmq_y = MMQ_Y_Q8_0_AMPERE; const int nwarps = NWARPS_Q8_0_AMPERE; mul_mat_q<QK8_0, QR8_0, QI8_0, false, block_q8_0, mmq_x, mmq_y, nwarps, allocate_tiles_q8_0<mmq_y>, load_tiles_q8_0<mmq_y, nwarps, true>, VDR_Q8_0_Q8_1_MMQ, vec_dot_q8_0_q8_1_mul_mat> (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_q2_K( const void * __restrict__ vx, const void * __restrict__ vy, float * __restrict__ dst, const int ncols_x, const int nrows_x, const int ncols_y, const int nrows_y, const int nrows_dst) { const int mmq_x = MMQ_X_Q2_K_AMPERE; const int mmq_y = MMQ_Y_Q2_K_AMPERE; const int nwarps = NWARPS_Q2_K_AMPERE; mul_mat_q<QK_K, QR2_K, QI2_K, false, block_q2_K, mmq_x, mmq_y, nwarps, allocate_tiles_q2_K<mmq_y>, load_tiles_q2_K<mmq_y, nwarps, true>, VDR_Q2_K_Q8_1_MMQ, vec_dot_q2_K_q8_1_mul_mat> (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_q3_K( const void * __restrict__ vx, const void * __restrict__ vy, float * __restrict__ dst, const int ncols_x, const int nrows_x, const int ncols_y, const int nrows_y, const int nrows_dst) { const int mmq_x = MMQ_X_Q3_K_AMPERE; const int mmq_y = MMQ_Y_Q3_K_AMPERE; const int nwarps = NWARPS_Q3_K_AMPERE; mul_mat_q<QK_K, QR3_K, QI3_K, false, block_q3_K, mmq_x, mmq_y, nwarps, allocate_tiles_q3_K<mmq_y>, load_tiles_q3_K<mmq_y, nwarps, true>, VDR_Q3_K_Q8_1_MMQ, vec_dot_q3_K_q8_1_mul_mat> (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_q4_K( const void * __restrict__ vx, const void * __restrict__ vy, float * __restrict__ dst, const int ncols_x, const int nrows_x, const int ncols_y, const int nrows_y, const int nrows_dst) { const int mmq_x = MMQ_X_Q4_K_AMPERE; const int mmq_y = MMQ_Y_Q4_K_AMPERE; const int nwarps = NWARPS_Q4_K_AMPERE; mul_mat_q<QK_K, QR4_K, QI4_K, true, block_q4_K, mmq_x, mmq_y, nwarps, allocate_tiles_q4_K<mmq_y>, load_tiles_q4_K<mmq_y, nwarps, true>, VDR_Q4_K_Q8_1_MMQ, vec_dot_q4_K_q8_1_mul_mat> (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_q5_K( const void * __restrict__ vx, const void * __restrict__ vy, float * __restrict__ dst, const int ncols_x, const int nrows_x, const int ncols_y, const int nrows_y, const int nrows_dst) { const int mmq_x = MMQ_X_Q5_K_AMPERE; const int mmq_y = MMQ_Y_Q5_K_AMPERE; const int nwarps = NWARPS_Q5_K_AMPERE; mul_mat_q<QK_K, QR5_K, QI5_K, true, block_q5_K, mmq_x, mmq_y, nwarps, allocate_tiles_q5_K<mmq_y>, load_tiles_q5_K<mmq_y, nwarps, true>, VDR_Q5_K_Q8_1_MMQ, vec_dot_q5_K_q8_1_mul_mat> (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); } extern "C" __global__ void mul_mat_q6_K( const void * __restrict__ vx, const void * __restrict__ vy, float * __restrict__ dst, const int ncols_x, const int nrows_x, const int ncols_y, const int nrows_y, const int nrows_dst) { const int mmq_x = MMQ_X_Q6_K_AMPERE; const int mmq_y = MMQ_Y_Q6_K_AMPERE; const int nwarps = NWARPS_Q6_K_AMPERE; mul_mat_q<QK_K, QR6_K, QI6_K, false, block_q6_K, mmq_x, mmq_y, nwarps, allocate_tiles_q6_K<mmq_y>, load_tiles_q6_K<mmq_y, nwarps, true>, VDR_Q6_K_Q8_1_MMQ, vec_dot_q6_K_q8_1_mul_mat> (vx, vy, dst, ncols_x, nrows_x, ncols_y, nrows_y, nrows_dst); }
candle/candle-kernels/src/quantized.cu/0
{ "file_path": "candle/candle-kernels/src/quantized.cu", "repo_id": "candle", "token_count": 85791 }
48
use crate::utils::EncoderProvider; use crate::{ConstantValues, Kernels, MetalKernelError, Source, Value}; use metal::{Buffer, ComputeCommandEncoderRef, Device, MTLSize, NSUInteger}; use std::ffi::c_void; #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub enum GemmDType { BF16, F16, F32, } #[allow(clippy::too_many_arguments)] pub fn call_mlx_gemm( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, dtype: GemmDType, (b, m, n, k): (usize, usize, usize, usize), lhs_stride: &[usize], lhs_offset: usize, lhs_buffer: &Buffer, rhs_stride: &[usize], rhs_offset: usize, rhs_buffer: &Buffer, output: &Buffer, ) -> Result<(), MetalKernelError> { #[derive(Debug)] #[repr(C)] struct GemmParams { m: i32, n: i32, k: i32, lda: i32, ldb: i32, ldd: i32, tiles_n: i32, tiles_m: i32, batch_stride_a: isize, batch_stride_b: isize, batch_stride_d: isize, swizzle_log: i32, gemm_k_iterations_aligned: i32, batch_ndim: i32, } assert!(rhs_stride.len() >= 2); assert!(lhs_stride.len() >= 2); let rhs_m1 = rhs_stride[rhs_stride.len() - 1]; let rhs_m2 = rhs_stride[rhs_stride.len() - 2]; let lhs_m1 = lhs_stride[lhs_stride.len() - 1]; let lhs_m2 = lhs_stride[lhs_stride.len() - 2]; // lhs has shape b, m, k // We also allow for the case where the stride on the minor dimension is not as expected but // there is a single element. let (lda, a_trans) = if (lhs_m1 == 1 || k == 1) && (lhs_m2 == k || m == 1) { (k as i32, false) } else if (lhs_m1 == m || k == 1) && (lhs_m2 == 1 || m == 1) { (m as i32, true) } else { return Err(MetalKernelError::MatMulNonContiguous { lhs_stride: lhs_stride.to_vec(), rhs_stride: rhs_stride.to_vec(), mnk: (m, n, k), })?; }; // rhs has shape b, k, n let (ldb, b_trans) = if (rhs_m1 == 1 || n == 1) && (rhs_m2 == n || k == 1) { (n as i32, false) } else if (rhs_m1 == k || n == 1) && (rhs_m2 == 1 || k == 1) { (k as i32, true) } else { return Err(MetalKernelError::MatMulNonContiguous { lhs_stride: lhs_stride.to_vec(), rhs_stride: rhs_stride.to_vec(), mnk: (m, n, k), })?; }; let (bm, bn, bk, wn, wm) = (32, 32, 16, 2, 2); // https://github.com/ml-explore/mlx/blob/02efb310cac667bc547d1b96f21596c221f84fe7/mlx/backend/metal/matmul.cpp#L422 let constants = Some(ConstantValues::new(vec![ (10, Value::Bool(/* has_batch */ b > 1)), (100, Value::Bool(/* use_out_source */ false)), (110, Value::Bool(/* do_axpby */ false)), (200, Value::Bool(/* align_m */ m % bm == 0)), (201, Value::Bool(/* align_n */ n % bn == 0)), (202, Value::Bool(/* align_k */ k % bk == 0)), (300, Value::Bool(/* do_gather */ false)), ])); let swizzle_log = 0; let tile = 1 << swizzle_log; let tn = n.div_ceil(bn); let tm = m.div_ceil(bm); let tn = tn * tile; let tm = tm.div_ceil(tile); let batch_stride_a = if lhs_stride.len() > 2 { lhs_stride[lhs_stride.len() - 3] } else { m * k }; let batch_stride_b = if rhs_stride.len() > 2 { rhs_stride[rhs_stride.len() - 3] } else { n * k }; let gemm_params = GemmParams { m: m as i32, n: n as i32, k: k as i32, lda, ldb, ldd: n as i32, tiles_n: tn as i32, tiles_m: tm as i32, swizzle_log, batch_stride_a: batch_stride_a as isize, batch_stride_b: batch_stride_b as isize, batch_stride_d: (m * n) as isize, batch_ndim: 1i32, gemm_k_iterations_aligned: (k / bk) as i32, }; let batch_strides = [gemm_params.batch_stride_a, gemm_params.batch_stride_b]; // TODO(laurent): generate the name // template [[host_name("gemm_" #tname "_" #iname "_" #oname "_bm" #bm "_bn" #bn "_bk" #bk "_wm" #wm "_wn" #wn)]] let name = match (dtype, a_trans, b_trans) { (GemmDType::F32, false, false) => "gemm_nn_f32_f32_32_32_16_2_2", (GemmDType::F32, true, false) => "gemm_tn_f32_f32_32_32_16_2_2", (GemmDType::F32, false, true) => "gemm_nt_f32_f32_32_32_16_2_2", (GemmDType::F32, true, true) => "gemm_tt_f32_f32_32_32_16_2_2", (GemmDType::BF16, false, false) => "gemm_nn_bf16_bf16_32_32_16_2_2", (GemmDType::BF16, true, false) => "gemm_tn_bf16_bf16_32_32_16_2_2", (GemmDType::BF16, false, true) => "gemm_nt_bf16_bf16_32_32_16_2_2", (GemmDType::BF16, true, true) => "gemm_tt_bf16_bf16_32_32_16_2_2", (GemmDType::F16, false, false) => "gemm_nn_f16_f16_32_32_16_2_2", (GemmDType::F16, true, false) => "gemm_tn_f16_f16_32_32_16_2_2", (GemmDType::F16, false, true) => "gemm_nt_f16_f16_32_32_16_2_2", (GemmDType::F16, true, true) => "gemm_tt_f16_f16_32_32_16_2_2", }; let pipeline = kernels.load_pipeline_with_constants(device, Source::Gemm, name, constants)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); encoder.set_buffer(0, Some(lhs_buffer), lhs_offset as NSUInteger); encoder.set_buffer(1, Some(rhs_buffer), rhs_offset as NSUInteger); encoder.set_buffer(3, Some(output), 0); encoder.set_bytes( 4, std::mem::size_of::<GemmParams>() as u64, &gemm_params as *const GemmParams as *const c_void, ); encoder.set_bytes( 6, // batch_shape std::mem::size_of::<i32>() as u64, &(b as i32) as *const i32 as *const c_void, ); encoder.set_bytes( 7, (std::mem::size_of::<isize>() * batch_strides.len()) as u64, batch_strides.as_ptr() as *const c_void, ); let grid_size = MTLSize { width: tn as u64, height: tm as u64, depth: /* batch_size_out */ b as u64, }; let group_size = MTLSize { width: 32, height: wn, depth: wm, }; encoder.use_resource(lhs_buffer, metal::MTLResourceUsage::Read); encoder.use_resource(rhs_buffer, metal::MTLResourceUsage::Read); encoder.use_resource(output, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(grid_size, group_size); Ok(()) }
candle/candle-metal-kernels/src/mlx_gemm.rs/0
{ "file_path": "candle/candle-metal-kernels/src/mlx_gemm.rs", "repo_id": "candle", "token_count": 3374 }
49
use candle_metal_kernels::{call_unary_contiguous, call_unary_strided, unary, 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 = [ unary::contiguous::sin::FLOAT, unary::contiguous::cos::FLOAT, unary::contiguous::exp::FLOAT, unary::contiguous::sqr::FLOAT, unary::contiguous::sqrt::FLOAT, unary::contiguous::neg::FLOAT, unary::contiguous::copy::FLOAT, ]; let f32_skernels = [ unary::strided::sin::FLOAT, unary::strided::cos::FLOAT, unary::strided::exp::FLOAT, unary::strided::sqr::FLOAT, unary::strided::sqrt::FLOAT, unary::strided::neg::FLOAT, unary::strided::copy::FLOAT, ]; let f16_ckernels = [ unary::contiguous::sin::HALF, unary::contiguous::cos::HALF, unary::contiguous::exp::HALF, unary::contiguous::sqr::HALF, unary::contiguous::sqrt::HALF, unary::contiguous::neg::HALF, unary::contiguous::copy::HALF, ]; let f16_skernels = [ unary::strided::sin::HALF, unary::strided::cos::HALF, unary::strided::exp::HALF, unary::strided::sqr::HALF, unary::strided::sqrt::HALF, unary::strided::neg::HALF, unary::strided::copy::HALF, ]; let bf16_ckernels = [ unary::contiguous::sin::BFLOAT, unary::contiguous::cos::BFLOAT, unary::contiguous::exp::BFLOAT, unary::contiguous::sqr::BFLOAT, unary::contiguous::sqrt::BFLOAT, unary::contiguous::neg::BFLOAT, unary::contiguous::copy::BFLOAT, ]; let bf16_skernels = [ unary::strided::sin::BFLOAT, unary::strided::cos::BFLOAT, unary::strided::exp::BFLOAT, unary::strided::sqr::BFLOAT, unary::strided::sqrt::BFLOAT, unary::strided::neg::BFLOAT, unary::strided::copy::BFLOAT, ]; println!( "{0: <5} | {1: <19} | {2: <6} | {3: <5} | {4: <11} | {5: <11}", "dtype", "kernel", "size", "runs", "total time", "avg time" ); // f32 run_unary_bench(&device, &kernels, &f32_1k, f32_ckernels, f32_skernels); run_unary_bench(&device, &kernels, &f32_10k, f32_ckernels, f32_skernels); run_unary_bench(&device, &kernels, &f32_100k, f32_ckernels, f32_skernels); // f16 run_unary_bench(&device, &kernels, &f16_1k, f16_ckernels, f16_skernels); run_unary_bench(&device, &kernels, &f16_10k, f16_ckernels, f16_skernels); run_unary_bench(&device, &kernels, &f16_100k, f16_ckernels, f16_skernels); // bf16 run_unary_bench(&device, &kernels, &bf16_1k, bf16_ckernels, bf16_skernels); run_unary_bench(&device, &kernels, &bf16_10k, bf16_ckernels, bf16_skernels); run_unary_bench(&device, &kernels, &bf16_100k, bf16_ckernels, bf16_skernels); } fn run_unary_bench<T: Clone>( device: &Device, kernels: &Kernels, v: &[T], contiguous: [unary::contiguous::Kernel; 7], strided: [unary::strided::Kernel; 7], ) { let command_queue = device.new_command_queue(); let options = MTLResourceOptions::StorageModeManaged; let iterations = 10000; 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_unary_contiguous( device, &command_buffer, kernels, kernel_name, v.len(), &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.0, 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_unary_strided( device, command_buffer, &kernels, kernel_name, &shape, &input, &strides, offset, &mut output, 0, ) .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.0, v.len(), iterations, total_time, total_time / iterations ); } }
candle/candle-metal-kernels/tmp/unary.rs/0
{ "file_path": "candle/candle-metal-kernels/tmp/unary.rs", "repo_id": "candle", "token_count": 3489 }
50
//! Group Normalization. //! //! This layer applies Group Normalization over a mini-batch of inputs. use candle::{DType, Result, Tensor}; // This group norm version handles both weight and bias so removes the mean. #[derive(Clone, Debug)] pub struct GroupNorm { weight: Tensor, bias: Tensor, eps: f64, num_channels: usize, num_groups: usize, } impl GroupNorm { pub fn new( weight: Tensor, bias: Tensor, num_channels: usize, num_groups: usize, eps: f64, ) -> Result<Self> { if num_channels % num_groups != 0 { candle::bail!( "GroupNorm: num_groups ({num_groups}) must divide num_channels ({num_channels})" ) } Ok(Self { weight, bias, eps, num_channels, num_groups, }) } } impl crate::Module for GroupNorm { fn forward(&self, x: &Tensor) -> Result<Tensor> { let x_shape = x.dims(); if x_shape.len() <= 2 { candle::bail!("input rank for GroupNorm should be at least 3"); } let (b_sz, n_channels) = (x_shape[0], x_shape[1]); let hidden_size = x_shape[2..].iter().product::<usize>() * n_channels / self.num_groups; if n_channels != self.num_channels { candle::bail!( "unexpected num-channels in GroupNorm ({n_channels} <> {}", self.num_channels ) } let x_dtype = x.dtype(); let internal_dtype = match x_dtype { DType::F16 | DType::BF16 => DType::F32, d => d, }; let x = x.reshape((b_sz, self.num_groups, hidden_size))?; let x = x.to_dtype(internal_dtype)?; let mean_x = (x.sum_keepdim(2)? / hidden_size as f64)?; let x = x.broadcast_sub(&mean_x)?; let norm_x = (x.sqr()?.sum_keepdim(2)? / hidden_size as f64)?; let x_normed = x.broadcast_div(&(norm_x + self.eps)?.sqrt()?)?; let mut w_dims = vec![1; x_shape.len()]; w_dims[1] = n_channels; let weight = self.weight.reshape(w_dims.clone())?; let bias = self.bias.reshape(w_dims)?; x_normed .to_dtype(x_dtype)? .reshape(x_shape)? .broadcast_mul(&weight)? .broadcast_add(&bias) } } pub fn group_norm( num_groups: usize, num_channels: usize, eps: f64, vb: crate::VarBuilder, ) -> Result<GroupNorm> { let weight = vb.get_with_hints(num_channels, "weight", crate::Init::Const(1.))?; let bias = vb.get_with_hints(num_channels, "bias", crate::Init::Const(0.))?; GroupNorm::new(weight, bias, num_channels, num_groups, eps) }
candle/candle-nn/src/group_norm.rs/0
{ "file_path": "candle/candle-nn/src/group_norm.rs", "repo_id": "candle", "token_count": 1372 }
51
/* Equivalent PyTorch code. import torch from torch.nn.functional import group_norm t = torch.tensor( [[[-0.3034, 0.2726, -0.9659], [-1.1845, -1.3236, 0.0172], [ 1.9507, 1.2554, -0.8625], [ 1.0682, 0.3604, 0.3985], [-0.4957, -0.4461, -0.9721], [ 1.5157, -0.1546, -0.5596]], [[-1.6698, -0.4040, -0.7927], [ 0.3736, -0.0975, -0.1351], [-0.9461, 0.5461, -0.6334], [-1.0919, -0.1158, 0.1213], [-0.9535, 0.1281, 0.4372], [-0.2845, 0.3488, 0.5641]]]) print(group_norm(t, num_groups=2)) print(group_norm(t, num_groups=3)) */ #[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; use anyhow::Result; use candle::test_utils::to_vec3_round; use candle::{Device, Tensor}; use candle_nn::{GroupNorm, Module}; #[test] fn group_norm() -> Result<()> { let device = &Device::Cpu; let w = Tensor::from_vec(vec![1f32; 6], 6, device)?; let b = Tensor::from_vec(vec![0f32; 6], 6, device)?; let gn2 = GroupNorm::new(w.clone(), b.clone(), 6, 2, 1e-5)?; let gn3 = GroupNorm::new(w, b, 6, 3, 1e-5)?; let input = Tensor::new( &[ [ [-0.3034f32, 0.2726, -0.9659], [-1.1845, -1.3236, 0.0172], [1.9507, 1.2554, -0.8625], [1.0682, 0.3604, 0.3985], [-0.4957, -0.4461, -0.9721], [1.5157, -0.1546, -0.5596], ], [ [-1.6698, -0.4040, -0.7927], [0.3736, -0.0975, -0.1351], [-0.9461, 0.5461, -0.6334], [-1.0919, -0.1158, 0.1213], [-0.9535, 0.1281, 0.4372], [-0.2845, 0.3488, 0.5641], ], ], device, )?; assert_eq!( to_vec3_round(&gn2.forward(&input)?, 4)?, &[ [ [-0.1653, 0.3748, -0.7866], [-0.9916, -1.1220, 0.1353], [1.9485, 1.2965, -0.6896], [1.2769, 0.3628, 0.4120], [-0.7427, -0.6786, -1.3578], [1.8547, -0.3022, -0.8252] ], [ [-1.9342, 0.0211, -0.5793], [1.2223, 0.4945, 0.4365], [-0.8163, 1.4887, -0.3333], [-1.7960, -0.0392, 0.3875], [-1.5469, 0.3998, 0.9561], [-0.3428, 0.7970, 1.1845] ] ] ); assert_eq!( to_vec3_round(&gn3.forward(&input)?, 4)?, &[ [ [0.4560, 1.4014, -0.6313], [-0.9901, -1.2184, 0.9822], [1.4254, 0.6360, -1.7682], [0.4235, -0.3800, -0.3367], [-0.3890, -0.3268, -0.9862], [2.1325, 0.0386, -0.4691] ], [ [-1.8797, 0.0777, -0.5234], [1.2802, 0.5517, 0.4935], [-1.0102, 1.5327, -0.4773], [-1.2587, 0.4047, 0.8088], [-1.9074, 0.1691, 0.7625], [-0.6230, 0.5928, 1.0061] ] ] ); Ok(()) }
candle/candle-nn/tests/group_norm.rs/0
{ "file_path": "candle/candle-nn/tests/group_norm.rs", "repo_id": "candle", "token_count": 2154 }
52
import math from typing import Any import candle from candle import Tensor from .module import Module # See https://github.com/pytorch/pytorch/blob/main/torch/nn/modules/linear.py class Identity(Module): r"""A placeholder identity operator that is argument-insensitive. Args: args: any argument (unused) kwargs: any keyword argument (unused) Shape: - Input: :math:`(*)`, where :math:`*` means any number of dimensions. - Output: :math:`(*)`, same shape as the input. Examples:: >>> m = nn.Identity(54, unused_argument1=0.1, unused_argument2=False) >>> input = candle.randn(128, 20) >>> output = m(input) >>> print(output.shape) """ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__() def forward(self, input: Tensor) -> Tensor: return input class Linear(Module): r"""Applies a linear transformation to the incoming data: :math:`y = xA^T + b` Args: in_features: size of each input sample out_features: size of each output sample bias: If set to ``False``, the layer will not learn an additive bias. Default: ``True`` Shape: - Input: :math:`(*, H_{in})` where :math:`*` means any number of dimensions including none and :math:`H_{in} = \text{in\_features}`. - Output: :math:`(*, H_{out})` where all but the last dimension are the same shape as the input and :math:`H_{out} = \text{out\_features}`. Attributes: weight: the learnable weights of the module of shape :math:`(\text{out\_features}, \text{in\_features})`. The values are initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})`, where :math:`k = \frac{1}{\text{in\_features}}` bias: the learnable bias of the module of shape :math:`(\text{out\_features})`. If :attr:`bias` is ``True``, the values are initialized from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where :math:`k = \frac{1}{\text{in\_features}}` """ __constants__ = ["in_features", "out_features"] in_features: int out_features: int weight: Tensor def __init__( self, in_features: int, out_features: int, bias: bool = True, device=None, dtype=None, ) -> None: factory_kwargs = {"device": device, "dtype": dtype} super().__init__() # Allow 'weight' to be quantized self._quantizable_buffers.add("weight") self.in_features = in_features self.out_features = out_features # TODO: Do actual initialization here: e.g. kaiming_uniform or xavier_uniform self.weight = candle.ones((out_features, in_features), **factory_kwargs) if bias: self.bias = candle.zeros((out_features,), **factory_kwargs) else: self.bias = None def forward(self, x: Tensor) -> Tensor: dims = x.shape last_dim = dims[-1] if isinstance(self.weight, candle.QTensor): if len(dims) < 3: matmul_result = self.weight.matmul_t(x).broadcast_add(self.bias) elif len(dims) == 3: b, n, m = dims output_shape = (b, n, self.out_features) re = x.reshape((b * n, m)) matmul_result = self.weight.matmul_t(re).reshape((output_shape)) else: raise NotImplementedError("'QTensor.matmul_t' is not implemented for more than 3 dimensions") if self.bias: return matmul_result.broadcast_add(self.bias) else: if self.weight.shape[-1] == last_dim and len(dims) < 3: w = self.weight.t() else: batch_size = dims[0] w = self.weight.broadcast_left((batch_size,)).t() x = x.matmul(w) if self.bias is not None: x = x.broadcast_add(self.bias) return x def extra_repr(self) -> str: return f"in_features={self.in_features}, out_features={self.out_features}, bias={self.bias is not None}"
candle/candle-pyo3/py_src/candle/nn/linear.py/0
{ "file_path": "candle/candle-pyo3/py_src/candle/nn/linear.py", "repo_id": "candle", "token_count": 1947 }
53
# See: https://raw.githubusercontent.com/huggingface/tokenizers/main/bindings/python/stub.py import argparse import inspect import os from typing import Optional import black from pathlib import Path import re INDENT = " " * 4 GENERATED_COMMENT = "# Generated content DO NOT EDIT\n" TYPING = """from typing import Any, Callable, Dict, List, Optional, Tuple, Union, Sequence from os import PathLike """ CANDLE_SPECIFIC_TYPING = "from candle.typing import _ArrayLike, Device, Scalar, Index, Shape\n" CANDLE_TENSOR_IMPORTS = "from candle import Tensor,DType,QTensor\n" RETURN_TYPE_MARKER = "&RETURNS&: " ADDITIONAL_TYPEHINTS = {} FORWARD_REF_PATTERN = re.compile(r"ForwardRef\('([^']+)'\)") def do_indent(text: Optional[str], indent: str): if text is None: return "" return text.replace("\n", f"\n{indent}") def function(obj, indent: str, text_signature: str = None): if text_signature is None: text_signature = obj.__text_signature__ text_signature = text_signature.replace("$self", "self").lstrip().rstrip() doc_string = obj.__doc__ if doc_string is None: doc_string = "" # Check if we have a return type annotation in the docstring return_type = None doc_lines = doc_string.split("\n") if doc_lines[-1].lstrip().startswith(RETURN_TYPE_MARKER): # Extract the return type and remove it from the docstring return_type = doc_lines[-1].lstrip()[len(RETURN_TYPE_MARKER) :].strip() doc_string = "\n".join(doc_lines[:-1]) string = "" if return_type: string += f"{indent}def {obj.__name__}{text_signature} -> {return_type}:\n" else: string += f"{indent}def {obj.__name__}{text_signature}:\n" indent += INDENT string += f'{indent}"""\n' string += f"{indent}{do_indent(doc_string, indent)}\n" string += f'{indent}"""\n' string += f"{indent}pass\n" string += "\n" string += "\n" return string def member_sort(member): if inspect.isclass(member): value = 10 + len(inspect.getmro(member)) else: value = 1 return value def fn_predicate(obj): value = inspect.ismethoddescriptor(obj) or inspect.isbuiltin(obj) if value: return obj.__text_signature__ and not obj.__name__.startswith("_") if inspect.isgetsetdescriptor(obj): return not obj.__name__.startswith("_") return False def get_module_members(module): members = [ member for name, member in inspect.getmembers(module) if not name.startswith("_") and not inspect.ismodule(member) ] members.sort(key=member_sort) return members def pyi_file(obj, indent=""): string = "" if inspect.ismodule(obj): string += GENERATED_COMMENT string += TYPING string += CANDLE_SPECIFIC_TYPING if obj.__name__ != "candle.candle": string += CANDLE_TENSOR_IMPORTS members = get_module_members(obj) for member in members: string += pyi_file(member, indent) elif inspect.isclass(obj): indent += INDENT mro = inspect.getmro(obj) if len(mro) > 2: inherit = f"({mro[1].__name__})" else: inherit = "" string += f"class {obj.__name__}{inherit}:\n" body = "" if obj.__doc__: body += f'{indent}"""\n{indent}{do_indent(obj.__doc__, indent)}\n{indent}"""\n' fns = inspect.getmembers(obj, fn_predicate) # Init if obj.__text_signature__: body += f"{indent}def __init__{obj.__text_signature__}:\n" body += f"{indent+INDENT}pass\n" body += "\n" if obj.__name__ in ADDITIONAL_TYPEHINTS: additional_members = inspect.getmembers(ADDITIONAL_TYPEHINTS[obj.__name__]) additional_functions = [] for name, member in additional_members: if inspect.isfunction(member): additional_functions.append((name, member)) def process_additional_function(fn): signature = inspect.signature(fn) cleaned_signature = re.sub(FORWARD_REF_PATTERN, r"\1", str(signature)) string = f"{indent}def {fn.__name__}{cleaned_signature}:\n" string += ( f'{indent+INDENT}"""{indent+INDENT}{do_indent(fn.__doc__, indent+INDENT)}{indent+INDENT}"""\n' ) string += f"{indent+INDENT}pass\n" string += "\n" return string for name, fn in additional_functions: body += process_additional_function(fn) for name, fn in fns: body += pyi_file(fn, indent=indent) if not body: body += f"{indent}pass\n" string += body string += "\n\n" elif inspect.isbuiltin(obj): string += f"{indent}@staticmethod\n" string += function(obj, indent) elif inspect.ismethoddescriptor(obj): string += function(obj, indent) elif inspect.isgetsetdescriptor(obj): # TODO it would be interesting to add the setter maybe ? string += f"{indent}@property\n" string += function(obj, indent, text_signature="(self)") elif obj.__class__.__name__ == "DType": string += f"class {str(obj).lower()}(DType):\n" string += f"{indent+INDENT}pass\n" else: raise Exception(f"Object {obj} is not supported") return string def py_file(module, origin): members = get_module_members(module) string = GENERATED_COMMENT string += f"from .. import {origin}\n" string += "\n" for member in members: if hasattr(member, "__name__"): name = member.__name__ else: name = str(member) string += f"{name} = {origin}.{name}\n" return string def do_black(content, is_pyi): mode = black.Mode( target_versions={black.TargetVersion.PY35}, line_length=119, is_pyi=is_pyi, string_normalization=True, ) try: return black.format_file_contents(content, fast=True, mode=mode) except black.NothingChanged: return content def write(module, directory, origin, check=False): submodules = [(name, member) for name, member in inspect.getmembers(module) if inspect.ismodule(member)] filename = os.path.join(directory, "__init__.pyi") pyi_content = pyi_file(module) pyi_content = do_black(pyi_content, is_pyi=True) os.makedirs(directory, exist_ok=True) if check: with open(filename, "r") as f: data = f.read() print("generated content") print(pyi_content) assert data == pyi_content, f"The content of {filename} seems outdated, please run `python stub.py`" else: with open(filename, "w") as f: f.write(pyi_content) filename = os.path.join(directory, "__init__.py") py_content = py_file(module, origin) py_content = do_black(py_content, is_pyi=False) os.makedirs(directory, exist_ok=True) is_auto = False if not os.path.exists(filename): is_auto = True else: with open(filename, "r") as f: line = f.readline() if line == GENERATED_COMMENT: is_auto = True if is_auto: if check: with open(filename, "r") as f: data = f.read() print("generated content") print(py_content) assert data == py_content, f"The content of {filename} seems outdated, please run `python stub.py`" else: with open(filename, "w") as f: f.write(py_content) for name, submodule in submodules: write(submodule, os.path.join(directory, name), f"{name}", check=check) def extract_additional_types(module): additional_types = {} for name, member in inspect.getmembers(module): if inspect.isclass(member): if hasattr(member, "__name__"): name = member.__name__ else: name = str(member) if name not in additional_types: additional_types[name] = member return additional_types if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--check", action="store_true") args = parser.parse_args() # Enable execution from the candle and candle-pyo3 directories cwd = Path.cwd() directory = "py_src/candle/" if cwd.name != "candle-pyo3": directory = f"candle-pyo3/{directory}" import candle import _additional_typing ADDITIONAL_TYPEHINTS = extract_additional_types(_additional_typing) write(candle.candle, directory, "candle", check=args.check)
candle/candle-pyo3/stub.py/0
{ "file_path": "candle/candle-pyo3/stub.py", "repo_id": "candle", "token_count": 3931 }
54
//! BERT (Bidirectional Encoder Representations from Transformers) //! //! Bert is a general large language model that can be used for various language tasks: //! - Compute sentence embeddings for a prompt. //! - Compute similarities between a set of sentences. //! - [Arxiv](https://arxiv.org/abs/1810.04805) "BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding" //! - Upstream [Github repo](https://github.com/google-research/bert). //! - See bert in [candle-examples](https://github.com/huggingface/candle/tree/main/candle-examples/) for runnable code //! use super::with_tracing::{layer_norm, linear, LayerNorm, Linear}; use candle::{DType, Device, Result, Tensor}; use candle_nn::{embedding, Embedding, Module, VarBuilder}; use serde::Deserialize; pub const DTYPE: DType = DType::F32; #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] #[serde(rename_all = "lowercase")] pub enum HiddenAct { Gelu, GeluApproximate, Relu, } #[derive(Clone)] struct HiddenActLayer { act: HiddenAct, span: tracing::Span, } impl HiddenActLayer { fn new(act: HiddenAct) -> Self { let span = tracing::span!(tracing::Level::TRACE, "hidden-act"); Self { act, span } } fn forward(&self, xs: &Tensor) -> candle::Result<Tensor> { let _enter = self.span.enter(); match self.act { // https://github.com/huggingface/transformers/blob/cd4584e3c809bb9e1392ccd3fe38b40daba5519a/src/transformers/activations.py#L213 HiddenAct::Gelu => xs.gelu_erf(), HiddenAct::GeluApproximate => xs.gelu(), HiddenAct::Relu => xs.relu(), } } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Default)] #[serde(rename_all = "lowercase")] pub enum PositionEmbeddingType { #[default] Absolute, } // https://github.com/huggingface/transformers/blob/6eedfa6dd15dc1e22a55ae036f681914e5a0d9a1/src/transformers/models/bert/configuration_bert.py#L1 #[derive(Debug, Clone, PartialEq, Deserialize)] pub struct Config { pub vocab_size: usize, pub hidden_size: usize, pub num_hidden_layers: usize, pub num_attention_heads: usize, pub intermediate_size: usize, pub hidden_act: HiddenAct, pub hidden_dropout_prob: f64, pub max_position_embeddings: usize, pub type_vocab_size: usize, pub initializer_range: f64, pub layer_norm_eps: f64, pub pad_token_id: usize, #[serde(default)] pub position_embedding_type: PositionEmbeddingType, #[serde(default)] pub use_cache: bool, pub classifier_dropout: Option<f64>, pub model_type: Option<String>, } impl Default for Config { fn default() -> Self { Self { vocab_size: 30522, hidden_size: 768, num_hidden_layers: 12, num_attention_heads: 12, intermediate_size: 3072, hidden_act: HiddenAct::Gelu, hidden_dropout_prob: 0.1, max_position_embeddings: 512, type_vocab_size: 2, initializer_range: 0.02, layer_norm_eps: 1e-12, pad_token_id: 0, position_embedding_type: PositionEmbeddingType::Absolute, use_cache: true, classifier_dropout: None, model_type: Some("bert".to_string()), } } } impl Config { fn _all_mini_lm_l6_v2() -> Self { // https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2/blob/main/config.json Self { vocab_size: 30522, hidden_size: 384, num_hidden_layers: 6, num_attention_heads: 12, intermediate_size: 1536, hidden_act: HiddenAct::Gelu, hidden_dropout_prob: 0.1, max_position_embeddings: 512, type_vocab_size: 2, initializer_range: 0.02, layer_norm_eps: 1e-12, pad_token_id: 0, position_embedding_type: PositionEmbeddingType::Absolute, use_cache: true, classifier_dropout: None, model_type: Some("bert".to_string()), } } } #[derive(Clone)] struct Dropout { #[allow(dead_code)] pr: f64, } impl Dropout { fn new(pr: f64) -> Self { Self { pr } } } impl Module for Dropout { fn forward(&self, x: &Tensor) -> Result<Tensor> { // TODO Ok(x.clone()) } } // https://github.com/huggingface/transformers/blob/6eedfa6dd15dc1e22a55ae036f681914e5a0d9a1/src/transformers/models/bert/modeling_bert.py#L180 struct BertEmbeddings { word_embeddings: Embedding, position_embeddings: Option<Embedding>, token_type_embeddings: Embedding, layer_norm: LayerNorm, dropout: Dropout, span: tracing::Span, } impl BertEmbeddings { fn load(vb: VarBuilder, config: &Config) -> Result<Self> { let word_embeddings = embedding( config.vocab_size, config.hidden_size, vb.pp("word_embeddings"), )?; let position_embeddings = embedding( config.max_position_embeddings, config.hidden_size, vb.pp("position_embeddings"), )?; let token_type_embeddings = embedding( config.type_vocab_size, config.hidden_size, vb.pp("token_type_embeddings"), )?; let layer_norm = layer_norm( config.hidden_size, config.layer_norm_eps, vb.pp("LayerNorm"), )?; Ok(Self { word_embeddings, position_embeddings: Some(position_embeddings), token_type_embeddings, layer_norm, dropout: Dropout::new(config.hidden_dropout_prob), span: tracing::span!(tracing::Level::TRACE, "embeddings"), }) } fn forward(&self, input_ids: &Tensor, token_type_ids: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let (_bsize, seq_len) = input_ids.dims2()?; let input_embeddings = self.word_embeddings.forward(input_ids)?; let token_type_embeddings = self.token_type_embeddings.forward(token_type_ids)?; let mut embeddings = (&input_embeddings + token_type_embeddings)?; if let Some(position_embeddings) = &self.position_embeddings { // TODO: Proper absolute positions? let position_ids = (0..seq_len as u32).collect::<Vec<_>>(); let position_ids = Tensor::new(&position_ids[..], input_ids.device())?; embeddings = embeddings.broadcast_add(&position_embeddings.forward(&position_ids)?)? } let embeddings = self.layer_norm.forward(&embeddings)?; let embeddings = self.dropout.forward(&embeddings)?; Ok(embeddings) } } #[derive(Clone)] struct BertSelfAttention { query: Linear, key: Linear, value: Linear, dropout: Dropout, num_attention_heads: usize, attention_head_size: usize, span: tracing::Span, span_softmax: tracing::Span, } impl BertSelfAttention { fn load(vb: VarBuilder, config: &Config) -> Result<Self> { let attention_head_size = config.hidden_size / config.num_attention_heads; let all_head_size = config.num_attention_heads * attention_head_size; let dropout = Dropout::new(config.hidden_dropout_prob); let hidden_size = config.hidden_size; let query = linear(hidden_size, all_head_size, vb.pp("query"))?; let value = linear(hidden_size, all_head_size, vb.pp("value"))?; let key = linear(hidden_size, all_head_size, vb.pp("key"))?; Ok(Self { query, key, value, dropout, num_attention_heads: config.num_attention_heads, attention_head_size, span: tracing::span!(tracing::Level::TRACE, "self-attn"), span_softmax: tracing::span!(tracing::Level::TRACE, "softmax"), }) } fn transpose_for_scores(&self, xs: &Tensor) -> Result<Tensor> { let mut new_x_shape = xs.dims().to_vec(); new_x_shape.pop(); new_x_shape.push(self.num_attention_heads); new_x_shape.push(self.attention_head_size); let xs = xs.reshape(new_x_shape.as_slice())?.transpose(1, 2)?; xs.contiguous() } fn forward(&self, hidden_states: &Tensor, attention_mask: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let query_layer = self.query.forward(hidden_states)?; let key_layer = self.key.forward(hidden_states)?; let value_layer = self.value.forward(hidden_states)?; let query_layer = self.transpose_for_scores(&query_layer)?; let key_layer = self.transpose_for_scores(&key_layer)?; let value_layer = self.transpose_for_scores(&value_layer)?; let attention_scores = query_layer.matmul(&key_layer.t()?)?; let attention_scores = (attention_scores / (self.attention_head_size as f64).sqrt())?; let attention_scores = attention_scores.broadcast_add(attention_mask)?; let attention_probs = { let _enter_sm = self.span_softmax.enter(); candle_nn::ops::softmax(&attention_scores, candle::D::Minus1)? }; let attention_probs = self.dropout.forward(&attention_probs)?; let context_layer = attention_probs.matmul(&value_layer)?; let context_layer = context_layer.transpose(1, 2)?.contiguous()?; let context_layer = context_layer.flatten_from(candle::D::Minus2)?; Ok(context_layer) } } #[derive(Clone)] struct BertSelfOutput { dense: Linear, layer_norm: LayerNorm, dropout: Dropout, span: tracing::Span, } impl BertSelfOutput { fn load(vb: VarBuilder, config: &Config) -> Result<Self> { let dense = linear(config.hidden_size, config.hidden_size, vb.pp("dense"))?; let layer_norm = layer_norm( config.hidden_size, config.layer_norm_eps, vb.pp("LayerNorm"), )?; let dropout = Dropout::new(config.hidden_dropout_prob); Ok(Self { dense, layer_norm, dropout, span: tracing::span!(tracing::Level::TRACE, "self-out"), }) } fn forward(&self, hidden_states: &Tensor, input_tensor: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let hidden_states = self.dense.forward(hidden_states)?; let hidden_states = self.dropout.forward(&hidden_states)?; self.layer_norm.forward(&(hidden_states + input_tensor)?) } } // https://github.com/huggingface/transformers/blob/6eedfa6dd15dc1e22a55ae036f681914e5a0d9a1/src/transformers/models/bert/modeling_bert.py#L392 #[derive(Clone)] struct BertAttention { self_attention: BertSelfAttention, self_output: BertSelfOutput, span: tracing::Span, } impl BertAttention { fn load(vb: VarBuilder, config: &Config) -> Result<Self> { let self_attention = BertSelfAttention::load(vb.pp("self"), config)?; let self_output = BertSelfOutput::load(vb.pp("output"), config)?; Ok(Self { self_attention, self_output, span: tracing::span!(tracing::Level::TRACE, "attn"), }) } fn forward(&self, hidden_states: &Tensor, attention_mask: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let self_outputs = self.self_attention.forward(hidden_states, attention_mask)?; let attention_output = self.self_output.forward(&self_outputs, hidden_states)?; Ok(attention_output) } } // https://github.com/huggingface/transformers/blob/6eedfa6dd15dc1e22a55ae036f681914e5a0d9a1/src/transformers/models/bert/modeling_bert.py#L441 #[derive(Clone)] struct BertIntermediate { dense: Linear, intermediate_act: HiddenActLayer, span: tracing::Span, } impl BertIntermediate { fn load(vb: VarBuilder, config: &Config) -> Result<Self> { let dense = linear(config.hidden_size, config.intermediate_size, vb.pp("dense"))?; Ok(Self { dense, intermediate_act: HiddenActLayer::new(config.hidden_act), span: tracing::span!(tracing::Level::TRACE, "inter"), }) } } impl Module for BertIntermediate { fn forward(&self, hidden_states: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let hidden_states = self.dense.forward(hidden_states)?; let ys = self.intermediate_act.forward(&hidden_states)?; Ok(ys) } } // https://github.com/huggingface/transformers/blob/6eedfa6dd15dc1e22a55ae036f681914e5a0d9a1/src/transformers/models/bert/modeling_bert.py#L456 #[derive(Clone)] struct BertOutput { dense: Linear, layer_norm: LayerNorm, dropout: Dropout, span: tracing::Span, } impl BertOutput { fn load(vb: VarBuilder, config: &Config) -> Result<Self> { let dense = linear(config.intermediate_size, config.hidden_size, vb.pp("dense"))?; let layer_norm = layer_norm( config.hidden_size, config.layer_norm_eps, vb.pp("LayerNorm"), )?; let dropout = Dropout::new(config.hidden_dropout_prob); Ok(Self { dense, layer_norm, dropout, span: tracing::span!(tracing::Level::TRACE, "out"), }) } fn forward(&self, hidden_states: &Tensor, input_tensor: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let hidden_states = self.dense.forward(hidden_states)?; let hidden_states = self.dropout.forward(&hidden_states)?; self.layer_norm.forward(&(hidden_states + input_tensor)?) } } // https://github.com/huggingface/transformers/blob/6eedfa6dd15dc1e22a55ae036f681914e5a0d9a1/src/transformers/models/bert/modeling_bert.py#L470 #[derive(Clone)] pub struct BertLayer { attention: BertAttention, intermediate: BertIntermediate, output: BertOutput, span: tracing::Span, } impl BertLayer { fn load(vb: VarBuilder, config: &Config) -> Result<Self> { let attention = BertAttention::load(vb.pp("attention"), config)?; let intermediate = BertIntermediate::load(vb.pp("intermediate"), config)?; let output = BertOutput::load(vb.pp("output"), config)?; Ok(Self { attention, intermediate, output, span: tracing::span!(tracing::Level::TRACE, "layer"), }) } fn forward(&self, hidden_states: &Tensor, attention_mask: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let attention_output = self.attention.forward(hidden_states, attention_mask)?; // TODO: Support cross-attention? // https://github.com/huggingface/transformers/blob/6eedfa6dd15dc1e22a55ae036f681914e5a0d9a1/src/transformers/models/bert/modeling_bert.py#L523 // TODO: Support something similar to `apply_chunking_to_forward`? let intermediate_output = self.intermediate.forward(&attention_output)?; let layer_output = self .output .forward(&intermediate_output, &attention_output)?; Ok(layer_output) } } // https://github.com/huggingface/transformers/blob/6eedfa6dd15dc1e22a55ae036f681914e5a0d9a1/src/transformers/models/bert/modeling_bert.py#L556 #[derive(Clone)] pub struct BertEncoder { pub layers: Vec<BertLayer>, span: tracing::Span, } impl BertEncoder { pub fn load(vb: VarBuilder, config: &Config) -> Result<Self> { let layers = (0..config.num_hidden_layers) .map(|index| BertLayer::load(vb.pp(format!("layer.{index}")), config)) .collect::<Result<Vec<_>>>()?; let span = tracing::span!(tracing::Level::TRACE, "encoder"); Ok(BertEncoder { layers, span }) } pub fn forward(&self, hidden_states: &Tensor, attention_mask: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let mut hidden_states = hidden_states.clone(); // Use a loop rather than a fold as it's easier to modify when adding debug/... for layer in self.layers.iter() { hidden_states = layer.forward(&hidden_states, attention_mask)? } Ok(hidden_states) } } // https://github.com/huggingface/transformers/blob/6eedfa6dd15dc1e22a55ae036f681914e5a0d9a1/src/transformers/models/bert/modeling_bert.py#L874 pub struct BertModel { embeddings: BertEmbeddings, encoder: BertEncoder, pub device: Device, span: tracing::Span, } impl BertModel { pub fn load(vb: VarBuilder, config: &Config) -> Result<Self> { let (embeddings, encoder) = match ( BertEmbeddings::load(vb.pp("embeddings"), config), BertEncoder::load(vb.pp("encoder"), config), ) { (Ok(embeddings), Ok(encoder)) => (embeddings, encoder), (Err(err), _) | (_, Err(err)) => { if let Some(model_type) = &config.model_type { if let (Ok(embeddings), Ok(encoder)) = ( BertEmbeddings::load(vb.pp(format!("{model_type}.embeddings")), config), BertEncoder::load(vb.pp(format!("{model_type}.encoder")), config), ) { (embeddings, encoder) } else { return Err(err); } } else { return Err(err); } } }; Ok(Self { embeddings, encoder, device: vb.device().clone(), span: tracing::span!(tracing::Level::TRACE, "model"), }) } pub fn forward( &self, input_ids: &Tensor, token_type_ids: &Tensor, attention_mask: Option<&Tensor>, ) -> Result<Tensor> { let _enter = self.span.enter(); let embedding_output = self.embeddings.forward(input_ids, token_type_ids)?; let attention_mask = match attention_mask { Some(attention_mask) => attention_mask.clone(), None => input_ids.ones_like()?, }; let dtype = embedding_output.dtype(); // https://github.com/huggingface/transformers/blob/6eedfa6dd15dc1e22a55ae036f681914e5a0d9a1/src/transformers/models/bert/modeling_bert.py#L995 let attention_mask = get_extended_attention_mask(&attention_mask, dtype)?; let sequence_output = self.encoder.forward(&embedding_output, &attention_mask)?; Ok(sequence_output) } } fn get_extended_attention_mask(attention_mask: &Tensor, dtype: DType) -> Result<Tensor> { let attention_mask = match attention_mask.rank() { 3 => attention_mask.unsqueeze(1)?, 2 => attention_mask.unsqueeze(1)?.unsqueeze(1)?, _ => candle::bail!("Wrong shape for input_ids or attention_mask"), }; let attention_mask = attention_mask.to_dtype(dtype)?; // torch.finfo(dtype).min (attention_mask.ones_like()? - &attention_mask)?.broadcast_mul( &Tensor::try_from(f32::MIN)? .to_device(attention_mask.device())? .to_dtype(dtype)?, ) } //https://github.com/huggingface/transformers/blob/1bd604d11c405dfb8b78bda4062d88fc75c17de0/src/transformers/models/bert/modeling_bert.py#L752-L766 struct BertPredictionHeadTransform { dense: Linear, activation: HiddenActLayer, layer_norm: LayerNorm, } impl BertPredictionHeadTransform { fn load(vb: VarBuilder, config: &Config) -> Result<Self> { let dense = linear(config.hidden_size, config.hidden_size, vb.pp("dense"))?; let activation = HiddenActLayer::new(config.hidden_act); let layer_norm = layer_norm( config.hidden_size, config.layer_norm_eps, vb.pp("LayerNorm"), )?; Ok(Self { dense, activation, layer_norm, }) } } impl Module for BertPredictionHeadTransform { fn forward(&self, hidden_states: &Tensor) -> Result<Tensor> { let hidden_states = self .activation .forward(&self.dense.forward(hidden_states)?)?; self.layer_norm.forward(&hidden_states) } } // https://github.com/huggingface/transformers/blob/1bd604d11c405dfb8b78bda4062d88fc75c17de0/src/transformers/models/bert/modeling_bert.py#L769C1-L790C1 pub struct BertLMPredictionHead { transform: BertPredictionHeadTransform, decoder: Linear, } impl BertLMPredictionHead { pub fn load(vb: VarBuilder, config: &Config) -> Result<Self> { let transform = BertPredictionHeadTransform::load(vb.pp("transform"), config)?; let decoder = linear(config.hidden_size, config.vocab_size, vb.pp("decoder"))?; Ok(Self { transform, decoder }) } } impl Module for BertLMPredictionHead { fn forward(&self, hidden_states: &Tensor) -> Result<Tensor> { self.decoder .forward(&self.transform.forward(hidden_states)?) } } // https://github.com/huggingface/transformers/blob/1bd604d11c405dfb8b78bda4062d88fc75c17de0/src/transformers/models/bert/modeling_bert.py#L792 pub struct BertOnlyMLMHead { predictions: BertLMPredictionHead, } impl BertOnlyMLMHead { pub fn load(vb: VarBuilder, config: &Config) -> Result<Self> { let predictions = BertLMPredictionHead::load(vb.pp("predictions"), config)?; Ok(Self { predictions }) } } impl Module for BertOnlyMLMHead { fn forward(&self, sequence_output: &Tensor) -> Result<Tensor> { self.predictions.forward(sequence_output) } } pub struct BertForMaskedLM { bert: BertModel, cls: BertOnlyMLMHead, } impl BertForMaskedLM { pub fn load(vb: VarBuilder, config: &Config) -> Result<Self> { let bert = BertModel::load(vb.pp("bert"), config)?; let cls = BertOnlyMLMHead::load(vb.pp("cls"), config)?; Ok(Self { bert, cls }) } pub fn forward( &self, input_ids: &Tensor, token_type_ids: &Tensor, attention_mask: Option<&Tensor>, ) -> Result<Tensor> { let sequence_output = self .bert .forward(input_ids, token_type_ids, attention_mask)?; self.cls.forward(&sequence_output) } }
candle/candle-transformers/src/models/bert.rs/0
{ "file_path": "candle/candle-transformers/src/models/bert.rs", "repo_id": "candle", "token_count": 10113 }
55
//! Implementation of the Descript Audio Codec (DAC) model //! //! See: [Descript Audio Codec](https://github.com/descriptinc/descript-audio-codec) //! /// An efficient neural codec for compressing/decompressing audio /// use crate::models::encodec; use candle::{IndexOp, Result, Tensor, D}; use candle_nn::{Conv1d, Conv1dConfig, ConvTranspose1d, ConvTranspose1dConfig, VarBuilder}; #[derive(serde::Deserialize, Debug, Clone)] pub struct Config { pub num_codebooks: usize, pub model_bitrate: u32, pub codebook_size: usize, pub latent_dim: usize, pub frame_rate: u32, pub sampling_rate: u32, } #[derive(Debug, Clone)] pub struct Snake1d { alpha: Tensor, } impl Snake1d { pub fn new(channels: usize, vb: VarBuilder) -> Result<Self> { let alpha = vb.get((1, channels, 1), "alpha")?; Ok(Self { alpha }) } } impl candle::Module for Snake1d { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let xs_shape = xs.shape(); let xs = xs.flatten_from(2)?; let sin = self.alpha.broadcast_mul(&xs)?.sin()?; let sin = (&sin * &sin)?; (xs + (&self.alpha + 1e-9)?.recip()?.broadcast_mul(&sin)?)?.reshape(xs_shape) } } #[derive(Debug, Clone)] pub struct ResidualUnit { snake1: Snake1d, conv1: Conv1d, snake2: Snake1d, conv2: Conv1d, } impl ResidualUnit { pub fn new(dim: usize, dilation: usize, vb: VarBuilder) -> Result<Self> { let pad = ((7 - 1) * dilation) / 2; let vb = vb.pp("block"); let snake1 = Snake1d::new(dim, vb.pp(0))?; let cfg1 = Conv1dConfig { dilation, padding: pad, ..Default::default() }; let conv1 = encodec::conv1d_weight_norm(dim, dim, 7, cfg1, vb.pp(1))?; let snake2 = Snake1d::new(dim, vb.pp(2))?; let conv2 = encodec::conv1d_weight_norm(dim, dim, 1, Default::default(), vb.pp(3))?; Ok(Self { snake1, conv1, snake2, conv2, }) } } impl candle::Module for ResidualUnit { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let ys = xs .apply(&self.snake1)? .apply(&self.conv1)? .apply(&self.snake2)? .apply(&self.conv2)?; let pad = (xs.dim(D::Minus1)? - ys.dim(D::Minus1)?) / 2; if pad > 0 { &ys + xs.narrow(D::Minus1, pad, ys.dim(D::Minus1)?) } else { ys + xs } } } #[derive(Debug, Clone)] pub struct EncoderBlock { res1: ResidualUnit, res2: ResidualUnit, res3: ResidualUnit, snake1: Snake1d, conv1: Conv1d, } impl EncoderBlock { pub fn new(dim: usize, stride: usize, vb: VarBuilder) -> Result<Self> { let vb = vb.pp("block"); let res1 = ResidualUnit::new(dim / 2, 1, vb.pp(0))?; let res2 = ResidualUnit::new(dim / 2, 3, vb.pp(1))?; let res3 = ResidualUnit::new(dim / 2, 9, vb.pp(2))?; let snake1 = Snake1d::new(dim / 2, vb.pp(3))?; let cfg1 = Conv1dConfig { stride, padding: stride.div_ceil(2), ..Default::default() }; let conv1 = encodec::conv1d_weight_norm(dim / 2, dim, 2 * stride, cfg1, vb.pp(4))?; Ok(Self { res1, res2, res3, snake1, conv1, }) } } impl candle::Module for EncoderBlock { fn forward(&self, xs: &Tensor) -> Result<Tensor> { xs.apply(&self.res1)? .apply(&self.res2)? .apply(&self.res3)? .apply(&self.snake1)? .apply(&self.conv1) } } #[derive(Debug, Clone)] pub struct Encoder { conv1: Conv1d, blocks: Vec<EncoderBlock>, snake1: Snake1d, conv2: Conv1d, } impl candle::Module for Encoder { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let mut xs = xs.apply(&self.conv1)?; for block in self.blocks.iter() { xs = xs.apply(block)? } xs.apply(&self.snake1)?.apply(&self.conv2) } } impl Encoder { pub fn new( mut d_model: usize, strides: &[usize], d_latent: usize, vb: VarBuilder, ) -> Result<Self> { let vb = vb.pp("block"); let cfg1 = Conv1dConfig { padding: 3, ..Default::default() }; let conv1 = encodec::conv1d_weight_norm(1, d_model, 7, cfg1, vb.pp(0))?; let mut blocks = Vec::with_capacity(strides.len()); for (block_idx, stride) in strides.iter().enumerate() { d_model *= 2; let block = EncoderBlock::new(d_model, *stride, vb.pp(block_idx + 1))?; blocks.push(block) } let snake1 = Snake1d::new(d_model, vb.pp(strides.len() + 1))?; let cfg2 = Conv1dConfig { padding: 1, ..Default::default() }; let conv2 = encodec::conv1d_weight_norm(d_model, d_latent, 3, cfg2, vb.pp(strides.len() + 2))?; Ok(Self { conv1, blocks, snake1, conv2, }) } } #[derive(Debug, Clone)] pub struct DecoderBlock { snake1: Snake1d, conv_tr1: ConvTranspose1d, res1: ResidualUnit, res2: ResidualUnit, res3: ResidualUnit, } impl DecoderBlock { pub fn new(in_dim: usize, out_dim: usize, stride: usize, vb: VarBuilder) -> Result<Self> { let vb = vb.pp("block"); let snake1 = Snake1d::new(in_dim, vb.pp(0))?; let cfg = ConvTranspose1dConfig { stride, padding: stride.div_ceil(2), ..Default::default() }; let conv_tr1 = encodec::conv_transpose1d_weight_norm( in_dim, out_dim, 2 * stride, true, cfg, vb.pp(1), )?; let res1 = ResidualUnit::new(out_dim, 1, vb.pp(2))?; let res2 = ResidualUnit::new(out_dim, 3, vb.pp(3))?; let res3 = ResidualUnit::new(out_dim, 9, vb.pp(4))?; Ok(Self { snake1, conv_tr1, res1, res2, res3, }) } } impl candle_nn::Module for DecoderBlock { fn forward(&self, xs: &Tensor) -> Result<Tensor> { xs.apply(&self.snake1)? .apply(&self.conv_tr1)? .apply(&self.res1)? .apply(&self.res2)? .apply(&self.res3) } } #[derive(Debug, Clone)] pub struct Decoder { conv1: Conv1d, blocks: Vec<DecoderBlock>, snake1: Snake1d, conv2: Conv1d, } impl Decoder { pub fn new( in_c: usize, mut channels: usize, rates: &[usize], d_out: usize, vb: VarBuilder, ) -> Result<Self> { let vb = vb.pp("model"); let cfg1 = Conv1dConfig { padding: 3, ..Default::default() }; let conv1 = encodec::conv1d_weight_norm(in_c, channels, 7, cfg1, vb.pp(0))?; let mut blocks = Vec::with_capacity(rates.len()); for (idx, stride) in rates.iter().enumerate() { let block = DecoderBlock::new(channels, channels / 2, *stride, vb.pp(idx + 1))?; channels /= 2; blocks.push(block) } let snake1 = Snake1d::new(channels, vb.pp(rates.len() + 1))?; let conv2 = encodec::conv1d_weight_norm(channels, d_out, 7, cfg1, vb.pp(rates.len() + 2))?; Ok(Self { conv1, blocks, snake1, conv2, }) } } impl candle::Module for Decoder { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let mut xs = xs.apply(&self.conv1)?; for block in self.blocks.iter() { xs = xs.apply(block)? } xs.apply(&self.snake1)?.apply(&self.conv2) } } #[allow(unused)] #[derive(Clone, Debug)] pub struct VectorQuantizer { in_proj: Conv1d, out_proj: Conv1d, codebook: candle_nn::Embedding, } impl VectorQuantizer { pub fn new(in_dim: usize, cb_size: usize, cb_dim: usize, vb: VarBuilder) -> Result<Self> { let in_proj = encodec::conv1d_weight_norm(in_dim, cb_dim, 1, Default::default(), vb.pp("in_proj"))?; let out_proj = encodec::conv1d_weight_norm(cb_dim, in_dim, 1, Default::default(), vb.pp("out_proj"))?; let codebook = candle_nn::embedding(cb_size, cb_dim, vb.pp("codebook"))?; Ok(Self { in_proj, out_proj, codebook, }) } pub fn embed_code(&self, embed_id: &Tensor) -> Result<Tensor> { embed_id.apply(&self.codebook) } pub fn decode_code(&self, embed_id: &Tensor) -> Result<Tensor> { self.embed_code(embed_id)?.transpose(1, 2) } } #[derive(Clone, Debug)] pub struct ResidualVectorQuantizer { quantizers: Vec<VectorQuantizer>, } impl ResidualVectorQuantizer { pub fn new( input_dim: usize, n_codebooks: usize, cb_size: usize, cb_dim: usize, vb: VarBuilder, ) -> Result<Self> { let vb = &vb.pp("quantizers"); let quantizers = (0..n_codebooks) .map(|i| VectorQuantizer::new(input_dim, cb_size, cb_dim, vb.pp(i))) .collect::<Result<Vec<_>>>()?; Ok(Self { quantizers }) } #[allow(clippy::wrong_self_convention)] pub fn from_codes(&self, codes: &Tensor) -> Result<Tensor> { let mut sum = None; for (idx, quantizer) in self.quantizers.iter().enumerate() { let z_p_i = quantizer.decode_code(&codes.i((.., idx))?)?; let z_q_i = z_p_i.apply(&quantizer.out_proj)?; let s = match sum { None => z_q_i, Some(s) => (s + z_q_i)?, }; sum = Some(s) } match sum { Some(s) => Ok(s), None => candle::bail!("empty codebooks"), } } } #[derive(Debug, Clone)] pub struct Model { pub encoder: Encoder, pub quantizer: ResidualVectorQuantizer, pub decoder: Decoder, } impl Model { pub fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let encoder = Encoder::new(64, &[2, 4, 8, 8], cfg.latent_dim, vb.pp("encoder"))?; let quantizer = ResidualVectorQuantizer::new( cfg.latent_dim, cfg.num_codebooks, cfg.codebook_size, 8, vb.pp("quantizer"), )?; let decoder = Decoder::new(cfg.latent_dim, 1536, &[8, 8, 4, 2], 1, vb.pp("decoder"))?; Ok(Self { encoder, decoder, quantizer, }) } pub fn decode_codes(&self, audio_codes: &Tensor) -> Result<Tensor> { let audio_values = self.quantizer.from_codes(audio_codes)?; audio_values.apply(&self.decoder) } }
candle/candle-transformers/src/models/dac.rs/0
{ "file_path": "candle/candle-transformers/src/models/dac.rs", "repo_id": "candle", "token_count": 5694 }
56
use super::model::{attention, timestep_embedding, Config, EmbedNd}; use crate::quantized_nn::{linear, linear_b, Linear}; use crate::quantized_var_builder::VarBuilder; use candle::{DType, IndexOp, Result, Tensor, D}; use candle_nn::{LayerNorm, RmsNorm}; fn layer_norm(dim: usize, vb: VarBuilder) -> Result<LayerNorm> { let ws = Tensor::ones(dim, DType::F32, vb.device())?; Ok(LayerNorm::new_no_bias(ws, 1e-6)) } #[derive(Debug, Clone)] pub struct MlpEmbedder { in_layer: Linear, out_layer: Linear, } impl MlpEmbedder { fn new(in_sz: usize, h_sz: usize, vb: VarBuilder) -> Result<Self> { let in_layer = linear(in_sz, h_sz, vb.pp("in_layer"))?; let out_layer = linear(h_sz, h_sz, vb.pp("out_layer"))?; Ok(Self { in_layer, out_layer, }) } } impl candle::Module for MlpEmbedder { fn forward(&self, xs: &Tensor) -> Result<Tensor> { xs.apply(&self.in_layer)?.silu()?.apply(&self.out_layer) } } #[derive(Debug, Clone)] pub struct QkNorm { query_norm: RmsNorm, key_norm: RmsNorm, } impl QkNorm { fn new(dim: usize, vb: VarBuilder) -> Result<Self> { let query_norm = vb.get(dim, "query_norm.scale")?.dequantize(vb.device())?; let query_norm = RmsNorm::new(query_norm, 1e-6); let key_norm = vb.get(dim, "key_norm.scale")?.dequantize(vb.device())?; let key_norm = RmsNorm::new(key_norm, 1e-6); Ok(Self { query_norm, key_norm, }) } } struct ModulationOut { shift: Tensor, scale: Tensor, gate: Tensor, } impl ModulationOut { fn scale_shift(&self, xs: &Tensor) -> Result<Tensor> { xs.broadcast_mul(&(&self.scale + 1.)?)? .broadcast_add(&self.shift) } fn gate(&self, xs: &Tensor) -> Result<Tensor> { self.gate.broadcast_mul(xs) } } #[derive(Debug, Clone)] struct Modulation1 { lin: Linear, } impl Modulation1 { fn new(dim: usize, vb: VarBuilder) -> Result<Self> { let lin = linear(dim, 3 * dim, vb.pp("lin"))?; Ok(Self { lin }) } fn forward(&self, vec_: &Tensor) -> Result<ModulationOut> { let ys = vec_ .silu()? .apply(&self.lin)? .unsqueeze(1)? .chunk(3, D::Minus1)?; if ys.len() != 3 { candle::bail!("unexpected len from chunk {ys:?}") } Ok(ModulationOut { shift: ys[0].clone(), scale: ys[1].clone(), gate: ys[2].clone(), }) } } #[derive(Debug, Clone)] struct Modulation2 { lin: Linear, } impl Modulation2 { fn new(dim: usize, vb: VarBuilder) -> Result<Self> { let lin = linear(dim, 6 * dim, vb.pp("lin"))?; Ok(Self { lin }) } fn forward(&self, vec_: &Tensor) -> Result<(ModulationOut, ModulationOut)> { let ys = vec_ .silu()? .apply(&self.lin)? .unsqueeze(1)? .chunk(6, D::Minus1)?; if ys.len() != 6 { candle::bail!("unexpected len from chunk {ys:?}") } let mod1 = ModulationOut { shift: ys[0].clone(), scale: ys[1].clone(), gate: ys[2].clone(), }; let mod2 = ModulationOut { shift: ys[3].clone(), scale: ys[4].clone(), gate: ys[5].clone(), }; Ok((mod1, mod2)) } } #[derive(Debug, Clone)] pub struct SelfAttention { qkv: Linear, norm: QkNorm, proj: Linear, num_heads: usize, } impl SelfAttention { fn new(dim: usize, num_heads: usize, qkv_bias: bool, vb: VarBuilder) -> Result<Self> { let head_dim = dim / num_heads; let qkv = linear_b(dim, dim * 3, qkv_bias, vb.pp("qkv"))?; let norm = QkNorm::new(head_dim, vb.pp("norm"))?; let proj = linear(dim, dim, vb.pp("proj"))?; Ok(Self { qkv, norm, proj, num_heads, }) } fn qkv(&self, xs: &Tensor) -> Result<(Tensor, Tensor, Tensor)> { let qkv = xs.apply(&self.qkv)?; let (b, l, _khd) = qkv.dims3()?; let qkv = qkv.reshape((b, l, 3, self.num_heads, ()))?; let q = qkv.i((.., .., 0))?.transpose(1, 2)?; let k = qkv.i((.., .., 1))?.transpose(1, 2)?; let v = qkv.i((.., .., 2))?.transpose(1, 2)?; let q = q.apply(&self.norm.query_norm)?; let k = k.apply(&self.norm.key_norm)?; Ok((q, k, v)) } #[allow(unused)] fn forward(&self, xs: &Tensor, pe: &Tensor) -> Result<Tensor> { let (q, k, v) = self.qkv(xs)?; attention(&q, &k, &v, pe)?.apply(&self.proj) } } #[derive(Debug, Clone)] struct Mlp { lin1: Linear, lin2: Linear, } impl Mlp { fn new(in_sz: usize, mlp_sz: usize, vb: VarBuilder) -> Result<Self> { let lin1 = linear(in_sz, mlp_sz, vb.pp("0"))?; let lin2 = linear(mlp_sz, in_sz, vb.pp("2"))?; Ok(Self { lin1, lin2 }) } } impl candle::Module for Mlp { fn forward(&self, xs: &Tensor) -> Result<Tensor> { xs.apply(&self.lin1)?.gelu()?.apply(&self.lin2) } } #[derive(Debug, Clone)] pub struct DoubleStreamBlock { img_mod: Modulation2, img_norm1: LayerNorm, img_attn: SelfAttention, img_norm2: LayerNorm, img_mlp: Mlp, txt_mod: Modulation2, txt_norm1: LayerNorm, txt_attn: SelfAttention, txt_norm2: LayerNorm, txt_mlp: Mlp, } impl DoubleStreamBlock { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let h_sz = cfg.hidden_size; let mlp_sz = (h_sz as f64 * cfg.mlp_ratio) as usize; let img_mod = Modulation2::new(h_sz, vb.pp("img_mod"))?; let img_norm1 = layer_norm(h_sz, vb.pp("img_norm1"))?; let img_attn = SelfAttention::new(h_sz, cfg.num_heads, cfg.qkv_bias, vb.pp("img_attn"))?; let img_norm2 = layer_norm(h_sz, vb.pp("img_norm2"))?; let img_mlp = Mlp::new(h_sz, mlp_sz, vb.pp("img_mlp"))?; let txt_mod = Modulation2::new(h_sz, vb.pp("txt_mod"))?; let txt_norm1 = layer_norm(h_sz, vb.pp("txt_norm1"))?; let txt_attn = SelfAttention::new(h_sz, cfg.num_heads, cfg.qkv_bias, vb.pp("txt_attn"))?; let txt_norm2 = layer_norm(h_sz, vb.pp("txt_norm2"))?; let txt_mlp = Mlp::new(h_sz, mlp_sz, vb.pp("txt_mlp"))?; Ok(Self { img_mod, img_norm1, img_attn, img_norm2, img_mlp, txt_mod, txt_norm1, txt_attn, txt_norm2, txt_mlp, }) } fn forward( &self, img: &Tensor, txt: &Tensor, vec_: &Tensor, pe: &Tensor, ) -> Result<(Tensor, Tensor)> { let (img_mod1, img_mod2) = self.img_mod.forward(vec_)?; // shift, scale, gate let (txt_mod1, txt_mod2) = self.txt_mod.forward(vec_)?; // shift, scale, gate let img_modulated = img.apply(&self.img_norm1)?; let img_modulated = img_mod1.scale_shift(&img_modulated)?; let (img_q, img_k, img_v) = self.img_attn.qkv(&img_modulated)?; let txt_modulated = txt.apply(&self.txt_norm1)?; let txt_modulated = txt_mod1.scale_shift(&txt_modulated)?; let (txt_q, txt_k, txt_v) = self.txt_attn.qkv(&txt_modulated)?; let q = Tensor::cat(&[txt_q, img_q], 2)?; let k = Tensor::cat(&[txt_k, img_k], 2)?; let v = Tensor::cat(&[txt_v, img_v], 2)?; let attn = attention(&q, &k, &v, pe)?; let txt_attn = attn.narrow(1, 0, txt.dim(1)?)?; let img_attn = attn.narrow(1, txt.dim(1)?, attn.dim(1)? - txt.dim(1)?)?; let img = (img + img_mod1.gate(&img_attn.apply(&self.img_attn.proj)?))?; let img = (&img + img_mod2.gate( &img_mod2 .scale_shift(&img.apply(&self.img_norm2)?)? .apply(&self.img_mlp)?, )?)?; let txt = (txt + txt_mod1.gate(&txt_attn.apply(&self.txt_attn.proj)?))?; let txt = (&txt + txt_mod2.gate( &txt_mod2 .scale_shift(&txt.apply(&self.txt_norm2)?)? .apply(&self.txt_mlp)?, )?)?; Ok((img, txt)) } } #[derive(Debug, Clone)] pub struct SingleStreamBlock { linear1: Linear, linear2: Linear, norm: QkNorm, pre_norm: LayerNorm, modulation: Modulation1, h_sz: usize, mlp_sz: usize, num_heads: usize, } impl SingleStreamBlock { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let h_sz = cfg.hidden_size; let mlp_sz = (h_sz as f64 * cfg.mlp_ratio) as usize; let head_dim = h_sz / cfg.num_heads; let linear1 = linear(h_sz, h_sz * 3 + mlp_sz, vb.pp("linear1"))?; let linear2 = linear(h_sz + mlp_sz, h_sz, vb.pp("linear2"))?; let norm = QkNorm::new(head_dim, vb.pp("norm"))?; let pre_norm = layer_norm(h_sz, vb.pp("pre_norm"))?; let modulation = Modulation1::new(h_sz, vb.pp("modulation"))?; Ok(Self { linear1, linear2, norm, pre_norm, modulation, h_sz, mlp_sz, num_heads: cfg.num_heads, }) } fn forward(&self, xs: &Tensor, vec_: &Tensor, pe: &Tensor) -> Result<Tensor> { let mod_ = self.modulation.forward(vec_)?; let x_mod = mod_.scale_shift(&xs.apply(&self.pre_norm)?)?; let x_mod = x_mod.apply(&self.linear1)?; let qkv = x_mod.narrow(D::Minus1, 0, 3 * self.h_sz)?; let (b, l, _khd) = qkv.dims3()?; let qkv = qkv.reshape((b, l, 3, self.num_heads, ()))?; let q = qkv.i((.., .., 0))?.transpose(1, 2)?; let k = qkv.i((.., .., 1))?.transpose(1, 2)?; let v = qkv.i((.., .., 2))?.transpose(1, 2)?; let mlp = x_mod.narrow(D::Minus1, 3 * self.h_sz, self.mlp_sz)?; let q = q.apply(&self.norm.query_norm)?; let k = k.apply(&self.norm.key_norm)?; let attn = attention(&q, &k, &v, pe)?; let output = Tensor::cat(&[attn, mlp.gelu()?], 2)?.apply(&self.linear2)?; xs + mod_.gate(&output) } } #[derive(Debug, Clone)] pub struct LastLayer { norm_final: LayerNorm, linear: Linear, ada_ln_modulation: Linear, } impl LastLayer { fn new(h_sz: usize, p_sz: usize, out_c: usize, vb: VarBuilder) -> Result<Self> { let norm_final = layer_norm(h_sz, vb.pp("norm_final"))?; let linear_ = linear(h_sz, p_sz * p_sz * out_c, vb.pp("linear"))?; let ada_ln_modulation = linear(h_sz, 2 * h_sz, vb.pp("adaLN_modulation.1"))?; Ok(Self { norm_final, linear: linear_, ada_ln_modulation, }) } fn forward(&self, xs: &Tensor, vec: &Tensor) -> Result<Tensor> { let chunks = vec.silu()?.apply(&self.ada_ln_modulation)?.chunk(2, 1)?; let (shift, scale) = (&chunks[0], &chunks[1]); let xs = xs .apply(&self.norm_final)? .broadcast_mul(&(scale.unsqueeze(1)? + 1.0)?)? .broadcast_add(&shift.unsqueeze(1)?)?; xs.apply(&self.linear) } } #[derive(Debug, Clone)] pub struct Flux { img_in: Linear, txt_in: Linear, time_in: MlpEmbedder, vector_in: MlpEmbedder, guidance_in: Option<MlpEmbedder>, pe_embedder: EmbedNd, double_blocks: Vec<DoubleStreamBlock>, single_blocks: Vec<SingleStreamBlock>, final_layer: LastLayer, } impl Flux { pub fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let img_in = linear(cfg.in_channels, cfg.hidden_size, vb.pp("img_in"))?; let txt_in = linear(cfg.context_in_dim, cfg.hidden_size, vb.pp("txt_in"))?; let mut double_blocks = Vec::with_capacity(cfg.depth); let vb_d = vb.pp("double_blocks"); for idx in 0..cfg.depth { let db = DoubleStreamBlock::new(cfg, vb_d.pp(idx))?; double_blocks.push(db) } let mut single_blocks = Vec::with_capacity(cfg.depth_single_blocks); let vb_s = vb.pp("single_blocks"); for idx in 0..cfg.depth_single_blocks { let sb = SingleStreamBlock::new(cfg, vb_s.pp(idx))?; single_blocks.push(sb) } let time_in = MlpEmbedder::new(256, cfg.hidden_size, vb.pp("time_in"))?; let vector_in = MlpEmbedder::new(cfg.vec_in_dim, cfg.hidden_size, vb.pp("vector_in"))?; let guidance_in = if cfg.guidance_embed { let mlp = MlpEmbedder::new(256, cfg.hidden_size, vb.pp("guidance_in"))?; Some(mlp) } else { None }; let final_layer = LastLayer::new(cfg.hidden_size, 1, cfg.in_channels, vb.pp("final_layer"))?; let pe_dim = cfg.hidden_size / cfg.num_heads; let pe_embedder = EmbedNd::new(pe_dim, cfg.theta, cfg.axes_dim.to_vec()); Ok(Self { img_in, txt_in, time_in, vector_in, guidance_in, pe_embedder, double_blocks, single_blocks, final_layer, }) } } impl super::WithForward for Flux { #[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> { if txt.rank() != 3 { candle::bail!("unexpected shape for txt {:?}", txt.shape()) } if img.rank() != 3 { candle::bail!("unexpected shape for img {:?}", img.shape()) } let dtype = img.dtype(); let pe = { let ids = Tensor::cat(&[txt_ids, img_ids], 1)?; ids.apply(&self.pe_embedder)? }; let mut txt = txt.apply(&self.txt_in)?; let mut img = img.apply(&self.img_in)?; let vec_ = timestep_embedding(timesteps, 256, dtype)?.apply(&self.time_in)?; let vec_ = match (self.guidance_in.as_ref(), guidance) { (Some(g_in), Some(guidance)) => { (vec_ + timestep_embedding(guidance, 256, dtype)?.apply(g_in))? } _ => vec_, }; let vec_ = (vec_ + y.apply(&self.vector_in))?; // Double blocks for block in self.double_blocks.iter() { (img, txt) = block.forward(&img, &txt, &vec_, &pe)? } // Single blocks let mut img = Tensor::cat(&[&txt, &img], 1)?; for block in self.single_blocks.iter() { img = block.forward(&img, &vec_, &pe)?; } let img = img.i((.., txt.dim(1)?..))?; self.final_layer.forward(&img, &vec_) } }
candle/candle-transformers/src/models/flux/quantized_model.rs/0
{ "file_path": "candle/candle-transformers/src/models/flux/quantized_model.rs", "repo_id": "candle", "token_count": 7943 }
57
pub fn get_anyres_image_grid_shape( image_size: (u32, u32), grid_pinpoints: &[(u32, u32)], patch_size: u32, ) -> (u32, u32) { let (width, height) = select_best_resolution(image_size, grid_pinpoints); (width / patch_size, height / patch_size) } pub fn select_best_resolution( original_size: (u32, u32), possible_resolutions: &[(u32, u32)], ) -> (u32, u32) { let (original_width, original_height) = original_size; let mut best_fit = (0, 0); let original_width_f = original_width as f32; let original_height_f = original_height as f32; let mut max_effective_resolution = 0_u32; let mut min_wasted_resolution = u32::MAX; for (width, height) in possible_resolutions { let width_f = *width as f32; let height_f = *height as f32; let scale = (width_f / original_width_f).min(height_f / original_height_f); let (downscaled_width, downscaled_height) = ( (original_width_f * scale) as u32, (original_height_f * scale) as u32, ); let effective_resolution = std::cmp::min((*width) * (*height), downscaled_width * downscaled_height); let wasted_resolution = (*width) * (*height) - effective_resolution; if effective_resolution > max_effective_resolution || (effective_resolution == max_effective_resolution && wasted_resolution < min_wasted_resolution) { best_fit = (*width, *height); max_effective_resolution = effective_resolution; min_wasted_resolution = wasted_resolution; } } best_fit }
candle/candle-transformers/src/models/llava/utils.rs/0
{ "file_path": "candle/candle-transformers/src/models/llava/utils.rs", "repo_id": "candle", "token_count": 689 }
58
// Implement the MMDiT model originally introduced for Stable Diffusion 3 (https://arxiv.org/abs/2403.03206), // as well as the MMDiT-X variant introduced for Stable Diffusion 3.5-medium (https://huggingface.co/stabilityai/stable-diffusion-3.5-medium) // This follows the implementation of the MMDiT model in the ComfyUI repository. // https://github.com/comfyanonymous/ComfyUI/blob/78e133d0415784924cd2674e2ee48f3eeca8a2aa/comfy/ldm/modules/diffusionmodules/mmdit.py#L1 // with MMDiT-X support following the Stability-AI/sd3.5 repository. // https://github.com/Stability-AI/sd3.5/blob/4e484e05308d83fb77ae6f680028e6c313f9da54/mmditx.py#L1 use candle::{Module, Result, Tensor, D}; use candle_nn as nn; use super::blocks::{ ContextQkvOnlyJointBlock, FinalLayer, JointBlock, MMDiTJointBlock, MMDiTXJointBlock, }; use super::embedding::{ PatchEmbedder, PositionEmbedder, TimestepEmbedder, Unpatchifier, VectorEmbedder, }; #[derive(Debug, Clone)] pub struct Config { pub patch_size: usize, pub in_channels: usize, pub out_channels: usize, pub depth: usize, pub head_size: usize, pub adm_in_channels: usize, pub pos_embed_max_size: usize, pub context_embed_size: usize, pub frequency_embedding_size: usize, } impl Config { pub fn sd3_medium() -> Self { Self { patch_size: 2, in_channels: 16, out_channels: 16, depth: 24, head_size: 64, adm_in_channels: 2048, pos_embed_max_size: 192, context_embed_size: 4096, frequency_embedding_size: 256, } } pub fn sd3_5_medium() -> Self { Self { patch_size: 2, in_channels: 16, out_channels: 16, depth: 24, head_size: 64, adm_in_channels: 2048, pos_embed_max_size: 384, context_embed_size: 4096, frequency_embedding_size: 256, } } pub fn sd3_5_large() -> Self { Self { patch_size: 2, in_channels: 16, out_channels: 16, depth: 38, head_size: 64, adm_in_channels: 2048, pos_embed_max_size: 192, context_embed_size: 4096, frequency_embedding_size: 256, } } } pub struct MMDiT { core: MMDiTCore, patch_embedder: PatchEmbedder, pos_embedder: PositionEmbedder, timestep_embedder: TimestepEmbedder, vector_embedder: VectorEmbedder, context_embedder: nn::Linear, unpatchifier: Unpatchifier, } impl MMDiT { pub fn new(cfg: &Config, use_flash_attn: bool, vb: nn::VarBuilder) -> Result<Self> { let hidden_size = cfg.head_size * cfg.depth; let core = MMDiTCore::new( cfg.depth, hidden_size, cfg.depth, cfg.patch_size, cfg.out_channels, use_flash_attn, vb.clone(), )?; let patch_embedder = PatchEmbedder::new( cfg.patch_size, cfg.in_channels, hidden_size, vb.pp("x_embedder"), )?; let pos_embedder = PositionEmbedder::new( hidden_size, cfg.patch_size, cfg.pos_embed_max_size, vb.clone(), )?; let timestep_embedder = TimestepEmbedder::new( hidden_size, cfg.frequency_embedding_size, vb.pp("t_embedder"), )?; let vector_embedder = VectorEmbedder::new(cfg.adm_in_channels, hidden_size, vb.pp("y_embedder"))?; let context_embedder = nn::linear( cfg.context_embed_size, hidden_size, vb.pp("context_embedder"), )?; let unpatchifier = Unpatchifier::new(cfg.patch_size, cfg.out_channels)?; Ok(Self { core, patch_embedder, pos_embedder, timestep_embedder, vector_embedder, context_embedder, unpatchifier, }) } pub fn forward( &self, x: &Tensor, t: &Tensor, y: &Tensor, context: &Tensor, skip_layers: Option<&[usize]>, ) -> Result<Tensor> { // Following the convention of the ComfyUI implementation. // https://github.com/comfyanonymous/ComfyUI/blob/78e133d0415784924cd2674e2ee48f3eeca8a2aa/comfy/ldm/modules/diffusionmodules/mmdit.py#L919 // // Forward pass of DiT. // x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images) // t: (N,) tensor of diffusion timesteps // y: (N,) tensor of class labels let h = x.dim(D::Minus2)?; let w = x.dim(D::Minus1)?; let cropped_pos_embed = self.pos_embedder.get_cropped_pos_embed(h, w)?; let x = self .patch_embedder .forward(x)? .broadcast_add(&cropped_pos_embed)?; let c = self.timestep_embedder.forward(t)?; let y = self.vector_embedder.forward(y)?; let c = (c + y)?; let context = self.context_embedder.forward(context)?; let x = self.core.forward(&context, &x, &c, skip_layers)?; let x = self.unpatchifier.unpatchify(&x, h, w)?; x.narrow(2, 0, h)?.narrow(3, 0, w) } } pub struct MMDiTCore { joint_blocks: Vec<Box<dyn JointBlock>>, context_qkv_only_joint_block: ContextQkvOnlyJointBlock, final_layer: FinalLayer, } impl MMDiTCore { pub fn new( depth: usize, hidden_size: usize, num_heads: usize, patch_size: usize, out_channels: usize, use_flash_attn: bool, vb: nn::VarBuilder, ) -> Result<Self> { let mut joint_blocks = Vec::with_capacity(depth - 1); for i in 0..depth - 1 { let joint_block_vb_pp = format!("joint_blocks.{i}"); let joint_block: Box<dyn JointBlock> = if vb.contains_tensor(&format!("{joint_block_vb_pp}.x_block.attn2.qkv.weight")) { Box::new(MMDiTXJointBlock::new( hidden_size, num_heads, use_flash_attn, vb.pp(&joint_block_vb_pp), )?) } else { Box::new(MMDiTJointBlock::new( hidden_size, num_heads, use_flash_attn, vb.pp(&joint_block_vb_pp), )?) }; joint_blocks.push(joint_block); } Ok(Self { joint_blocks, context_qkv_only_joint_block: ContextQkvOnlyJointBlock::new( hidden_size, num_heads, use_flash_attn, vb.pp(format!("joint_blocks.{}", depth - 1)), )?, final_layer: FinalLayer::new( hidden_size, patch_size, out_channels, vb.pp("final_layer"), )?, }) } pub fn forward( &self, context: &Tensor, x: &Tensor, c: &Tensor, skip_layers: Option<&[usize]>, ) -> Result<Tensor> { let (mut context, mut x) = (context.clone(), x.clone()); for (i, joint_block) in self.joint_blocks.iter().enumerate() { if let Some(skip_layers) = &skip_layers { if skip_layers.contains(&i) { continue; } } (context, x) = joint_block.forward(&context, &x, c)?; } let x = self.context_qkv_only_joint_block.forward(&context, &x, c)?; self.final_layer.forward(&x, c) } }
candle/candle-transformers/src/models/mmdit/model.rs/0
{ "file_path": "candle/candle-transformers/src/models/mmdit/model.rs", "repo_id": "candle", "token_count": 4202 }
59
//! Multimodal multi-purpose model combining Gemma-based language model with SigLIP image understanding //! //! See PaLiGemma details at: //! - [Paper](https://arxiv.org/abs/2402.05257) //! - [Google Blog Post](https://blog.research.google/2024/02/paligemma-scaling-language-image.html) //! //! The model is a multimodal combination of: //! - SigLIP vision encoder //! - Gemma language model //! - Cross-projection layers //! //! References: //! - [HuggingFace Implementation](https://huggingface.co/google/paligemma-3b) //! - [Paper: PaLI-3 and Beyond: Scaling Language-Image Learning](https://arxiv.org/abs/2402.05257) //! use crate::models::{gemma, siglip}; use candle::{Module, Result, Tensor}; use candle_nn::{linear, Linear, VarBuilder}; #[derive(serde::Deserialize, Clone, Debug)] pub struct Config { pub vision_config: siglip::VisionConfig, pub text_config: gemma::Config, pub projection_dim: usize, } impl Config { pub fn paligemma_3b_224() -> Self { // https://huggingface.co/google/paligemma-3b-pt-224/blob/main/config.json Self { vision_config: siglip::VisionConfig::paligemma_3b_224(), text_config: gemma::Config { hidden_size: 2048, intermediate_size: 16384, num_attention_heads: 8, num_hidden_layers: 18, num_key_value_heads: 1, vocab_size: 257216, // Default values. rope_theta: 10000., head_dim: 256, hidden_act: Some(candle_nn::Activation::GeluPytorchTanh), hidden_activation: None, attention_bias: false, max_position_embeddings: 8192, rms_norm_eps: 1e-6, }, projection_dim: 2048, } } pub fn paligemma_3b_448() -> Self { Self { vision_config: siglip::VisionConfig::paligemma_3b_448(), text_config: gemma::Config { hidden_size: 2048, intermediate_size: 16384, num_attention_heads: 8, num_hidden_layers: 18, num_key_value_heads: 1, // Default values. rope_theta: 10000., head_dim: 256, hidden_act: Some(candle_nn::Activation::GeluPytorchTanh), hidden_activation: None, attention_bias: false, max_position_embeddings: 8192, rms_norm_eps: 1e-6, vocab_size: 257216, }, projection_dim: 2048, } } } #[derive(Clone, Debug)] pub struct MultiModalProjector { linear: Linear, } impl MultiModalProjector { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let linear = linear( cfg.vision_config.hidden_size, cfg.projection_dim, vb.pp("linear"), )?; Ok(Self { linear }) } } impl Module for MultiModalProjector { fn forward(&self, xs: &Tensor) -> Result<Tensor> { xs.apply(&self.linear) } } #[derive(Clone, Debug)] pub struct Model { pos: usize, vision_tower: siglip::VisionModel, multi_modal_projector: MultiModalProjector, language_model: gemma::Model, } impl Model { pub fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let vision_tower = siglip::VisionModel::new( &cfg.vision_config, false, vb.pp("vision_tower.vision_model"), )?; let multi_modal_projector = MultiModalProjector::new(cfg, vb.pp("multi_modal_projector"))?; let language_model = gemma::Model::new(false, &cfg.text_config, vb.pp("language_model"))?; Ok(Self { pos: 0, language_model, vision_tower, multi_modal_projector, }) } pub fn setup(&mut self, pixel_values: &Tensor, input_ids: &Tensor) -> Result<Tensor> { self.clear_kv_cache(); let image_features = self .vision_tower .forward(pixel_values)? .apply(&self.multi_modal_projector)?; let image_features = crate::models::clip::div_l2_norm(&image_features)?; let text_features = self.language_model.embed_tokens().forward(input_ids)?; let input_embeds = Tensor::cat(&[image_features, text_features], 1)?; self.pos = input_embeds.dim(1)?; self.language_model.forward_embeds(&input_embeds, None, 0) } pub fn forward(&mut self, input_ids: &Tensor) -> Result<Tensor> { let pos = self.pos; let seq_len = input_ids.dim(1)?; self.pos = pos + seq_len; self.language_model.forward(input_ids, pos) } pub fn forward_without_projection(&mut self, input_ids: &Tensor) -> Result<Tensor> { self.clear_kv_cache(); let input_embeds = self.language_model.embed_tokens().forward(input_ids)?; self.language_model .forward_embeds_without_projection(&input_embeds, None, 0) } pub fn setup_without_projection( &mut self, pixel_values: &Tensor, input_ids: &Tensor, ) -> Result<Tensor> { self.clear_kv_cache(); let image_features = self .vision_tower .forward(pixel_values)? .apply(&self.multi_modal_projector)?; let image_features = crate::models::clip::div_l2_norm(&image_features)?; let text_features = self.language_model.embed_tokens().forward(input_ids)?; let input_embeds = Tensor::cat(&[image_features, text_features], 1)?; self.language_model .forward_embeds_without_projection(&input_embeds, None, 0) } pub fn clear_kv_cache(&mut self) { self.pos = 0; self.language_model.clear_kv_cache() } }
candle/candle-transformers/src/models/paligemma.rs/0
{ "file_path": "candle/candle-transformers/src/models/paligemma.rs", "repo_id": "candle", "token_count": 2807 }
60
//! Implementation of a quantized Moondream vision language model. //! //! Moondream is a lightweight vision-language model for image understanding and generation. //! This module provides a quantized version for reduced memory usage and faster inference. //! //! Key features: //! - ViT-based vision encoder //! - Phi-2 text decoder model //! - Memory efficient 8-bit quantization //! - Optimized for efficient deployment //! //! References: //! - [Moondream Model](https://github.com/vikhyat/moondream) //! use crate::models::moondream::{Config, VisionConfig}; use crate::models::quantized_mixformer::MixFormerSequentialForCausalLM as PhiModel; use crate::quantized_nn::{layer_norm, linear_b, Linear}; use crate::quantized_var_builder::VarBuilder; use candle::{IndexOp, Module, Result, Tensor, D}; fn scaled_dot_product_attention(q: &Tensor, k: &Tensor, v: &Tensor) -> Result<Tensor> { let dim = q.dim(D::Minus1)?; let scale_factor = 1.0 / (dim as f64).sqrt(); let attn_weights = (q.matmul(&k.t()?)? * scale_factor)?; candle_nn::ops::softmax_last_dim(&attn_weights)?.matmul(v) } #[derive(Debug, Clone)] struct LinearPatchEmbedding { linear: Linear, } impl LinearPatchEmbedding { fn new(vb: VarBuilder) -> Result<Self> { let linear = linear_b(588, 1152, true, vb.pp("linear"))?; Ok(Self { linear }) } } impl Module for LinearPatchEmbedding { fn forward(&self, xs: &Tensor) -> Result<Tensor> { xs.apply(&self.linear) } } #[derive(Debug, Clone)] struct Attention { num_heads: usize, head_dim: usize, qkv: Linear, proj: Linear, } impl Attention { pub fn new(vb: VarBuilder, dim: usize, num_heads: usize) -> Result<Self> { let qkv = linear_b(dim, dim * 3, true, vb.pp("qkv"))?; let proj = linear_b(dim, dim, true, vb.pp("proj"))?; Ok(Self { num_heads, head_dim: dim / num_heads, qkv, proj, }) } } impl Module for Attention { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let (b, n, c) = xs.dims3()?; let qkv = xs .apply(&self.qkv)? .reshape((b, n, 3, self.num_heads, self.head_dim))? .permute((2, 0, 3, 1, 4))?; let (q, k, v) = ( qkv.i(0)?.contiguous()?, qkv.i(1)?.contiguous()?, qkv.i(2)?.contiguous()?, ); scaled_dot_product_attention(&q, &k, &v)? .transpose(1, 2)? .reshape((b, n, c))? .apply(&self.proj) } } #[derive(Debug, Clone)] struct VitBlock { attn: Attention, mlp: Mlp, norm1: candle_nn::LayerNorm, norm2: candle_nn::LayerNorm, } impl VitBlock { fn new(vb: VarBuilder, dim: usize, num_heads: usize, cfg: &VisionConfig) -> Result<Self> { let attn = Attention::new(vb.pp("attn"), dim, num_heads)?; let mlp = Mlp::new(vb.pp("mlp"), dim, cfg.hidden_features, dim, cfg.act)?; let norm1 = layer_norm(dim, 1e-5, vb.pp("norm1"))?; let norm2 = layer_norm(dim, 1e-5, vb.pp("norm2"))?; Ok(Self { attn, mlp, norm1, norm2, }) } } impl Module for VitBlock { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let ys = xs.apply(&self.norm1)?.apply(&self.attn)?; let xs = (xs + &ys)?; let ys = xs.apply(&self.norm2)?.apply(&self.mlp)?; let xs = (&xs + &ys)?; Ok(xs) } } #[derive(Debug, Clone)] struct VisionTransformer { patch_embed: LinearPatchEmbedding, pos_embed: Tensor, blocks: Vec<VitBlock>, norm: candle_nn::LayerNorm, } impl VisionTransformer { fn new(cfg: &VisionConfig, vb: VarBuilder) -> Result<Self> { let patch_embed = LinearPatchEmbedding::new(vb.pp("patch_embed"))?; let pos_embed = vb .get((1, cfg.embed_len, cfg.embed_dim), "pos_embed")? .dequantize(vb.device())?; let blocks = (0..cfg.num_blocks) .map(|i| { VitBlock::new( vb.pp(format!("blocks.{i}")), cfg.embed_dim, cfg.num_heads, cfg, ) }) .collect::<Result<_>>()?; let norm = layer_norm(cfg.embed_dim, 1e-5, vb.pp("norm"))?; Ok(Self { patch_embed, pos_embed, blocks, norm, }) } } impl Module for VisionTransformer { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let mut xs = (&xs.apply(&self.patch_embed)? + &self.pos_embed)?; for block in self.blocks.iter() { xs = xs.apply(block)?; } xs.apply(&self.norm) } } #[derive(Debug, Clone)] pub struct Encoder { model: VisionTransformer, } impl Encoder { fn new(cfg: &VisionConfig, vb: VarBuilder) -> Result<Self> { let model = VisionTransformer::new(cfg, vb.pp("model.visual"))?; Ok(Self { model }) } } impl Module for Encoder { fn forward(&self, xs: &Tensor) -> Result<Tensor> { xs.apply(&self.model) } } #[derive(Debug, Clone)] struct Mlp { fc1: Linear, act: candle_nn::Activation, fc2: Linear, } impl Mlp { fn new( vb: VarBuilder, in_features: usize, hidden_features: usize, out_features: usize, act: candle_nn::Activation, ) -> Result<Self> { let fc1 = linear_b(in_features, hidden_features, true, vb.pp("fc1"))?; let fc2 = linear_b(hidden_features, out_features, true, vb.pp("fc2"))?; Ok(Self { fc1, act, fc2 }) } } impl Module for Mlp { fn forward(&self, xs: &Tensor) -> Result<Tensor> { xs.apply(&self.fc1)?.apply(&self.act)?.apply(&self.fc2) } } #[derive(Debug, Clone)] struct VisionProjection { mlp: Mlp, } impl VisionProjection { fn new(cfg: &VisionConfig, vb: VarBuilder) -> Result<Self> { let mlp = Mlp::new( vb.pp("mlp"), cfg.image_embedding_dim, cfg.hidden_dim, cfg.model_dim, cfg.act, )?; Ok(Self { mlp }) } } impl Module for VisionProjection { fn forward(&self, xs: &Tensor) -> Result<Tensor> { xs.apply(&self.mlp) } } #[derive(Debug, Clone)] pub struct VisionEncoder { encoder: Encoder, projection: VisionProjection, } impl VisionEncoder { pub fn new(cfg: &VisionConfig, vb: VarBuilder) -> Result<Self> { let encoder = Encoder::new(cfg, vb.pp("encoder"))?; let projection = VisionProjection::new(cfg, vb.pp("projection"))?; Ok(Self { encoder, projection, }) } } impl Module for VisionEncoder { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let (b, c, hp1, wp2) = xs.dims4()?; let (p1, p2) = (14, 14); let h = hp1 / p1; let w = wp2 / p2; xs.reshape((b, c, h, p1, h, p2))? .permute((0, 2, 4, 1, 3, 5))? .reshape((b, h * w, c * p1 * p2))? .apply(&self.encoder)? .apply(&self.projection) } } pub struct Model { pub text_model: PhiModel, pub vision_encoder: VisionEncoder, } impl Model { pub fn new(config: &Config, vb: VarBuilder) -> Result<Self> { let text_model = PhiModel::new_v2(&config.phi_config, vb.pp("text_model"))?; let vision_encoder = VisionEncoder::new(&config.vision_config, vb.pp("vision_encoder"))?; Ok(Self { text_model, vision_encoder, }) } pub fn vision_encoder(&self) -> &VisionEncoder { &self.vision_encoder } pub fn text_model(&mut self) -> &mut PhiModel { &mut self.text_model } }
candle/candle-transformers/src/models/quantized_moondream.rs/0
{ "file_path": "candle/candle-transformers/src/models/quantized_moondream.rs", "repo_id": "candle", "token_count": 3810 }
61
//! RepVGG inference implementation //! //! Key characteristics: //! - Efficient inference architecture through structural reparameterization //! - Single 3x3 conv layer after fusing 3x3 branch, 1x1 branch and identity branch //! - Different configurations including a0-a2, b0-b3 and variants with group convolutions //! - High accuracy with VGG-like plain architecture and training //! //! References: //! - [RepVGG Paper](https://arxiv.org/abs/2101.03697). RepVGG: Making VGG-style ConvNets Great Again //! - [Official Implementation](https://github.com/DingXiaoH/RepVGG) //! use candle::{Result, Tensor, D}; use candle_nn::{ batch_norm, conv2d_no_bias, linear, BatchNorm, Conv2d, Conv2dConfig, Func, VarBuilder, }; const CHANNELS_PER_STAGE: [usize; 5] = [64, 64, 128, 256, 512]; #[derive(Clone)] pub struct Config { a: f32, b: f32, groups: usize, stages: [usize; 4], } impl Config { pub fn a0() -> Self { Self { a: 0.75, b: 2.5, groups: 1, stages: [2, 4, 14, 1], } } pub fn a1() -> Self { Self { a: 1.0, b: 2.5, groups: 1, stages: [2, 4, 14, 1], } } pub fn a2() -> Self { Self { a: 1.5, b: 2.75, groups: 1, stages: [2, 4, 14, 1], } } pub fn b0() -> Self { Self { a: 1.0, b: 2.5, groups: 1, stages: [4, 6, 16, 1], } } pub fn b1() -> Self { Self { a: 2.0, b: 4.0, groups: 1, stages: [4, 6, 16, 1], } } pub fn b2() -> Self { Self { a: 2.5, b: 5.0, groups: 1, stages: [4, 6, 16, 1], } } pub fn b3() -> Self { Self { a: 3.0, b: 5.0, groups: 1, stages: [4, 6, 16, 1], } } pub fn b1g4() -> Self { Self { a: 2.0, b: 4.0, groups: 4, stages: [4, 6, 16, 1], } } pub fn b2g4() -> Self { Self { a: 2.5, b: 5.0, groups: 4, stages: [4, 6, 16, 1], } } pub fn b3g4() -> Self { Self { a: 3.0, b: 5.0, groups: 4, stages: [4, 6, 16, 1], } } } // fuses a convolutional kernel and a batchnorm layer into a convolutional layer // based on the _fuse_bn_tensor method in timm // see https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/byobnet.py#L602 fn fuse_conv_bn(weights: &Tensor, bn: BatchNorm) -> Result<(Tensor, Tensor)> { let (gamma, beta) = bn.weight_and_bias().unwrap(); let mu = bn.running_mean(); let sigma = (bn.running_var() + bn.eps())?.sqrt(); let gps = (gamma / sigma)?; let bias = (beta - mu * &gps)?; let weights = weights.broadcast_mul(&gps.reshape(((), 1, 1, 1))?)?; Ok((weights, bias)) } // A RepVGG layer has a different training time and inference time architecture. // The latter is a simple and efficient equivalent transformation of the former // realized by a structural reparameterization technique, where 3x3 and 1x1 convolutions // along with identity branches and batchnorm layers are fused into a single 3x3 convolution. fn repvgg_layer( has_identity: bool, dim: usize, stride: usize, in_channels: usize, out_channels: usize, groups: usize, vb: VarBuilder, ) -> Result<Func<'static>> { let conv2d_cfg = Conv2dConfig { stride, groups, padding: 1, ..Default::default() }; // read and reparameterize the 1x1 conv and bn into w1 and b1 // based on https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/byobnet.py#L543 let conv1x1_bn = batch_norm(dim, 1e-5, vb.pp("conv_1x1.bn"))?; let conv1x1 = conv2d_no_bias( in_channels, out_channels, 1, conv2d_cfg, vb.pp("conv_1x1.conv"), )?; let (mut w1, b1) = fuse_conv_bn(conv1x1.weight(), conv1x1_bn)?; // resize to 3x3 w1 = w1.pad_with_zeros(D::Minus1, 1, 1)?; w1 = w1.pad_with_zeros(D::Minus2, 1, 1)?; // read and reparameterize the 3x3 conv and bn into w3 and b3 let convkxk_bn = batch_norm(dim, 1e-5, vb.pp("conv_kxk.bn"))?; let conv3x3 = conv2d_no_bias( in_channels, out_channels, 3, conv2d_cfg, vb.pp("conv_kxk.conv"), )?; let (w3, b3) = fuse_conv_bn(conv3x3.weight(), convkxk_bn)?; let mut w = (w1 + w3)?; let mut b = (b1 + b3)?; // read and reparameterize the identity bn into wi and bi if has_identity { let identity_bn = batch_norm(dim, 1e-5, vb.pp("identity"))?; // create a 3x3 convolution equivalent to the identity branch let mut weights: Vec<f32> = vec![0.0; conv3x3.weight().elem_count()]; // https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/byobnet.py#L620 let in_dim = in_channels / groups; for i in 0..in_channels { weights[i * in_dim * 3 * 3 + (i % in_dim) * 3 * 3 + 4] = 1.0; } let weights = &Tensor::from_vec(weights, w.shape(), w.device())?; let (wi, bi) = fuse_conv_bn(weights, identity_bn)?; w = (w + wi)?; b = (b + bi)?; } // create the 3x3 conv equivalent to the sum of 3x3, 1x1 and identity branches let reparam_conv = Conv2d::new(w, Some(b), conv2d_cfg); Ok(Func::new(move |xs| { let xs = xs.apply(&reparam_conv)?.relu()?; Ok(xs) })) } // Get the number of output channels per stage taking into account the multipliers fn output_channels_per_stage(a: f32, b: f32, stage: usize) -> usize { let channels = CHANNELS_PER_STAGE[stage] as f32; match stage { 0 => std::cmp::min(64, (channels * a) as usize), 4 => (channels * b) as usize, _ => (channels * a) as usize, } } // Each stage is made of layers. The first layer always downsamples with stride 2. // All but the first layer have a residual connection. // The G4 variants have a groupwise convolution instead of a dense one on odd layers // counted across stage boundaries, so we keep track of which layer we are in the // full model. fn repvgg_stage(cfg: &Config, idx: usize, vb: VarBuilder) -> Result<Func<'static>> { let nlayers = cfg.stages[idx - 1]; let mut layers = Vec::with_capacity(nlayers); let prev_layers: usize = cfg.stages[..idx - 1].iter().sum(); let out_channels_prev = output_channels_per_stage(cfg.a, cfg.b, idx - 1); let out_channels = output_channels_per_stage(cfg.a, cfg.b, idx); for layer_idx in 0..nlayers { let (has_identity, stride, in_channels) = if layer_idx == 0 { (false, 2, out_channels_prev) } else { (true, 1, out_channels) }; let groups = if (prev_layers + layer_idx) % 2 == 1 { cfg.groups } else { 1 }; layers.push(repvgg_layer( has_identity, out_channels, stride, in_channels, out_channels, groups, vb.pp(layer_idx), )?) } Ok(Func::new(move |xs| { let mut xs = xs.clone(); for layer in layers.iter() { xs = xs.apply(layer)? } Ok(xs) })) } // Build a RepVGG model for a given configuration. fn repvgg_model(config: &Config, nclasses: Option<usize>, vb: VarBuilder) -> Result<Func<'static>> { let cls = match nclasses { None => None, Some(nclasses) => { let outputs = output_channels_per_stage(config.a, config.b, 4); let linear = linear(outputs, nclasses, vb.pp("head.fc"))?; Some(linear) } }; let stem_dim = output_channels_per_stage(config.a, config.b, 0); let stem = repvgg_layer(false, stem_dim, 2, 3, stem_dim, 1, vb.pp("stem"))?; let vb = vb.pp("stages"); let stage1 = repvgg_stage(config, 1, vb.pp(0))?; let stage2 = repvgg_stage(config, 2, vb.pp(1))?; let stage3 = repvgg_stage(config, 3, vb.pp(2))?; let stage4 = repvgg_stage(config, 4, vb.pp(3))?; Ok(Func::new(move |xs| { let xs = xs .apply(&stem)? .apply(&stage1)? .apply(&stage2)? .apply(&stage3)? .apply(&stage4)? .mean(D::Minus1)? .mean(D::Minus1)?; match &cls { None => Ok(xs), Some(cls) => xs.apply(cls), } })) } pub fn repvgg(cfg: &Config, nclasses: usize, vb: VarBuilder) -> Result<Func<'static>> { repvgg_model(cfg, Some(nclasses), vb) } pub fn repvgg_no_final_layer(cfg: &Config, vb: VarBuilder) -> Result<Func<'static>> { repvgg_model(cfg, None, vb) }
candle/candle-transformers/src/models/repvgg.rs/0
{ "file_path": "candle/candle-transformers/src/models/repvgg.rs", "repo_id": "candle", "token_count": 4487 }
62