text
stringlengths
5
631k
id
stringlengths
14
178
metadata
dict
__index_level_0__
int64
0
647
# Copyright 2024 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 Qwen2Audio model.""" import tempfile import unittest from io import BytesIO from urllib.request import urlopen import librosa import pytest from transformers import ( AutoProcessor, Qwen2AudioConfig, Qwen2AudioForConditionalGeneration, is_torch_available, ) from transformers.testing_utils import ( cleanup, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor if is_torch_available(): import torch class Qwen2AudioModelTester: def __init__( self, parent, ignore_index=-100, audio_token_index=0, seq_length=25, feat_seq_length=60, text_config={ "model_type": "qwen2", "intermediate_size": 36, "initializer_range": 0.02, "hidden_size": 32, "max_position_embeddings": 52, "num_hidden_layers": 2, "num_attention_heads": 4, "num_key_value_heads": 2, "use_labels": True, "use_mrope": False, "vocab_size": 99, }, is_training=True, audio_config={ "model_type": "qwen2_audio_encoder", "d_model": 16, "encoder_attention_heads": 4, "encoder_ffn_dim": 16, "encoder_layers": 2, "num_mel_bins": 80, "max_source_positions": 30, "initializer_range": 0.02, }, ): self.parent = parent self.ignore_index = ignore_index self.audio_token_index = audio_token_index self.text_config = text_config self.audio_config = audio_config self.seq_length = seq_length self.feat_seq_length = feat_seq_length self.num_hidden_layers = text_config["num_hidden_layers"] self.vocab_size = text_config["vocab_size"] self.hidden_size = text_config["hidden_size"] self.num_attention_heads = text_config["num_attention_heads"] self.is_training = is_training self.batch_size = 3 self.encoder_seq_length = seq_length def get_config(self): return Qwen2AudioConfig( text_config=self.text_config, audio_config=self.audio_config, ignore_index=self.ignore_index, audio_token_index=self.audio_token_index, ) def prepare_config_and_inputs(self): input_features_values = floats_tensor( [ self.batch_size, self.audio_config["num_mel_bins"], self.feat_seq_length, ] ) config = self.get_config() feature_attention_mask = torch.ones([self.batch_size, self.feat_seq_length], dtype=torch.long).to(torch_device) return config, input_features_values, feature_attention_mask def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, input_features_values, feature_attention_mask = config_and_inputs input_length = (input_features_values.shape[-1] - 1) // 2 + 1 num_audio_tokens = (input_length - 2) // 2 + 1 input_ids = ids_tensor([self.batch_size, self.seq_length], config.text_config.vocab_size - 1) + 1 attention_mask = torch.ones(input_ids.shape, dtype=torch.long).to(torch_device) attention_mask[:, :1] = 0 # we are giving 3 audios let's make sure we pass in 3 audios tokens input_ids[:, 1 : 1 + num_audio_tokens] = config.audio_token_index inputs_dict = { "input_features": input_features_values, "feature_attention_mask": feature_attention_mask, "input_ids": input_ids, "attention_mask": attention_mask, } return config, inputs_dict @require_torch class Qwen2AudioForConditionalGenerationModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase): """ Model tester for `Qwen2AudioForConditionalGeneration`. """ all_model_classes = (Qwen2AudioForConditionalGeneration,) if is_torch_available() else () test_pruning = False test_head_masking = False _is_composite = True def setUp(self): self.model_tester = Qwen2AudioModelTester(self) self.config_tester = ConfigTester(self, config_class=Qwen2AudioConfig, has_text_modality=False) @unittest.skip(reason="Compile not yet supported because in Qwen2Audio models") @pytest.mark.torch_compile_test def test_sdpa_can_compile_dynamic(self): pass @unittest.skip(reason="Compile not yet supported because in Qwen2Audio models") def test_sdpa_can_dispatch_on_flash(self): pass @unittest.skip(reason="Qwen2 Audio does not support right padding.") def test_flash_attn_2_inference_equivalence_right_padding(self): pass def test_sdpa_can_dispatch_composite_models(self): # overwrite because Qwen2 is audio+text model (not vision+text) if not self.has_attentions: self.skipTest(reason="Model architecture does not support attentions") if not self._is_composite: self.skipTest(f"{self.all_model_classes[0].__name__} does not support SDPA") for model_class in self.all_model_classes: config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() model = model_class(config) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(tmpdirname) model_sdpa = model_class.from_pretrained(tmpdirname) model_sdpa = model_sdpa.eval().to(torch_device) text_attn = "sdpa" if model.language_model._supports_sdpa else "eager" vision_attn = "sdpa" if model.audio_tower._supports_sdpa else "eager" # `None` as it is the requested one which will be assigned to each sub-config # Sub-model will dispatch to SDPA if it can (checked below that `SDPA` layers are present) self.assertTrue(model_sdpa.config._attn_implementation == "sdpa") self.assertTrue(model.language_model.config._attn_implementation == text_attn) self.assertTrue(model.audio_tower.config._attn_implementation == vision_attn) model_eager = model_class.from_pretrained(tmpdirname, attn_implementation="eager") model_eager = model_eager.eval().to(torch_device) self.assertTrue(model_eager.config._attn_implementation == "eager") self.assertTrue(model_eager.language_model.config._attn_implementation == "eager") self.assertTrue(model_eager.audio_tower.config._attn_implementation == "eager") for name, submodule in model_eager.named_modules(): class_name = submodule.__class__.__name__ if "SdpaAttention" in class_name or "SdpaSelfAttention" in class_name: raise ValueError("The eager model should not have SDPA attention layers") @require_torch class Qwen2AudioForConditionalGenerationIntegrationTest(unittest.TestCase): def setUp(self): self.processor = AutoProcessor.from_pretrained("Qwen/Qwen2-Audio-7B-Instruct") def tearDown(self): cleanup(torch_device, gc_collect=True) @slow def test_small_model_integration_test_single(self): # Let' s make sure we test the preprocessing to replace what is used model = Qwen2AudioForConditionalGeneration.from_pretrained("Qwen/Qwen2-Audio-7B-Instruct") url = "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/glass-breaking-151256.mp3" messages = [ { "role": "user", "content": [ {"type": "audio", "audio_url": url}, {"type": "text", "text": "What's that sound?"}, ], } ] raw_audio, _ = librosa.load(BytesIO(urlopen(url).read()), sr=self.processor.feature_extractor.sampling_rate) formatted_prompt = self.processor.apply_chat_template(messages, add_generation_prompt=True) inputs = self.processor(text=formatted_prompt, audios=[raw_audio], return_tensors="pt", padding=True) output = model.generate(**inputs, max_new_tokens=32) # fmt: off EXPECTED_INPUT_IDS = torch.tensor([[ 151644, 8948, 198, 2610, 525, 264, 10950, 17847, 13, 151645, 198, 151644, 872, 198, 14755, 220, 16, 25, 220, 151647, *[151646] * 101, 151648, 198, 3838, 594, 429, 5112, 30, 151645, 198, 151644, 77091, 198, ]]) # fmt: on self.assertTrue(torch.equal(inputs["input_ids"], EXPECTED_INPUT_IDS)) EXPECTED_DECODED_TEXT = ( "<|im_start|>system\nYou are a helpful assistant.<|im_end|>\n<|im_start|>user\nAudio 1: <|audio_bos|>" + "<|AUDIO|>" * 101 + "<|audio_eos|>\nWhat's that sound?<|im_end|>\n<|im_start|>assistant\nIt is the sound of glass breaking.<|im_end|>" ) self.assertEqual( self.processor.decode(output[0], skip_special_tokens=False), EXPECTED_DECODED_TEXT, ) # test the error when incorrect number of audio tokens # fmt: off inputs["input_ids"] = torch.tensor([[ 151644, 8948, 198, 2610, 525, 264, 10950, 17847, 13, 151645, 198, 151644, 872, 198, 14755, 220, 16, 25, 220, 151647, *[151646] * 200, 151648, 198, 3838, 594, 429, 5112, 30, 151645, 198, 151644, 77091, 198, ]]) # fmt: on with self.assertRaisesRegex( ValueError, "Audio features and audio tokens do not match: tokens: 200, features 101" ): model.generate(**inputs, max_new_tokens=32) @slow def test_small_model_integration_test_batch(self): # Let' s make sure we test the preprocessing to replace what is used model = Qwen2AudioForConditionalGeneration.from_pretrained("Qwen/Qwen2-Audio-7B-Instruct") conversation1 = [ { "role": "user", "content": [ { "type": "audio", "audio_url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/glass-breaking-151256.mp3", }, {"type": "text", "text": "What's that sound?"}, ], }, {"role": "assistant", "content": "It is the sound of glass shattering."}, { "role": "user", "content": [ { "type": "audio", "audio_url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/f2641_0_throatclearing.wav", }, {"type": "text", "text": "What can you hear?"}, ], }, ] conversation2 = [ { "role": "user", "content": [ { "type": "audio", "audio_url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/1272-128104-0000.flac", }, {"type": "text", "text": "What does the person say?"}, ], }, ] conversations = [conversation1, conversation2] text = [ self.processor.apply_chat_template(conversation, add_generation_prompt=True, tokenize=False) for conversation in conversations ] audios = [] for conversation in conversations: for message in conversation: if isinstance(message["content"], list): for ele in message["content"]: if ele["type"] == "audio": audios.append( librosa.load( BytesIO(urlopen(ele["audio_url"]).read()), sr=self.processor.feature_extractor.sampling_rate, )[0] ) inputs = self.processor(text=text, audios=audios, return_tensors="pt", padding=True) output = model.generate(**inputs, max_new_tokens=32) EXPECTED_DECODED_TEXT = [ "system\nYou are a helpful assistant.\nuser\nAudio 1: \nWhat's that sound?\nassistant\nIt is the sound of glass shattering.\nuser\nAudio 2: \nWhat can you hear?\nassistant\ncough and throat clearing.", "system\nYou are a helpful assistant.\nuser\nAudio 1: \nWhat does the person say?\nassistant\nThe original content of this audio is: 'Mister Quiller is the apostle of the middle classes and we are glad to welcome his gospel.'", ] self.assertEqual( self.processor.batch_decode(output, skip_special_tokens=True), EXPECTED_DECODED_TEXT, ) @slow def test_small_model_integration_test_multiturn(self): # Let' s make sure we test the preprocessing to replace what is used model = Qwen2AudioForConditionalGeneration.from_pretrained("Qwen/Qwen2-Audio-7B-Instruct") messages = [ {"role": "system", "content": "You are a helpful assistant."}, { "role": "user", "content": [ { "type": "audio", "audio_url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/glass-breaking-151256.mp3", }, {"type": "text", "text": "What's that sound?"}, ], }, {"role": "assistant", "content": "It is the sound of glass shattering."}, { "role": "user", "content": [ { "type": "audio", "audio_url": "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/f2641_0_throatclearing.wav", }, {"type": "text", "text": "How about this one?"}, ], }, ] formatted_prompt = self.processor.apply_chat_template(messages, add_generation_prompt=True) audios = [] for message in messages: if isinstance(message["content"], list): for ele in message["content"]: if ele["type"] == "audio": audios.append( librosa.load( BytesIO(urlopen(ele["audio_url"]).read()), sr=self.processor.feature_extractor.sampling_rate, )[0] ) inputs = self.processor(text=formatted_prompt, audios=audios, return_tensors="pt", padding=True) output = model.generate(**inputs, max_new_tokens=32, top_k=1) EXPECTED_DECODED_TEXT = [ "system\nYou are a helpful assistant.\nuser\nAudio 1: \nWhat's that sound?\nassistant\nIt is the sound of glass shattering.\nuser\nAudio 2: \nHow about this one?\nassistant\nThroat clearing.", ] self.assertEqual( self.processor.batch_decode(output, skip_special_tokens=True), EXPECTED_DECODED_TEXT, )
transformers/tests/models/qwen2_audio/test_modeling_qwen2_audio.py/0
{ "file_path": "transformers/tests/models/qwen2_audio/test_modeling_qwen2_audio.py", "repo_id": "transformers", "token_count": 7775 }
566
# 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 json import os import shutil import tempfile from unittest import TestCase from transformers import BartTokenizer, BartTokenizerFast, DPRQuestionEncoderTokenizer, DPRQuestionEncoderTokenizerFast from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES from transformers.models.dpr.configuration_dpr import DPRConfig from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES from transformers.testing_utils import require_faiss, require_tokenizers, require_torch, slow from transformers.utils import is_datasets_available, is_faiss_available, is_torch_available if is_torch_available() and is_datasets_available() and is_faiss_available(): from transformers.models.rag.configuration_rag import RagConfig from transformers.models.rag.tokenization_rag import RagTokenizer @require_faiss @require_torch class RagTokenizerTest(TestCase): def setUp(self): self.tmpdirname = tempfile.mkdtemp() self.retrieval_vector_size = 8 # DPR tok vocab_tokens = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] dpr_tokenizer_path = os.path.join(self.tmpdirname, "dpr_tokenizer") os.makedirs(dpr_tokenizer_path, exist_ok=True) self.vocab_file = os.path.join(dpr_tokenizer_path, DPR_VOCAB_FILES_NAMES["vocab_file"]) with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) # BART tok vocab = [ "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "\u0120", "\u0120l", "\u0120n", "\u0120lo", "\u0120low", "er", "\u0120lowest", "\u0120newer", "\u0120wider", "<unk>", ] vocab_tokens = dict(zip(vocab, range(len(vocab)))) merges = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""] self.special_tokens_map = {"unk_token": "<unk>"} bart_tokenizer_path = os.path.join(self.tmpdirname, "bart_tokenizer") os.makedirs(bart_tokenizer_path, exist_ok=True) self.vocab_file = os.path.join(bart_tokenizer_path, BART_VOCAB_FILES_NAMES["vocab_file"]) self.merges_file = os.path.join(bart_tokenizer_path, BART_VOCAB_FILES_NAMES["merges_file"]) with open(self.vocab_file, "w", encoding="utf-8") as fp: fp.write(json.dumps(vocab_tokens) + "\n") with open(self.merges_file, "w", encoding="utf-8") as fp: fp.write("\n".join(merges)) def get_dpr_tokenizer(self) -> DPRQuestionEncoderTokenizer: return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname, "dpr_tokenizer")) def get_bart_tokenizer(self) -> BartTokenizer: return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname, "bart_tokenizer")) def tearDown(self): shutil.rmtree(self.tmpdirname) @require_tokenizers def test_save_load_pretrained_with_saved_config(self): save_dir = os.path.join(self.tmpdirname, "rag_tokenizer") rag_config = RagConfig(question_encoder=DPRConfig().to_dict(), generator=BartConfig().to_dict()) rag_tokenizer = RagTokenizer(question_encoder=self.get_dpr_tokenizer(), generator=self.get_bart_tokenizer()) rag_config.save_pretrained(save_dir) rag_tokenizer.save_pretrained(save_dir) new_rag_tokenizer = RagTokenizer.from_pretrained(save_dir, config=rag_config) self.assertIsInstance(new_rag_tokenizer.question_encoder, DPRQuestionEncoderTokenizerFast) self.assertEqual(new_rag_tokenizer.question_encoder.get_vocab(), rag_tokenizer.question_encoder.get_vocab()) self.assertIsInstance(new_rag_tokenizer.generator, BartTokenizerFast) self.assertEqual(new_rag_tokenizer.generator.get_vocab(), rag_tokenizer.generator.get_vocab()) @slow def test_pretrained_token_nq_tokenizer(self): tokenizer = RagTokenizer.from_pretrained("facebook/rag-token-nq") input_strings = [ "who got the first nobel prize in physics", "when is the next deadpool movie being released", "which mode is used for short wave broadcast service", "who is the owner of reading football club", "when is the next scandal episode coming out", "when is the last time the philadelphia won the superbowl", "what is the most current adobe flash player version", "how many episodes are there in dragon ball z", "what is the first step in the evolution of the eye", "where is gall bladder situated in human body", "what is the main mineral in lithium batteries", "who is the president of usa right now", "where do the greasers live in the outsiders", "panda is a national animal of which country", "what is the name of manchester united stadium", ] input_dict = tokenizer(input_strings) self.assertIsNotNone(input_dict) @slow def test_pretrained_sequence_nq_tokenizer(self): tokenizer = RagTokenizer.from_pretrained("facebook/rag-sequence-nq") input_strings = [ "who got the first nobel prize in physics", "when is the next deadpool movie being released", "which mode is used for short wave broadcast service", "who is the owner of reading football club", "when is the next scandal episode coming out", "when is the last time the philadelphia won the superbowl", "what is the most current adobe flash player version", "how many episodes are there in dragon ball z", "what is the first step in the evolution of the eye", "where is gall bladder situated in human body", "what is the main mineral in lithium batteries", "who is the president of usa right now", "where do the greasers live in the outsiders", "panda is a national animal of which country", "what is the name of manchester united stadium", ] input_dict = tokenizer(input_strings) self.assertIsNotNone(input_dict)
transformers/tests/models/rag/test_tokenization_rag.py/0
{ "file_path": "transformers/tests/models/rag/test_tokenization_rag.py", "repo_id": "transformers", "token_count": 3143 }
567
# Copyright 2023 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 SeamlessM4T model.""" import copy import tempfile import unittest from transformers import SeamlessM4TConfig, is_speech_available, is_torch_available from transformers.testing_utils import require_speech, require_torch, slow, torch_device from transformers.trainer_utils import set_seed from transformers.utils import cached_property 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 ( SeamlessM4TForSpeechToSpeech, SeamlessM4TForSpeechToText, SeamlessM4TForTextToSpeech, SeamlessM4TForTextToText, SeamlessM4TModel, ) if is_speech_available(): from transformers import SeamlessM4TProcessor class SeamlessM4TModelTester: def __init__( self, parent, input_modality="speech", batch_size=2, seq_length=4, is_training=True, use_input_mask=True, use_token_type_ids=True, use_labels=True, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, initializer_range=0.02, max_new_tokens=None, num_labels=3, num_choices=4, scope=None, vocab_size=20, t2u_vocab_size=20, hidden_size=6, num_hidden_layers=2, intermediate_size=6, max_position_embeddings=256, encoder_layers=2, decoder_layers=2, encoder_ffn_dim=6, decoder_ffn_dim=6, t2u_encoder_layers=2, t2u_decoder_layers=2, t2u_encoder_ffn_dim=6, t2u_decoder_ffn_dim=6, num_heads=2, vocoder_num_spkrs=5, vocoder_num_langs=5, upsample_initial_channel=32, unit_embed_dim=25, spkr_embed_dim=6, lang_embed_dim=6, num_conv_pos_embeddings=8, unit_hifi_gan_vocab_size=20, t2u_num_langs=0, t2u_max_new_tokens=25, t2u_offset_tgt_lang=0, vocoder_offset=0, ): self.parent = parent self.input_modality = input_modality 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.hidden_act = hidden_act self.hidden_dropout_prob = hidden_dropout_prob self.attention_probs_dropout_prob = attention_probs_dropout_prob self.initializer_range = initializer_range self.num_labels = num_labels self.num_choices = num_choices self.scope = scope self.vocab_size = vocab_size self.t2u_vocab_size = t2u_vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.intermediate_size = intermediate_size self.max_position_embeddings = max_position_embeddings self.encoder_layers = encoder_layers self.decoder_layers = decoder_layers self.encoder_ffn_dim = encoder_ffn_dim self.decoder_ffn_dim = decoder_ffn_dim self.t2u_encoder_layers = t2u_encoder_layers self.t2u_decoder_layers = t2u_decoder_layers self.t2u_encoder_ffn_dim = t2u_encoder_ffn_dim self.t2u_decoder_ffn_dim = t2u_decoder_ffn_dim self.num_heads = num_heads self.num_attention_heads = num_heads self.vocoder_num_spkrs = vocoder_num_spkrs self.vocoder_num_langs = vocoder_num_langs self.upsample_initial_channel = upsample_initial_channel self.unit_embed_dim = unit_embed_dim self.spkr_embed_dim = spkr_embed_dim self.num_conv_pos_embeddings = num_conv_pos_embeddings self.lang_embed_dim = lang_embed_dim self.max_new_tokens = max_new_tokens self.unit_hifi_gan_vocab_size = unit_hifi_gan_vocab_size self.t2u_num_langs = t2u_num_langs self.t2u_max_new_tokens = t2u_max_new_tokens self.t2u_offset_tgt_lang = t2u_offset_tgt_lang self.vocoder_offset = vocoder_offset def prepare_config_and_inputs(self): if self.input_modality == "text": inputs = ids_tensor([self.batch_size, self.seq_length], self.vocab_size - 1) else: inputs = ids_tensor([self.batch_size, self.seq_length, 160], self.vocab_size - 1).float() input_mask = None if self.use_input_mask: input_mask = random_attention_mask([self.batch_size, self.seq_length]) decoder_input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size - 1) lm_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) config = self.get_config() return config, inputs, decoder_input_ids, input_mask, lm_labels def get_config(self): return SeamlessM4TConfig( hidden_act=self.hidden_act, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, initializer_range=self.initializer_range, vocab_size=self.vocab_size, t2u_vocab_size=self.t2u_vocab_size, hidden_size=self.hidden_size, speech_encoder_layers=self.num_heads, speech_encoder_intermediate_size=self.intermediate_size, max_position_embeddings=self.max_position_embeddings, encoder_layers=self.encoder_layers, decoder_layers=self.decoder_layers, encoder_ffn_dim=self.encoder_ffn_dim, decoder_ffn_dim=self.decoder_ffn_dim, t2u_encoder_layers=self.t2u_encoder_layers, t2u_decoder_layers=self.t2u_decoder_layers, t2u_encoder_ffn_dim=self.t2u_encoder_ffn_dim, t2u_decoder_ffn_dim=self.t2u_decoder_ffn_dim, num_attention_heads=self.num_heads, encoder_attention_heads=self.num_heads, decoder_attention_heads=self.num_heads, t2u_encoder_attention_heads=self.num_heads, t2u_decoder_attention_heads=self.num_heads, speech_encoder_attention_heads=self.num_heads, unit_hifigan_vocab_vise=self.t2u_vocab_size, vocoder_num_spkrs=self.vocoder_num_spkrs, vocoder_num_langs=self.vocoder_num_langs, upsample_initial_channel=self.upsample_initial_channel, unit_embed_dim=self.unit_embed_dim, spkr_embed_dim=self.spkr_embed_dim, num_conv_pos_embeddings=self.num_conv_pos_embeddings, lang_embed_dim=self.lang_embed_dim, max_new_tokens=self.max_new_tokens, unit_hifi_gan_vocab_size=self.unit_hifi_gan_vocab_size, t2u_num_langs=self.t2u_num_langs, t2u_max_new_tokens=self.t2u_max_new_tokens, t2u_offset_tgt_lang=self.t2u_offset_tgt_lang, vocoder_offset=self.vocoder_offset, ) def prepare_config_and_inputs_for_decoder(self): ( config, input_ids, decoder_input_ids, input_mask, lm_labels, ) = self.prepare_config_and_inputs() config.is_decoder = True encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size]) encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2) return ( config, input_ids, decoder_input_ids, input_mask, lm_labels, encoder_hidden_states, encoder_attention_mask, ) def create_and_check_model(self, config, input_ids, decoder_input_ids, input_mask, labels): model = SeamlessM4TModel(config=config) model.to(torch_device) model.eval() if self.input_modality == "text": result = model(input_ids=input_ids, attention_mask=input_mask, decoder_input_ids=decoder_input_ids) result = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) else: result = model(input_features=input_ids, attention_mask=input_mask, decoder_input_ids=decoder_input_ids) result = model(input_features=input_ids, decoder_input_ids=decoder_input_ids) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) decoder_output = result.logits decoder_past = result.past_key_values encoder_output = result.encoder_last_hidden_state if self.input_modality == "text": seq_length = self.seq_length else: # if speech, expected length has been subsampled. seq_length = model._compute_sub_sample_lengths_from_attention_mask(input_mask).max().item() self.parent.assertEqual(encoder_output.size(), (self.batch_size, seq_length, self.hidden_size)) self.parent.assertEqual(decoder_output.size(), (self.batch_size, decoder_input_ids.shape[1], self.vocab_size)) # There should be `num_layers` key value embeddings stored in decoder_past self.parent.assertEqual(len(decoder_past), config.decoder_layers) # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple self.parent.assertEqual(len(decoder_past[0]), 4) def create_and_check_decoder_model_past_large_inputs( self, config, input_ids, decoder_input_ids, input_mask, lm_labels, encoder_hidden_states, encoder_attention_mask, ): config.is_decoder = True model = SeamlessM4TModel(config=config) model.to(torch_device) model.eval() # make sure no pad token in decoder_input_ids decoder_input_ids = torch.clamp(decoder_input_ids, config.pad_token_id + 1) # first forward pass outputs = model( input_ids, decoder_input_ids=decoder_input_ids, decoder_attention_mask=input_mask, use_cache=True ) past_key_values = outputs.past_key_values # create hypothetical multiple next token and extent to next_input_ids next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size) next_mask = ids_tensor((self.batch_size, 3), vocab_size=2) # append to next input_ids and next_input_ids = torch.cat([decoder_input_ids, next_tokens], dim=-1) next_attention_mask = torch.cat([input_mask, next_mask], dim=-1) output_from_no_past = model( input_ids, decoder_input_ids=next_input_ids, decoder_attention_mask=next_attention_mask, output_hidden_states=True, ) output_from_no_past = output_from_no_past["decoder_hidden_states"][0] output_from_past = model( input_ids, decoder_input_ids=next_tokens, decoder_attention_mask=next_attention_mask, past_key_values=past_key_values, output_hidden_states=True, )["decoder_hidden_states"][0] # select random slice random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item() output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach() output_from_past_slice = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]) # test that outputs are equal for slice self.parent.assertTrue(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, decoder_input_ids, input_mask, lm_labels, ) = config_and_inputs input_name = "input_ids" if self.input_modality == "text" else "input_features" inputs_dict = { input_name: input_ids, "attention_mask": input_mask, "decoder_input_ids": decoder_input_ids, "labels": lm_labels, } return config, inputs_dict @require_torch class SeamlessM4TModelWithSpeechInputTest(ModelTesterMixin, unittest.TestCase): is_encoder_decoder = True fx_compatible = False test_missing_keys = False test_pruning = False test_model_parallel = False test_resize_embeddings = False test_headmasking = False test_torchscript = False all_model_classes = ( ( SeamlessM4TModel, SeamlessM4TForSpeechToSpeech, SeamlessM4TForSpeechToText, ) if is_torch_available() else () ) # Doesn't run generation tests. Custom generation method with a different interface all_generative_model_classes = () def setUp(self): self.model_tester = SeamlessM4TModelTester(self, input_modality="speech") self.config_tester = ConfigTester(self, config_class=SeamlessM4TConfig) 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) @slow def test_model_from_pretrained(self): model_name = "facebook/hf-seamless-m4t-medium" model = SeamlessM4TModel.from_pretrained(model_name) self.assertIsNotNone(model) 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", "masked_spec_embed", "codevectors", "quantizer.weight_proj.weight", "project_hid.weight", "project_hid.bias", "project_q.weight", "project_q.bias", "pos_bias_v", "pos_bias_u", "pointwise_conv1", "pointwise_conv2", "feature_projection.projection.weight", "feature_projection.projection.bias", "objective.weight", "adapter", ] 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", ) @unittest.skip(reason="SeamlessM4TSpeechEncoder doesn't have an embedding layer") def test_inputs_embeds(self): pass @unittest.skip(reason="SeamlessM4TSpeechEncoder doesn't have an embedding layer") def test_inputs_embeds_matches_input_ids(self): pass @unittest.skip( reason="Expected missing keys serve when using SeamlessM4TForXXX.from_pretrained from a checkpoint saved by SeamlessM4TModel.save_pretrained." ) def test_model_weights_reload_no_missing_tied_weights(self): pass @unittest.skip(reason="SeamlessM4TModel can takes input_ids or input_features") def test_forward_signature(self): pass @unittest.skip( reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" ) def test_training_gradient_checkpointing(self): pass @unittest.skip( reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" ) def test_training_gradient_checkpointing_use_reentrant(self): pass @unittest.skip( reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" ) def test_training_gradient_checkpointing_use_reentrant_false(self): pass @unittest.skip( reason="This architecture has tied weights by default and there is no way to remove it, check: https://github.com/huggingface/transformers/pull/31771#issuecomment-2210915245" ) def test_load_save_without_tied_weights(self): pass def test_attention_outputs(self): # expected length is subsampled so need to change a bit this test if not self.has_attentions: self.skipTest(reason="Model does not output attentions") config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() config.return_dict = True seq_len = getattr(self.model_tester, "seq_length", None) decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", seq_len) encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", seq_len) decoder_key_length = getattr(self.model_tester, "decoder_key_length", decoder_seq_length) encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length) # no more chunk_length test for model_class in self.all_model_classes: inputs_dict["output_attentions"] = True inputs_dict["output_hidden_states"] = False config.return_dict = True model = model_class._from_config(config, attn_implementation="eager") config = model.config model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) # check that output_attentions also work using config del inputs_dict["output_attentions"] config.output_attentions = True model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) self.assertListEqual( list(attentions[0].shape[-3:]), [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length], ) out_len = len(outputs) if self.is_encoder_decoder: correct_outlen = 5 # loss is at first position if "labels" in inputs_dict: correct_outlen += 1 # loss is added to beginning if "past_key_values" in outputs: correct_outlen += 1 # past_key_values have been returned self.assertEqual(out_len, correct_outlen) # decoder attentions decoder_attentions = outputs.decoder_attentions self.assertIsInstance(decoder_attentions, (list, tuple)) self.assertEqual(len(decoder_attentions), self.model_tester.num_hidden_layers) self.assertListEqual( list(decoder_attentions[0].shape[-3:]), [self.model_tester.num_attention_heads, decoder_seq_length, decoder_key_length], ) # cross attentions cross_attentions = outputs.cross_attentions self.assertIsInstance(cross_attentions, (list, tuple)) self.assertEqual(len(cross_attentions), self.model_tester.num_hidden_layers) sub_sampled_length = ( model._compute_sub_sample_lengths_from_attention_mask(inputs_dict["attention_mask"]).max().item() ) self.assertListEqual( list(cross_attentions[0].shape[-3:]), [ self.model_tester.num_attention_heads, decoder_seq_length, sub_sampled_length, ], ) # Check attention is always last and order is fine inputs_dict["output_attentions"] = True inputs_dict["output_hidden_states"] = True model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) if hasattr(self.model_tester, "num_hidden_states_types"): added_hidden_states = self.model_tester.num_hidden_states_types elif self.is_encoder_decoder: added_hidden_states = 2 else: added_hidden_states = 1 self.assertEqual(out_len + added_hidden_states, len(outputs)) self_attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers) self.assertListEqual( list(self_attentions[0].shape[-3:]), [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length], ) def test_retain_grad_hidden_states_attentions(self): # When training the model, the first speech encoder layer is sometimes skipped. # Setting the seed to always have the first layer. set_seed(0) super().test_retain_grad_hidden_states_attentions() @require_torch class SeamlessM4TModelWithTextInputTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): is_encoder_decoder = True fx_compatible = False test_missing_keys = False test_pruning = False test_model_parallel = False test_resize_embeddings = True test_headmasking = False test_torchscript = False all_model_classes = ( ( SeamlessM4TModel, SeamlessM4TForTextToSpeech, SeamlessM4TForTextToText, ) if is_torch_available() else () ) # Doesn't run generation tests. Has custom generation method with a different interface all_generative_model_classes = () pipeline_model_mapping = ( { "automatic-speech-recognition": SeamlessM4TForSpeechToText, "feature-extraction": SeamlessM4TModel, "summarization": SeamlessM4TForTextToText, "text-to-audio": SeamlessM4TForTextToSpeech, "text2text-generation": SeamlessM4TForTextToText, "translation": SeamlessM4TForTextToText, } if is_torch_available() else {} ) def setUp(self): self.model_tester = SeamlessM4TModelTester(self, input_modality="text") self.config_tester = ConfigTester(self, config_class=SeamlessM4TConfig) 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) @slow def test_model_from_pretrained(self): model_name = "facebook/hf-seamless-m4t-medium" model = SeamlessM4TModel.from_pretrained(model_name) self.assertIsNotNone(model) 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", "masked_spec_embed", "codevectors", "quantizer.weight_proj.weight", "project_hid.weight", "project_hid.bias", "project_q.weight", "project_q.bias", "pos_bias_v", "pos_bias_u", "pointwise_conv1", "pointwise_conv2", "feature_projection.projection.weight", "feature_projection.projection.bias", "objective.weight", "adapter", ] 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", ) @unittest.skip( reason="Expected missing keys serve when using SeamlessM4TForXXX.from_pretrained from a checkpoint saved by SeamlessM4TModel.save_pretrained." ) def test_model_weights_reload_no_missing_tied_weights(self): pass @unittest.skip(reason="SeamlessM4TModel can take input_ids or input_features") def test_forward_signature(self): pass def test_decoder_model_past_with_large_inputs(self): config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder() self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs) @unittest.skip( reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" ) def test_training_gradient_checkpointing(self): pass @unittest.skip( reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" ) def test_training_gradient_checkpointing_use_reentrant(self): pass @unittest.skip( reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" ) def test_training_gradient_checkpointing_use_reentrant_false(self): pass @unittest.skip( reason="In training model, the first encoder layer is sometimes skipped. Training is not supported yet, so the test is ignored." ) def test_retain_grad_hidden_states_attentions(self): pass @unittest.skip( reason="This architecture has tied weights by default and there is no way to remove it, check: https://github.com/huggingface/transformers/pull/31771#issuecomment-2210915245" ) def test_load_save_without_tied_weights(self): pass @require_torch class SeamlessM4TGenerationTest(unittest.TestCase): # test that non-standard generation works # test generation of: SeamlessM4TModel, SeamlessM4TForSpeechToSpeech, SeamlessM4TForSpeechToText, SeamlessM4TForTextToSpeech def setUp(self): self.speech_model_tester = SeamlessM4TModelTester(self, input_modality="speech") self.text_model_tester = SeamlessM4TModelTester(self, input_modality="text") self.tmpdirname = tempfile.mkdtemp() def update_generation(self, model): lang_code_to_id = { "fra": 4, "eng": 4, } generation_config = copy.deepcopy(model.generation_config) generation_config.__setattr__("text_decoder_lang_to_code_id", lang_code_to_id) generation_config.__setattr__("t2u_lang_code_to_id", lang_code_to_id) generation_config.__setattr__("vocoder_lang_code_to_id", lang_code_to_id) generation_config._from_model_config = False model.generation_config = generation_config def prepare_text_input(self): config, inputs, decoder_input_ids, input_mask, lm_labels = self.text_model_tester.prepare_config_and_inputs() input_dict = { "input_ids": inputs, "attention_mask": input_mask, "tgt_lang": "eng", "num_beams": 2, "do_sample": True, } return config, input_dict def prepare_speech_input(self): config, inputs, decoder_input_ids, input_mask, lm_labels = self.speech_model_tester.prepare_config_and_inputs() input_dict = { "input_features": inputs, "attention_mask": input_mask, "tgt_lang": "fra", "num_beams": 2, "do_sample": True, } return config, input_dict def prepare_speech_and_text_input(self): config, inputs, decoder_input_ids, input_mask, lm_labels = self.speech_model_tester.prepare_config_and_inputs() input_speech = { "input_features": inputs, "attention_mask": input_mask, "tgt_lang": "fra", "num_beams": 2, "do_sample": True, } config, inputs, decoder_input_ids, input_mask, lm_labels = self.text_model_tester.prepare_config_and_inputs() input_text = { "input_ids": inputs, "attention_mask": input_mask, "tgt_lang": "eng", "num_beams": 2, "do_sample": True, } return config, input_speech, input_text def factory_generation_speech_test(self, model, inputs): set_seed(0) output = model.generate(**inputs) return output def test_speech_generation(self): config, input_speech, input_text = self.prepare_speech_and_text_input() model = SeamlessM4TModel(config=config) self.update_generation(model) model.save_pretrained(self.tmpdirname) model.to(torch_device) model.eval() output_original_text = self.factory_generation_speech_test(model, input_text) output_original_speech = self.factory_generation_speech_test(model, input_speech) state_dict = model.state_dict() text_model = SeamlessM4TForTextToSpeech.from_pretrained(self.tmpdirname) self.update_generation(text_model) text_model.to(torch_device) text_model.eval() output_text = self.factory_generation_speech_test(model, input_text) speech_model = SeamlessM4TForSpeechToSpeech.from_pretrained(self.tmpdirname) self.update_generation(speech_model) speech_model.to(torch_device) speech_model.eval() for name, tensor in speech_model.state_dict().items(): right_tensor = state_dict.get(name) self.assertEqual(tensor.tolist(), right_tensor.tolist(), f"Tensor {name}") output_speech = self.factory_generation_speech_test(model, input_speech) # test same text output from input text self.assertListEqual(output_original_text[0].ravel().tolist(), output_text[0].ravel().tolist()) self.assertListEqual(output_original_text[1].ravel().tolist(), output_text[1].ravel().tolist()) # test same speech output from input text # assertTrue because super long list makes this hang in case of failure self.assertTrue( output_original_speech[0].ravel().tolist() == output_speech[0].ravel().tolist(), "Speech generated was different", ) self.assertTrue( output_original_speech[1].ravel().tolist() == output_speech[1].ravel().tolist(), "Speech generated was different", ) def test_text_generation(self): config, input_speech, input_text = self.prepare_speech_and_text_input() # to return speech input_speech["generate_speech"] = False input_text["generate_speech"] = False model = SeamlessM4TModel(config=config) self.update_generation(model) model.save_pretrained(self.tmpdirname) model.to(torch_device) model.eval() output_original_text = self.factory_generation_speech_test(model, input_text) output_original_speech = self.factory_generation_speech_test(model, input_speech) # other models don't need it input_speech.pop("generate_speech") input_text.pop("generate_speech") state_dict = model.state_dict() text_model = SeamlessM4TForTextToText.from_pretrained(self.tmpdirname) self.update_generation(text_model) text_model.to(torch_device) text_model.eval() for name, tensor in text_model.state_dict().items(): right_tensor = state_dict.get(name) self.assertEqual(tensor.tolist(), right_tensor.tolist()) output_text = self.factory_generation_speech_test(text_model, input_text) speech_model = SeamlessM4TForSpeechToText.from_pretrained(self.tmpdirname) for name, tensor in speech_model.state_dict().items(): right_tensor = state_dict.get(name) self.assertEqual(tensor.tolist(), right_tensor.tolist(), f"Tensor {name}") self.update_generation(speech_model) speech_model.to(torch_device) speech_model.eval() output_speech = self.factory_generation_speech_test(speech_model, input_speech) # test same text output from input text self.assertListEqual(output_original_text[0].ravel().tolist(), output_text.ravel().tolist()) # test same speech output from input text self.assertListEqual(output_original_speech[0].ravel().tolist(), output_speech.ravel().tolist()) def test_generation(self): config, input_speech, input_text = self.prepare_speech_and_text_input() input_speech["num_beams"] = 3 input_speech["do_sample"] = True input_speech["num_return_sequences"] = 3 input_text["num_beams"] = 3 input_text["do_sample"] = True input_text["num_return_sequences"] = 3 for model_class in [SeamlessM4TForSpeechToSpeech, SeamlessM4TForSpeechToText, SeamlessM4TModel]: model = model_class(config=config) self.update_generation(model) model.to(torch_device) model.eval() output = model.generate(**input_speech) output = output[0] if isinstance(output, tuple) else output self.assertEqual(output.shape[0], 3 * input_speech["input_features"].shape[0]) for model_class in [SeamlessM4TForTextToSpeech, SeamlessM4TForTextToText, SeamlessM4TModel]: model = model_class(config=config) self.update_generation(model) model.to(torch_device) model.eval() output = model.generate(**input_text) output = output[0] if isinstance(output, tuple) else output self.assertEqual(output.shape[0], 3 * input_text["input_ids"].shape[0]) @require_torch class SeamlessM4TModelIntegrationTest(unittest.TestCase): repo_id = "facebook/hf-seamless-m4t-medium" def assertListAlmostEqual(self, list1, list2, tol=1e-3): self.assertEqual(len(list1), len(list2)) for a, b in zip(list1, list2): self.assertAlmostEqual(a, b, delta=tol) @cached_property def processor(self): return SeamlessM4TProcessor.from_pretrained(self.repo_id) @cached_property def input_text(self): # corresponds to "C'est un test." with seamlessM4T_medium checkpoint input_ids = torch.tensor([[256057, 152, 248116, 354, 159, 7356, 248075, 3]]) # fmt: skip input_ids = input_ids.to(torch_device) attention_mask = torch.ones_like(input_ids).to(torch_device) inputs = { "attention_mask": attention_mask, "input_ids": input_ids, } return inputs @cached_property def input_audio(self): set_seed(0) seq_len = 20000 sampling_rate = 16000 input_features = torch.rand((2, seq_len)) return self.processor(audios=[input_features.tolist()], sampling_rate=sampling_rate, return_tensors="pt").to( torch_device ) def factory_test_task(self, class1, class2, inputs, class1_kwargs, class2_kwargs): model1 = class1.from_pretrained(self.repo_id).to(torch_device) model2 = class2.from_pretrained(self.repo_id).to(torch_device) set_seed(0) output_1 = model1.generate(**inputs, **class1_kwargs) set_seed(0) output_2 = model2.generate(**inputs, **class2_kwargs) for key in output_1: if isinstance(output_1[key], torch.Tensor): if len(output_1[key].shape) == 0: self.assertEqual(output_1[key].item(), output_2[key].item()) else: self.assertListAlmostEqual(output_1[key].squeeze().tolist(), output_2[key].squeeze().tolist()) @slow def test_to_eng_text(self): model = SeamlessM4TModel.from_pretrained(self.repo_id).to(torch_device) # test text - tgt lang: eng expected_text_tokens = [3, 256047, 3291, 248116, 248066, 9, 7356, 248075, 3] # fmt: skip # fmt: off expected_unit_tokens = [ 2,10051,8980,8212,949,1270,4311,1123,5918,2333,5311,3882,2415,5284,1123,612,8816,6370,5386,7334,4345,5645, 9437,5748,1378,9818,4319,7968,7375,2909,9119,5151,8728,5335,3896,4013,8939,8885,6048,9530,3167,5833,1072,693, 431,9867,364,7909,4608,5938,1889,9984,7947,4944,6171,3767,9861,9169,1187,8365,4571,7635,7784,7635,800,2393, 32,5380,5852,8289,2530,2762,1833,2056,3553,4641,3553,5683,370,2288,1344,1518,7534,703,8359,7699,2 ] # fmt: on expected_wav_slice = [-3e-05, -0.0004, -0.00037, -0.00013, -6e-05, 0.00012, -0.00016, 0.00025, 7e-05, -3e-05] # fmt: skip set_seed(0) output = model.generate(**self.input_text, num_beams=1, tgt_lang="eng", return_intermediate_token_ids=True) self.assertListEqual(expected_text_tokens, output.sequences.squeeze().tolist()) # FOR NOW, only first units correspondence self.assertListEqual(expected_unit_tokens[:10], output.unit_sequences.squeeze().tolist()[:10]) self.assertListAlmostEqual(expected_wav_slice, output.waveform.squeeze().tolist()[50:60]) @slow def test_to_swh_text(self): model = SeamlessM4TModel.from_pretrained(self.repo_id).to(torch_device) # test text - tgt lang: swh expected_text_tokens = [3, 256168, 1665, 188589, 7040, 248075, 3] # fmt: skip # fmt: off expected_unit_tokens = [ 2,10071,5729,9995,3089,7546,1204,1721,2532,4340,5623,3496,432,7730,9096,7677,3143,8211,6447,8399,4248,3565, 4529,7700,9308,217,6476,3485,9667,3194,8476,4923,5593,1148,4466,7416,4872,463,4872,253,2348,4640,3450,2133, 6318,2806,817,7613,2698,6563,8712,8344,9286,6878,6387,4281,6387,640,6387,3200,640,8355,640,6708,979,1738,2 ] # fmt: on expected_wav_slice = [1e-05, -7e-05, -4e-05, -4e-05, -6e-05, -9e-05, -0.0001, -2e-05, -7e-05, -2e-05] # fmt: skip set_seed(0) output = model.generate(**self.input_text, num_beams=1, tgt_lang="swh", return_intermediate_token_ids=True) self.assertListEqual(expected_text_tokens, output.sequences.squeeze().tolist()) self.assertListEqual(expected_unit_tokens[:10], output.unit_sequences.squeeze().tolist()[:10]) self.assertListAlmostEqual(expected_wav_slice, output.waveform.squeeze().tolist()[50:60]) @require_speech @slow def test_to_rus_speech(self): model = SeamlessM4TModel.from_pretrained(self.repo_id).to(torch_device) # test audio - tgt lang: rus expected_text_tokens = [3, 256147, 1197, 73565, 3413, 537, 233331, 248075, 3] # fmt: skip # fmt: off expected_unit_tokens = [ 2, 10067, 5729, 4798, 9631, 8378, 4446, 2393, 6901, 5983, 2817, 4629, 8532, 1991, 2931, 8576, 8857, 5936, 4317, 9000, 7740, 7995, 1225, 5980, 6094, 1420, 5373, 8771, 6600, 4487, 7029, 3630, 6740, 4870, 1483, 3003, 5585, 5511, 7465, 3222, 32, 6272, 1950, 3120, 5368, 639, 3713, 5935, 7943, 567, 6129, 6822, 1226, 5063, 9878, 7756, 8825, 1078, 5943, 457, 9282, 9668, 817, 7613, 2698, 6563, 8712, 8704, 9286, 8704, 6387, 4281, 6387, 640, 3200, 6387, 640, 8355, 6708, 979, 1738, 2 ] # fmt: on expected_wav_slice = [0.00013, 0.00012, 0.00014, 3e-05, 0.0, -6e-05, -0.00018, -0.00016, -0.00021, -0.00018] # fmt: skip set_seed(0) output = model.generate(**self.input_audio, num_beams=1, tgt_lang="rus", return_intermediate_token_ids=True) self.assertListEqual(expected_text_tokens, output.sequences.squeeze().tolist()) self.assertListEqual(expected_unit_tokens[:10], output.unit_sequences.squeeze().tolist()[:10]) self.assertListAlmostEqual(expected_wav_slice, output.waveform.squeeze().tolist()[50:60]) @slow def test_text_to_text_model(self): kwargs1 = {"tgt_lang": "eng", "return_intermediate_token_ids": True, "generate_speech": False} kwargs2 = { "tgt_lang": "eng", "output_hidden_states": True, "return_dict_in_generate": True, "output_scores": True, } self.factory_test_task(SeamlessM4TModel, SeamlessM4TForTextToText, self.input_text, kwargs1, kwargs2) @require_speech @slow def test_speech_to_text_model(self): kwargs1 = {"tgt_lang": "eng", "return_intermediate_token_ids": True, "generate_speech": False} kwargs2 = { "tgt_lang": "eng", "output_hidden_states": True, "return_dict_in_generate": True, "output_scores": True, } self.factory_test_task(SeamlessM4TModel, SeamlessM4TForSpeechToText, self.input_audio, kwargs1, kwargs2) @require_speech @slow def test_speech_to_speech_model(self): kwargs1 = {"tgt_lang": "eng", "return_intermediate_token_ids": True} self.factory_test_task(SeamlessM4TModel, SeamlessM4TForSpeechToSpeech, self.input_audio, kwargs1, kwargs1) @slow def test_text_to_speech_model(self): kwargs1 = {"tgt_lang": "eng", "return_intermediate_token_ids": True} self.factory_test_task(SeamlessM4TModel, SeamlessM4TForTextToSpeech, self.input_text, kwargs1, kwargs1)
transformers/tests/models/seamless_m4t/test_modeling_seamless_m4t.py/0
{ "file_path": "transformers/tests/models/seamless_m4t/test_modeling_seamless_m4t.py", "repo_id": "transformers", "token_count": 20993 }
568
# 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 shutil import tempfile import unittest from io import BytesIO from typing import Optional import numpy as np import requests from transformers import SmolVLMProcessor from transformers.models.auto.processing_auto import AutoProcessor from transformers.testing_utils import require_av, require_torch, require_vision from transformers.utils import is_vision_available from ...test_processing_common import ProcessorTesterMixin if is_vision_available(): from PIL import Image @require_torch @require_vision class SmolVLMProcessorTest(ProcessorTesterMixin, unittest.TestCase): processor_class = SmolVLMProcessor videos_input_name = "pixel_values" @classmethod def setUpClass(cls): cls.tmpdirname = tempfile.mkdtemp() processor_kwargs = cls.prepare_processor_dict() processor = SmolVLMProcessor.from_pretrained("HuggingFaceTB/SmolVLM2-256M-Video-Instruct", **processor_kwargs) processor.save_pretrained(cls.tmpdirname) cls.image1 = Image.open( BytesIO( requests.get( "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" ).content ) ) cls.image2 = Image.open( BytesIO(requests.get("https://cdn.britannica.com/59/94459-050-DBA42467/Skyline-Chicago.jpg").content) ) cls.image3 = Image.open( BytesIO( requests.get( "https://thumbs.dreamstime.com/b/golden-gate-bridge-san-francisco-purple-flowers-california-echium-candicans-36805947.jpg" ).content ) ) cls.bos_token = processor.tokenizer.bos_token cls.image_token = processor.image_token cls.video_token = processor.video_token cls.fake_image_token = processor.fake_image_token cls.global_img_token = processor.global_image_token cls.bos_token_id = processor.tokenizer.convert_tokens_to_ids(cls.bos_token) cls.image_token_id = processor.tokenizer.convert_tokens_to_ids(cls.image_token) cls.fake_image_token_id = processor.tokenizer.convert_tokens_to_ids(cls.fake_image_token) cls.global_img_tokens_id = processor.tokenizer(cls.global_img_token, add_special_tokens=False)["input_ids"] cls.padding_token_id = processor.tokenizer.pad_token_id cls.image_seq_len = processor.image_seq_len def get_tokenizer(self, **kwargs): return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).tokenizer def get_image_processor(self, **kwargs): return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).image_processor def get_video_processor(self, **kwargs): return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).video_processor def get_processor(self, **kwargs): return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs) @staticmethod def prepare_processor_dict(): return { "image_seq_len": 2, "chat_template": "<|im_start|>{% for message in messages %}{{message['role'] | capitalize}}{% if message['content'][0]['type'] == 'image' %}{{':'}}{% else %}{{': '}}{% endif %}{% for line in message['content'] %}{% if line['type'] == 'text' %}{{line['text']}}{% elif line['type'] == 'image' %}{{ '<image>' }}{% endif %}{% endfor %}<end_of_utterance>\n{% endfor %}{% if add_generation_prompt %}{{ 'Assistant:' }}{% endif %}", } def prepare_video_inputs(self, batch_size: Optional[int] = None): """This function prepares a list of numpy videos.""" video_input = [np.random.randint(255, size=(3, 30, 400), dtype=np.uint8)] * 8 if batch_size is None: return [[video_input]] return [[video_input]] * batch_size def get_split_image_expected_tokens(self, processor, image_rows, image_cols): text_split_images = [] for n_h in range(image_rows): for n_w in range(image_cols): text_split_images += ( [self.fake_image_token_id] + processor.tokenizer(f"<row_{n_h + 1}_col_{n_w + 1}>", add_special_tokens=False)["input_ids"] + [self.image_token_id] * self.image_seq_len ) text_split_images += processor.tokenizer("\n", add_special_tokens=False)["input_ids"] text_split_images = text_split_images[:-1] # remove last newline # add double newline, as it gets its own token text_split_images += processor.tokenizer("\n\n", add_special_tokens=False)["input_ids"] text_split_images += ( [self.fake_image_token_id] + self.global_img_tokens_id + [self.image_token_id] * self.image_seq_len + [self.fake_image_token_id] ) return text_split_images @classmethod def tearDownClass(cls): shutil.rmtree(cls.tmpdirname, ignore_errors=True) def test_process_interleaved_images_prompts_no_image_splitting(self): processor_components = self.prepare_components() processor_components["tokenizer"] = self.get_component("tokenizer", padding_side="left") processor_components["image_processor"] = self.get_component("image_processor", do_image_splitting=False) processor_kwargs = self.prepare_processor_dict() processor = self.processor_class(**processor_components, **processor_kwargs) # Test that a single image is processed correctly inputs = processor(images=self.image1) image1_expected_size = (512, 512) self.assertEqual(np.array(inputs["pixel_values"]).shape, (1, 1, 3, *image1_expected_size)) self.assertEqual(np.array(inputs["pixel_attention_mask"]).shape, (1, 1, *image1_expected_size)) # fmt: on # Test a single sample with image and text image_str = "<image>" text_str = "In this image, we see" text = image_str + text_str inputs = processor(text=text, images=self.image1) # fmt: off tokenized_sentence = processor.tokenizer(text_str, add_special_tokens=False) expected_input_ids = [[self.fake_image_token_id] + self.global_img_tokens_id + [self.image_token_id] * self.image_seq_len + [self.fake_image_token_id] + tokenized_sentence["input_ids"]] self.assertEqual(inputs["input_ids"], expected_input_ids) self.assertEqual(inputs["attention_mask"], [[1] * len(expected_input_ids[0])]) self.assertEqual(np.array(inputs["pixel_values"]).shape, (1, 1, 3, *image1_expected_size)) self.assertEqual(np.array(inputs["pixel_attention_mask"]).shape, (1, 1, *image1_expected_size)) # fmt: on # Test that batch is correctly processed image_str = "<image>" text_str_1 = "In this image, we see" text_str_2 = "In this image, we see" text = [ image_str + text_str_1, image_str + image_str + text_str_2, ] images = [[self.image1], [self.image2, self.image3]] inputs = processor(text=text, images=images, padding=True) # fmt: off tokenized_sentence_1 = processor.tokenizer(text_str_1, add_special_tokens=False) tokenized_sentence_2 = processor.tokenizer(text_str_2, add_special_tokens=False) image_tokens = [self.fake_image_token_id] + self.global_img_tokens_id + [self.image_token_id] * self.image_seq_len + [self.fake_image_token_id] expected_input_ids_1 = image_tokens + tokenized_sentence_1["input_ids"] expected_input_ids_2 = 2 * image_tokens + tokenized_sentence_2["input_ids"] # Pad the first input to match the second input pad_len = len(expected_input_ids_2) - len(expected_input_ids_1) padded_expected_input_ids_1 = [self.padding_token_id] * pad_len + expected_input_ids_1 self.assertEqual( inputs["input_ids"], [padded_expected_input_ids_1, expected_input_ids_2] ) self.assertEqual( inputs["attention_mask"], [[0] * pad_len + [1] * len(expected_input_ids_1), [1] * len(expected_input_ids_2)] ) self.assertEqual(np.array(inputs['pixel_values']).shape, (2, 2, 3, 512, 512)) self.assertEqual(np.array(inputs['pixel_attention_mask']).shape, (2, 2, 512, 512)) # fmt: on def test_process_interleaved_images_prompts_image_splitting(self): processor_components = self.prepare_components() processor_components["tokenizer"] = self.get_component("tokenizer", padding_side="left") processor_components["image_processor"] = self.get_component("image_processor", do_image_splitting=True) processor_kwargs = self.prepare_processor_dict() processor = self.processor_class(**processor_components, **processor_kwargs) # Test that a single image is processed correctly inputs = processor(images=self.image1) self.assertEqual(np.array(inputs["pixel_values"]).shape, (1, 13, 3, 512, 512)) self.assertEqual(np.array(inputs["pixel_attention_mask"]).shape, (1, 13, 512, 512)) # fmt: on self.maxDiff = None # Test a single sample with image and text image_str = "<image>" text_str = "In this image, we see" text = image_str + text_str inputs = processor(text=text, images=self.image1) # fmt: off tokenized_sentence = processor.tokenizer(text_str, add_special_tokens=False) split_image1_tokens = self.get_split_image_expected_tokens(processor, 3, 4) expected_input_ids_1 = [split_image1_tokens + tokenized_sentence["input_ids"]] self.assertEqual(inputs["input_ids"], expected_input_ids_1) self.assertEqual(inputs["attention_mask"], [[1] * len(expected_input_ids_1[0])]) self.assertEqual(np.array(inputs["pixel_values"]).shape, (1, 13, 3, 512, 512)) self.assertEqual(np.array(inputs["pixel_attention_mask"]).shape, (1, 13, 512, 512)) # fmt: on # Test that batch is correctly processed image_str = "<image>" text_str_1 = "In this image, we see" text_str_2 = "bla, bla" text = [ image_str + text_str_1, text_str_2 + image_str + image_str, ] images = [[self.image1], [self.image2, self.image3]] inputs = processor(text=text, images=images, padding=True) # fmt: off tokenized_sentence_1 = processor.tokenizer(text_str_1, add_special_tokens=False) tokenized_sentence_2 = processor.tokenizer(text_str_2, add_special_tokens=False) split_image1_tokens = self.get_split_image_expected_tokens(processor, 3, 4) split_image2_tokens = self.get_split_image_expected_tokens(processor, 4, 4) split_image3_tokens = self.get_split_image_expected_tokens(processor, 3, 4) expected_input_ids_1 = split_image1_tokens + tokenized_sentence_1["input_ids"] expected_input_ids_2 = tokenized_sentence_2["input_ids"] + split_image2_tokens + split_image3_tokens # Pad the first input to match the second input pad_len = len(expected_input_ids_2) - len(expected_input_ids_1) padded_expected_input_ids_1 = [self.padding_token_id] * pad_len + expected_input_ids_1 self.assertEqual( inputs["input_ids"], [padded_expected_input_ids_1, expected_input_ids_2] ) self.assertEqual( inputs["attention_mask"], [[0] * pad_len + [1] * len(expected_input_ids_1), [1] * len(expected_input_ids_2)] ) self.assertEqual(np.array(inputs['pixel_values']).shape, (2, 30, 3, 512, 512)) self.assertEqual(np.array(inputs['pixel_attention_mask']).shape, (2, 30, 512, 512)) # fmt: on def test_add_special_tokens_processor(self): processor = self.get_processor() image_str = "<image>" text_str = "In this image, we see" text = text_str + image_str # fmt: off inputs = processor(text=text, images=self.image1, add_special_tokens=False) tokenized_sentence = processor.tokenizer(text_str, add_special_tokens=False) split_image1_tokens = self.get_split_image_expected_tokens(processor, 3, 4) expected_input_ids = [tokenized_sentence["input_ids"] + split_image1_tokens] self.assertEqual(inputs["input_ids"], expected_input_ids) inputs = processor(text=text, images=self.image1) expected_input_ids = [tokenized_sentence["input_ids"] + split_image1_tokens] self.assertEqual(inputs["input_ids"], expected_input_ids) # fmt: on @unittest.skip(reason="from @molbap @zucchini-nlp, passing non-nested images is error-prone and not recommended") def test_non_nested_images_with_batched_text(self): processor = self.get_processor() processor.image_processor.do_image_splitting = False image_str = "<image>" text_str_1 = "In this image, we see" text_str_2 = "In this image, we see" text = [ image_str + text_str_1, image_str + image_str + text_str_2, ] images = [[self.image1], [self.image2, self.image3]] inputs = processor(text=text, images=images, padding=True) self.assertEqual(np.array(inputs["pixel_values"]).shape, (2, 2, 3, 512, 512)) self.assertEqual(np.array(inputs["pixel_attention_mask"]).shape, (2, 2, 512, 512)) # Copied from tests.models.idefics2.test_processing_idefics2.Idefics2ProcessorTest.test_process_interleaved_images_prompts_image_error def test_process_interleaved_images_prompts_image_error(self): processor = self.get_processor() text = [ "This is a test sentence.", "In this other sentence we try some good things", ] images = [[self.image1], [self.image2]] with self.assertRaises(ValueError): processor(text=text, images=images, padding=True) images = [[self.image1], []] with self.assertRaises(ValueError): processor(text=text, images=images, padding=True) text = [ "This is a test sentence.<image>", "In this other sentence we try some good things<image>", ] images = [[self.image1], [self.image2, self.image3]] with self.assertRaises(ValueError): processor(text=text, images=images, padding=True) images = [[], [self.image2]] with self.assertRaises(ValueError): processor(text=text, images=images, padding=True) images = [self.image1, self.image2, self.image3] with self.assertRaises(ValueError): processor(text=text, images=images, padding=True) images = [self.image1] with self.assertRaises(ValueError): processor(text=text, images=images, padding=True) text = [ "This is a test sentence.", "In this other sentence we try some good things<image>", ] images = [[self.image1], []] with self.assertRaises(ValueError): processor(text=text, images=images, padding=True) images = [[], [self.image2]] with self.assertRaises(ValueError): processor(text=text, images=images, padding=True) images = [self.image1, self.image2] with self.assertRaises(ValueError): processor(text=text, images=images, padding=True) images = [self.image1] with self.assertRaises(ValueError): processor(text=text, images=images, padding=True) def test_apply_chat_template(self): # Message contains content which a mix of lists with images and image urls and string messages = [ { "role": "user", "content": [ {"type": "text", "text": "What do these images show?"}, {"type": "image"}, {"type": "image"}, ], }, { "role": "assistant", "content": [ { "type": "text", "text": "The first image shows the statue of Liberty in New York. The second image picture depicts Idefix, the dog of Obelix in Asterix and Obelix.", } ], }, {"role": "user", "content": [{"type": "text", "text": "And who is that?"}]}, ] processor = self.get_processor() # Make short sequence length to test that the fake tokens are added correctly rendered = processor.apply_chat_template(messages, add_generation_prompt=True) expected_rendered = ( "<|im_start|>User: What do these images show?<image><image><end_of_utterance>\n" "Assistant: The first image shows the statue of Liberty in New York. The second image picture depicts Idefix, the dog of Obelix in Asterix and Obelix.<end_of_utterance>\n" "User: And who is that?<end_of_utterance>\n" "Assistant:" ) self.assertEqual(rendered, expected_rendered) @require_av @require_torch def test_apply_chat_template_video_frame_sampling(self): # overridden because SmolVLM has special preprocessing for videos processor = self.get_processor() if processor.chat_template is None: self.skipTest("Processor has no chat template") messages = [ [ { "role": "user", "content": [ { "type": "video", "url": "https://huggingface.co/datasets/raushan-testing-hf/videos-test/resolve/main/Big_Buck_Bunny_720_10s_10MB.mp4", }, {"type": "text", "text": "What is shown in this video?"}, ], }, ] ] num_frames = 3 out_dict_with_video = processor.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, num_frames=num_frames, return_tensors="pt", ) self.assertTrue(self.videos_input_name in out_dict_with_video) self.assertEqual(len(out_dict_with_video[self.videos_input_name]), 1) # SmolVLM doesn't sample `num_frames` exactly, by uses other sampling method self.assertEqual(len(out_dict_with_video[self.videos_input_name][0]), 3) # Load with `fps` arg fps = 1 out_dict_with_video = processor.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, fps=fps, return_tensors="pt", ) self.assertTrue(self.videos_input_name in out_dict_with_video) self.assertEqual(len(out_dict_with_video[self.videos_input_name]), 1) # SmolVLM doesn't sample 1 frame per second exactly, by uses other sampling method self.assertEqual(len(out_dict_with_video[self.videos_input_name][0]), fps * 10) # NOTE: the last assert checks are removed # Loading video as a list of frames (i.e. images) is not supported in SmolVLM @require_torch @require_vision def test_unstructured_kwargs_batched(self): if "image_processor" not in self.processor_class.attributes: self.skipTest(f"image_processor attribute not present in {self.processor_class}") image_processor = self.get_component("image_processor") video_processor = self.get_component("video_processor") tokenizer = self.get_component("tokenizer") processor_kwargs = self.prepare_processor_dict() processor = self.processor_class( tokenizer=tokenizer, image_processor=image_processor, video_processor=video_processor, **processor_kwargs ) self.skip_processor_without_typed_kwargs(processor) input_str = self.prepare_text_inputs(batch_size=2, modality="image") image_input = self.prepare_image_inputs(batch_size=2) image_input = [[image_input[0]], [image_input[1]]] inputs = processor( text=input_str, images=image_input, return_tensors="pt", padding="max_length", max_length=76, truncation=True, max_image_size={"longest_edge": 300}, ) self.assertEqual(inputs["pixel_values"].shape[2], 3) self.assertEqual(inputs["pixel_values"].shape[3], 300) self.assertEqual(len(inputs["input_ids"][0]), 76) @require_torch @require_vision def test_unstructured_kwargs_batched_video(self): if "video_processor" not in self.processor_class.attributes: self.skipTest(f"video_processor attribute not present in {self.processor_class}") processor_components = self.prepare_components() processor_kwargs = self.prepare_processor_dict() processor = self.processor_class(**processor_components, **processor_kwargs) self.skip_processor_without_typed_kwargs(processor) input_str = self.prepare_text_inputs(batch_size=2, modality="video") video_input = self.prepare_video_inputs(batch_size=2) inputs = processor( text=input_str, videos=video_input, return_tensors="pt", do_rescale=True, rescale_factor=-1, padding="max_length", max_length=172, ) self.assertLessEqual(inputs[self.videos_input_name][0].mean(), 0) self.assertEqual(len(inputs["input_ids"][0]), 172) @require_torch @require_vision def test_text_only_inference(self): """Test that the processor works correctly with text-only input.""" processor_components = self.prepare_components() processor_components["tokenizer"] = self.get_component("tokenizer", padding_side="left") processor_kwargs = self.prepare_processor_dict() processor = self.processor_class(**processor_components, **processor_kwargs) text = "This is a simple text without images." inputs = processor(text=text) tokenized_sentence = processor.tokenizer(text, add_special_tokens=False) expected_input_ids = [tokenized_sentence["input_ids"]] self.assertEqual(inputs["input_ids"], expected_input_ids) self.assertEqual(inputs["attention_mask"], [[1] * len(expected_input_ids[0])]) self.assertTrue("pixel_values" not in inputs) self.assertTrue("pixel_attention_mask" not in inputs) # Test batch of texts without image tokens texts = ["First text.", "Second piece of text."] batch_inputs = processor(text=texts, padding=True) tokenized_1 = processor.tokenizer(texts[0], add_special_tokens=False) tokenized_2 = processor.tokenizer(texts[1], add_special_tokens=False) expected_1 = tokenized_1["input_ids"] expected_2 = tokenized_2["input_ids"] # Pad the shorter sequence pad_len = len(expected_2) - len(expected_1) if pad_len > 0: padded_expected_1 = [self.padding_token_id] * pad_len + expected_1 expected_attention_1 = [0] * pad_len + [1] * len(expected_1) self.assertEqual(batch_inputs["input_ids"], [padded_expected_1, expected_2]) self.assertEqual(batch_inputs["attention_mask"], [expected_attention_1, [1] * len(expected_2)]) else: pad_len = -pad_len padded_expected_2 = [self.padding_token_id] * pad_len + expected_2 expected_attention_2 = [0] * pad_len + [1] * len(expected_2) self.assertEqual(batch_inputs["input_ids"], [expected_1, padded_expected_2]) self.assertEqual(batch_inputs["attention_mask"], [[1] * len(expected_1), expected_attention_2]) @require_torch @require_vision def test_missing_images_error(self): """Test that appropriate error is raised when images are referenced but not provided.""" processor = self.get_processor() # Test single text with image token but no image text = "Let me show you this image: <image> What do you think?" with self.assertRaises(ValueError) as context: processor(text=text) self.assertTrue("tokens in the text but no images/videos were passed" in str(context.exception)) # Test batch with image tokens but no images texts = [ "First text with <image> token.", "Second text <image> with token.", ] with self.assertRaises(ValueError) as context: processor(text=texts) self.assertTrue("tokens in the text but no images/videos were passed" in str(context.exception)) # Test with None as Images with self.assertRaises(ValueError) as context: processor(text=text, images=None) self.assertTrue("tokens in the text but no images/videos were passed" in str(context.exception)) with self.assertRaises(ValueError) as context: processor(text=texts, images=None) self.assertTrue("tokens in the text but no images/videos were passed" in str(context.exception)) def test_special_mm_token_truncation(self): """Tests that special vision tokens do not get truncated when `truncation=True` is set.""" processor = self.get_processor() input_str = self.prepare_text_inputs(batch_size=2, modality="image") image_input = self.prepare_image_inputs(batch_size=2) image_input = [[image_input[0]], [image_input[1]]] _ = processor( text=input_str, images=image_input, return_tensors="pt", truncation=None, padding=True, ) with self.assertRaises(ValueError): _ = processor( text=input_str, images=image_input, return_tensors="pt", truncation=True, padding=True, max_length=20, ) @unittest.skip("SmolVLM cannot accept image URL as video frames, because it needs to know video fps and duration") def test_apply_chat_template_video_1(self): pass @unittest.skip( "SmolVLM cannot accept list of decoded video frames, because it needs to know video fps and duration" ) def test_apply_chat_template_video_2(self): pass
transformers/tests/models/smolvlm/test_processing_smolvlm.py/0
{ "file_path": "transformers/tests/models/smolvlm/test_processing_smolvlm.py", "repo_id": "transformers", "token_count": 11855 }
569
# Copyright 2024 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. import inspect import tempfile import unittest from transformers import pipeline from transformers.testing_utils import ( Expectations, require_bitsandbytes, require_timm, require_torch, require_vision, slow, torch_device, ) from transformers.utils.import_utils import is_timm_available, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import TimmWrapperConfig, TimmWrapperForImageClassification, TimmWrapperModel if is_timm_available(): import timm if is_vision_available(): from PIL import Image from transformers import TimmWrapperImageProcessor class TimmWrapperModelTester: def __init__( self, parent, model_name="timm/resnet18.a1_in1k", batch_size=3, image_size=32, num_channels=3, is_training=True, ): self.parent = parent self.model_name = model_name self.batch_size = batch_size self.image_size = image_size self.num_channels = num_channels self.is_training = is_training def prepare_config_and_inputs(self): pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) config = self.get_config() return config, pixel_values def get_config(self): return TimmWrapperConfig.from_pretrained(self.model_name) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, pixel_values = config_and_inputs inputs_dict = {"pixel_values": pixel_values} return config, inputs_dict @require_torch @require_timm class TimmWrapperModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (TimmWrapperModel, TimmWrapperForImageClassification) if is_torch_available() else () pipeline_model_mapping = ( {"image-feature-extraction": TimmWrapperModel, "image-classification": TimmWrapperForImageClassification} if is_torch_available() else {} ) test_resize_embeddings = False test_head_masking = False test_pruning = False has_attentions = False test_model_parallel = False def setUp(self): self.config_class = TimmWrapperConfig self.model_tester = TimmWrapperModelTester(self) self.config_tester = ConfigTester( self, config_class=self.config_class, has_text_modality=False, common_properties=[], model_name="timm/resnet18.a1_in1k", ) def test_config(self): self.config_tester.run_common_tests() def test_hidden_states_output(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) # check all hidden states with torch.no_grad(): outputs = model(**inputs_dict, output_hidden_states=True) self.assertTrue( len(outputs.hidden_states) == 5, f"expected 5 hidden states, but got {len(outputs.hidden_states)}" ) expected_shapes = [[16, 16], [8, 8], [4, 4], [2, 2], [1, 1]] resulted_shapes = [list(h.shape[2:]) for h in outputs.hidden_states] self.assertListEqual(expected_shapes, resulted_shapes) # check we can select hidden states by indices with torch.no_grad(): outputs = model(**inputs_dict, output_hidden_states=[-2, -1]) self.assertTrue( len(outputs.hidden_states) == 2, f"expected 2 hidden states, but got {len(outputs.hidden_states)}" ) expected_shapes = [[2, 2], [1, 1]] resulted_shapes = [list(h.shape[2:]) for h in outputs.hidden_states] self.assertListEqual(expected_shapes, resulted_shapes) @unittest.skip(reason="TimmWrapper models doesn't have inputs_embeds") def test_inputs_embeds(self): pass @unittest.skip(reason="TimmWrapper models doesn't have inputs_embeds") def test_model_get_set_embeddings(self): pass @unittest.skip(reason="TimmWrapper doesn't support output_attentions=True.") def test_torchscript_output_attentions(self): pass @unittest.skip(reason="TimmWrapper doesn't support this.") def test_retain_grad_hidden_states_attentions(self): pass @unittest.skip(reason="TimmWrapper initialization is managed on the timm side") def test_can_init_all_missing_weights(self): pass @unittest.skip(reason="TimmWrapper initialization is managed on the timm side") def test_initialization(self): pass @unittest.skip(reason="TimmWrapper initialization is managed on the timm side") def test_mismatched_shapes_have_properly_initialized_weights(self): pass @unittest.skip(reason="Need to use a timm model and there is no tiny model available.") def test_model_is_small(self): pass def test_gradient_checkpointing(self): config, _ = self.model_tester.prepare_config_and_inputs_for_common() model = TimmWrapperModel._from_config(config) self.assertTrue(model.supports_gradient_checkpointing) def test_gradient_checkpointing_on_non_supported_model(self): config = TimmWrapperConfig.from_pretrained("timm/hrnet_w18.ms_aug_in1k") model = TimmWrapperModel._from_config(config) self.assertFalse(model.supports_gradient_checkpointing) def test_forward_signature(self): config, _ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) signature = inspect.signature(model.forward) # signature.parameters is an OrderedDict => so arg_names order is deterministic arg_names = [*signature.parameters.keys()] expected_arg_names = ["pixel_values"] self.assertListEqual(arg_names[:1], expected_arg_names) def test_do_pooling_option(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() config.do_pooling = False model = TimmWrapperModel._from_config(config) # check there is no pooling with torch.no_grad(): output = model(**inputs_dict) self.assertIsNone(output.pooler_output) # check there is pooler output with torch.no_grad(): output = model(**inputs_dict, do_pooling=True) self.assertIsNotNone(output.pooler_output) def test_timm_config_labels(self): # test timm config with no labels checkpoint = "timm/resnet18.a1_in1k" config = TimmWrapperConfig.from_pretrained(checkpoint) self.assertIsNone(config.label2id) self.assertIsInstance(config.id2label, dict) self.assertEqual(len(config.id2label), 1000) self.assertEqual(config.id2label[1], "goldfish, Carassius auratus") # test timm config with labels in config checkpoint = "timm/eva02_large_patch14_clip_336.merged2b_ft_inat21" config = TimmWrapperConfig.from_pretrained(checkpoint) self.assertIsInstance(config.id2label, dict) self.assertEqual(len(config.id2label), 10000) self.assertEqual(config.id2label[1], "Sabella spallanzanii") self.assertIsInstance(config.label2id, dict) self.assertEqual(len(config.label2id), 10000) self.assertEqual(config.label2id["Sabella spallanzanii"], 1) # test custom labels are provided checkpoint = "timm/resnet18.a1_in1k" config = TimmWrapperConfig.from_pretrained(checkpoint, num_labels=2) self.assertEqual(config.num_labels, 2) self.assertEqual(config.id2label, {0: "LABEL_0", 1: "LABEL_1"}) self.assertEqual(config.label2id, {"LABEL_0": 0, "LABEL_1": 1}) # test with provided id2label and label2id checkpoint = "timm/resnet18.a1_in1k" config = TimmWrapperConfig.from_pretrained( checkpoint, num_labels=2, id2label={0: "LABEL_0", 1: "LABEL_1"}, label2id={"LABEL_0": 0, "LABEL_1": 1} ) self.assertEqual(config.num_labels, 2) self.assertEqual(config.id2label, {0: "LABEL_0", 1: "LABEL_1"}) self.assertEqual(config.label2id, {"LABEL_0": 0, "LABEL_1": 1}) # test save load checkpoint = "timm/resnet18.a1_in1k" config = TimmWrapperConfig.from_pretrained(checkpoint) with tempfile.TemporaryDirectory() as tmpdirname: config.save_pretrained(tmpdirname) restored_config = TimmWrapperConfig.from_pretrained(tmpdirname) self.assertEqual(config.num_labels, restored_config.num_labels) self.assertEqual(config.id2label, restored_config.id2label) self.assertEqual(config.label2id, restored_config.label2id) def test_model_init_args(self): # test init from config config = TimmWrapperConfig.from_pretrained( "timm/vit_base_patch32_clip_448.laion2b_ft_in12k_in1k", model_args={"depth": 3}, ) model = TimmWrapperModel(config) self.assertEqual(len(model.timm_model.blocks), 3) cls_model = TimmWrapperForImageClassification(config) self.assertEqual(len(cls_model.timm_model.blocks), 3) # test save load with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(tmpdirname) restored_model = TimmWrapperModel.from_pretrained(tmpdirname) self.assertEqual(len(restored_model.timm_model.blocks), 3) # We will verify our results on an image of cute cats def prepare_img(): image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") return image @require_torch @require_timm @require_vision class TimmWrapperModelIntegrationTest(unittest.TestCase): # some popular ones model_names_to_test = [ "vit_small_patch16_384.augreg_in21k_ft_in1k", "resnet50.a1_in1k", "tf_mobilenetv3_large_minimal_100.in1k", "swin_tiny_patch4_window7_224.ms_in1k", "ese_vovnet19b_dw.ra_in1k", "hrnet_w18.ms_aug_in1k", ] @slow def test_inference_image_classification_head(self): checkpoint = "timm/resnet18.a1_in1k" model = TimmWrapperForImageClassification.from_pretrained(checkpoint, device_map=torch_device).eval() image_processor = TimmWrapperImageProcessor.from_pretrained(checkpoint) image = prepare_img() inputs = image_processor(images=image, return_tensors="pt").to(torch_device) # forward pass with torch.no_grad(): outputs = model(**inputs) # verify the shape and logits expected_shape = torch.Size((1, 1000)) self.assertEqual(outputs.logits.shape, expected_shape) expected_label = 281 # tabby cat self.assertEqual(torch.argmax(outputs.logits).item(), expected_label) expectations = Expectations( { (None, None): [-11.2618, -9.6192, -10.3205], ("cuda", 8): [-11.2634, -9.6208, -10.3199], } ) expected_slice = torch.tensor(expectations.get_expectation()).to(torch_device) resulted_slice = outputs.logits[0, :3] torch.testing.assert_close(resulted_slice, expected_slice, atol=1e-3, rtol=1e-3) @slow def test_inference_with_pipeline(self): image = prepare_img() classifier = pipeline(model="timm/resnet18.a1_in1k", device=torch_device) result = classifier(image) # verify result expected_label = "tabby, tabby cat" expected_score = 0.4329 self.assertEqual(result[0]["label"], expected_label) self.assertAlmostEqual(result[0]["score"], expected_score, places=3) @slow @require_bitsandbytes def test_inference_image_classification_quantized(self): from transformers import BitsAndBytesConfig checkpoint = "timm/vit_small_patch16_384.augreg_in21k_ft_in1k" quantization_config = BitsAndBytesConfig(load_in_8bit=True) model = TimmWrapperForImageClassification.from_pretrained( checkpoint, quantization_config=quantization_config, device_map=torch_device ).eval() image_processor = TimmWrapperImageProcessor.from_pretrained(checkpoint) image = prepare_img() inputs = image_processor(images=image, return_tensors="pt").to(torch_device) # forward pass with torch.no_grad(): outputs = model(**inputs) # verify the shape and logits expected_shape = torch.Size((1, 1000)) self.assertEqual(outputs.logits.shape, expected_shape) expected_label = 281 # tabby cat self.assertEqual(torch.argmax(outputs.logits).item(), expected_label) expectations = Expectations( { (None, None): [-2.4043, 1.4492, -0.5127], ("cuda", 8): [-2.2676, 1.5303, -0.4409], } ) expected_slice = torch.tensor(expectations.get_expectation()).to(torch_device) resulted_slice = outputs.logits[0, :3].to(dtype=torch.float32) torch.testing.assert_close(resulted_slice, expected_slice, atol=0.1, rtol=0.1) @slow def test_transformers_model_for_classification_is_equivalent_to_timm(self): # check that wrapper logits are the same as timm model logits image = prepare_img() for model_name in self.model_names_to_test: checkpoint = f"timm/{model_name}" with self.subTest(msg=model_name): # prepare inputs image_processor = TimmWrapperImageProcessor.from_pretrained(checkpoint) pixel_values = image_processor(images=image).pixel_values.to(torch_device) # load models model = TimmWrapperForImageClassification.from_pretrained(checkpoint, device_map=torch_device).eval() timm_model = timm.create_model(model_name, pretrained=True).to(torch_device).eval() with torch.inference_mode(): outputs = model(pixel_values) timm_outputs = timm_model(pixel_values) # check shape is the same self.assertEqual(outputs.logits.shape, timm_outputs.shape) # check logits are the same diff = (outputs.logits - timm_outputs).max().item() self.assertLess(diff, 1e-4) @slow def test_transformers_model_is_equivalent_to_timm(self): # check that wrapper logits are the same as timm model logits image = prepare_img() models_to_test = ["vit_small_patch16_224.dino"] + self.model_names_to_test for model_name in models_to_test: checkpoint = f"timm/{model_name}" with self.subTest(msg=model_name): # prepare inputs image_processor = TimmWrapperImageProcessor.from_pretrained(checkpoint) pixel_values = image_processor(images=image).pixel_values.to(torch_device) # load models model = TimmWrapperModel.from_pretrained(checkpoint, device_map=torch_device).eval() timm_model = timm.create_model(model_name, pretrained=True, num_classes=0).to(torch_device).eval() with torch.inference_mode(): outputs = model(pixel_values) timm_outputs = timm_model(pixel_values) # check shape is the same self.assertEqual(outputs.pooler_output.shape, timm_outputs.shape) # check logits are the same diff = (outputs.pooler_output - timm_outputs).max().item() self.assertLess(diff, 1e-4) @slow def test_save_load_to_timm(self): # test that timm model can be loaded to transformers, saved and then loaded back into timm model = TimmWrapperForImageClassification.from_pretrained( "timm/resnet18.a1_in1k", num_labels=10, ignore_mismatched_sizes=True ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(tmpdirname) # there is no direct way to load timm model from folder, use the same config + path to weights timm_model = timm.create_model( "resnet18", num_classes=10, checkpoint_path=f"{tmpdirname}/model.safetensors" ) # check that all weights are the same after reload different_weights = [] for (name1, param1), (name2, param2) in zip( model.timm_model.named_parameters(), timm_model.named_parameters() ): if param1.shape != param2.shape or not torch.equal(param1, param2): different_weights.append((name1, name2)) if different_weights: self.fail(f"Found different weights after reloading: {different_weights}")
transformers/tests/models/timm_wrapper/test_modeling_timm_wrapper.py/0
{ "file_path": "transformers/tests/models/timm_wrapper/test_modeling_timm_wrapper.py", "repo_id": "transformers", "token_count": 7732 }
570
# 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 UniSpeechSat model.""" import math import unittest import numpy as np import pytest from datasets import load_dataset from transformers import UniSpeechSatConfig, is_torch_available from transformers.testing_utils import require_torch, require_torchcodec, 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 ( UniSpeechSatForAudioFrameClassification, UniSpeechSatForCTC, UniSpeechSatForPreTraining, UniSpeechSatForSequenceClassification, UniSpeechSatForXVector, UniSpeechSatModel, Wav2Vec2FeatureExtractor, Wav2Vec2Processor, ) class UniSpeechSatModelTester: 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, mask_time_prob=0.5, mask_time_length=2, 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.mask_time_prob = mask_time_prob self.mask_time_length = mask_time_length 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 UniSpeechSatConfig( 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, mask_time_prob=self.mask_time_prob, mask_time_length=self.mask_time_length, 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 = UniSpeechSatModel(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 create_and_check_batch_inference(self, config, input_values, *args): # test does not pass for models making use of `group_norm` # check: https://github.com/pytorch/fairseq/issues/3227 model = UniSpeechSatModel(config=config) model.to(torch_device) model.eval() input_values = input_values[:3] attention_mask = torch.ones(input_values.shape, device=torch_device, dtype=torch.bool) input_lengths = [input_values.shape[-1] // i for i in [4, 2, 1]] # pad input for i in range(len(input_lengths)): input_values[i, input_lengths[i] :] = 0.0 attention_mask[i, input_lengths[i] :] = 0.0 batch_outputs = model(input_values, attention_mask=attention_mask).last_hidden_state for i in range(input_values.shape[0]): input_slice = input_values[i : i + 1, : input_lengths[i]] output = model(input_slice).last_hidden_state batch_output = batch_outputs[i : i + 1, : output.shape[1]] self.parent.assertTrue(torch.allclose(output, batch_output, atol=1e-3)) def check_ctc_loss(self, config, input_values, *args): model = UniSpeechSatForCTC(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 = UniSpeechSatForSequenceClassification(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 = UniSpeechSatForCTC(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 = UniSpeechSatForSequenceClassification(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_xvector_training(self, config, *args): config.ctc_zero_infinity = True model = UniSpeechSatForXVector(config=config) model.to(torch_device) model.train() # freeze everything but the classification head model.freeze_base_model() # use a longer sequence length to account for TDNN temporal downsampling input_values = floats_tensor([self.batch_size, self.seq_length * 2], scale=1.0) 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_labels_out_of_vocab(self, config, input_values, *args): model = UniSpeechSatForCTC(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 UniSpeechSatModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( ( UniSpeechSatForCTC, UniSpeechSatForPreTraining, UniSpeechSatModel, UniSpeechSatForSequenceClassification, UniSpeechSatForAudioFrameClassification, UniSpeechSatForXVector, ) if is_torch_available() else () ) pipeline_model_mapping = ( { "audio-classification": UniSpeechSatForSequenceClassification, "automatic-speech-recognition": UniSpeechSatForCTC, "feature-extraction": UniSpeechSatModel, } if is_torch_available() else {} ) test_pruning = False test_headmasking = False test_torchscript = False def setUp(self): self.model_tester = UniSpeechSatModelTester(self) self.config_tester = ConfigTester(self, config_class=UniSpeechSatConfig, 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_xvector_train(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.check_xvector_training(*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="Model has no input_embeds") def test_inputs_embeds(self): pass @unittest.skip(reason="Model has input_values instead of input_ids") def test_forward_signature(self): pass @unittest.skip(reason="Model has no tokens embeddings") def test_resize_tokens_embeddings(self): pass @unittest.skip(reason="Model has no input_embeds") def test_model_get_set_embeddings(self): pass 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 # force eager attention to support output attentions config._attn_implementation = "eager" # 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] attentions = outputs.attentions[0] hidden_states.retain_grad() attentions.retain_grad() output.flatten()[0].backward(retain_graph=True) self.assertIsNotNone(hidden_states.grad) self.assertIsNotNone(attentions.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", "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) def test_mask_feature_prob_ctc(self): model = UniSpeechSatForCTC.from_pretrained( "hf-internal-testing/tiny-random-unispeech-sat", mask_feature_prob=0.2, mask_feature_length=2 ) model.to(torch_device).train() processor = Wav2Vec2Processor.from_pretrained( "hf-internal-testing/tiny-random-unispeech-sat", return_attention_mask=True ) batch_duration_in_seconds = [1, 3, 2, 6] input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds] batch = processor( input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="pt" ) logits = model( input_values=batch["input_values"].to(torch_device), attention_mask=batch["attention_mask"].to(torch_device), ).logits self.assertEqual(logits.shape, (4, 1498, 32)) def test_mask_time_prob_ctc(self): model = UniSpeechSatForCTC.from_pretrained( "hf-internal-testing/tiny-random-unispeech-sat", mask_time_prob=0.2, mask_time_length=2 ) model.to(torch_device).train() processor = Wav2Vec2Processor.from_pretrained( "hf-internal-testing/tiny-random-unispeech-sat", return_attention_mask=True ) batch_duration_in_seconds = [1, 3, 2, 6] input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds] batch = processor( input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="pt" ) logits = model( input_values=batch["input_values"].to(torch_device), attention_mask=batch["attention_mask"].to(torch_device), ).logits self.assertEqual(logits.shape, (4, 1498, 32)) @unittest.skip(reason="Feed forward chunking is not implemented") def test_feed_forward_chunking(self): pass @slow def test_model_from_pretrained(self): model = UniSpeechSatModel.from_pretrained("microsoft/unispeech-sat-base-plus") self.assertIsNotNone(model) @require_torch class UniSpeechSatRobustModelTest(ModelTesterMixin, unittest.TestCase): all_model_classes = ( (UniSpeechSatForCTC, UniSpeechSatForPreTraining, UniSpeechSatModel, UniSpeechSatForSequenceClassification) if is_torch_available() else () ) test_pruning = False test_headmasking = False test_torchscript = False def setUp(self): self.model_tester = UniSpeechSatModelTester( self, conv_stride=(3, 3, 3), feat_extract_norm="layer", do_stable_layer_norm=True ) self.config_tester = ConfigTester(self, config_class=UniSpeechSatConfig, 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_batched_inference(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_batch_inference(*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_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="Model has no input_embeds") def test_inputs_embeds(self): pass @unittest.skip(reason="Model has input_values instead of input_ids") def test_forward_signature(self): pass @unittest.skip(reason="Model has no tokens embeddings") def test_resize_tokens_embeddings(self): pass @unittest.skip(reason="Model has no input_embeds") def test_model_get_set_embeddings(self): pass 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 # force eager attention to support output attentions config._attn_implementation = "eager" # 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] attentions = outputs.attentions[0] hidden_states.retain_grad() attentions.retain_grad() output.flatten()[0].backward(retain_graph=True) self.assertIsNotNone(hidden_states.grad) self.assertIsNotNone(attentions.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", "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) def test_mask_feature_prob_ctc(self): model = UniSpeechSatForCTC.from_pretrained( "hf-internal-testing/tiny-random-unispeech-sat", mask_feature_prob=0.2, mask_feature_length=2 ) model.to(torch_device).train() processor = Wav2Vec2Processor.from_pretrained( "hf-internal-testing/tiny-random-unispeech-sat", return_attention_mask=True ) batch_duration_in_seconds = [1, 3, 2, 6] input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds] batch = processor( input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="pt" ) logits = model( input_values=batch["input_values"].to(torch_device), attention_mask=batch["attention_mask"].to(torch_device), ).logits self.assertEqual(logits.shape, (4, 1498, 32)) def test_mask_time_prob_ctc(self): model = UniSpeechSatForCTC.from_pretrained( "hf-internal-testing/tiny-random-unispeech-sat", mask_time_prob=0.2, mask_time_length=2 ) model.to(torch_device).train() processor = Wav2Vec2Processor.from_pretrained( "hf-internal-testing/tiny-random-unispeech-sat", return_attention_mask=True ) batch_duration_in_seconds = [1, 3, 2, 6] input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds] batch = processor( input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="pt" ) logits = model( input_values=batch["input_values"].to(torch_device), attention_mask=batch["attention_mask"].to(torch_device), ).logits self.assertEqual(logits.shape, (4, 1498, 32)) def test_mask_time_feature_prob_ctc_single_batch(self): model = UniSpeechSatForCTC.from_pretrained( "hf-internal-testing/tiny-random-unispeech-sat", mask_time_prob=0.2, mask_feature_prob=0.2, mask_time_length=2, mask_feature_length=2, ) model.to(torch_device).train() processor = Wav2Vec2Processor.from_pretrained( "hf-internal-testing/tiny-random-unispeech-sat", return_attention_mask=True ) batch_duration_in_seconds = [6] input_features = [np.random.random(16_000 * s) for s in batch_duration_in_seconds] batch = processor( input_features, padding=True, sampling_rate=processor.feature_extractor.sampling_rate, return_tensors="pt" ) logits = model( input_values=batch["input_values"].to(torch_device), attention_mask=batch["attention_mask"].to(torch_device), ).logits self.assertEqual(logits.shape, (1, 1498, 32)) @unittest.skip(reason="Feed forward chunking is not implemented") def test_feed_forward_chunking(self): pass @slow def test_model_from_pretrained(self): model = UniSpeechSatModel.from_pretrained("microsoft/unispeech-sat-large") self.assertIsNotNone(model) @require_torch @require_torchcodec @slow class UniSpeechSatModelIntegrationTest(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_encoder_base(self): model = UniSpeechSatModel.from_pretrained("microsoft/unispeech-sat-base-plus") model.to(torch_device) feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained( "facebook/wav2vec2-base", return_attention_mask=True ) input_speech = self._load_datasamples(2) inputs_dict = feature_extractor(input_speech, return_tensors="pt", padding=True) with torch.no_grad(): outputs = model( inputs_dict.input_values.to(torch_device), attention_mask=inputs_dict.attention_mask.to(torch_device), ) # fmt: off expected_hidden_states_slice = torch.tensor( [[[-0.0743, 0.1384], [-0.0845, 0.1704]], [[-0.0954, 0.1936], [-0.1123, 0.2095]]], device=torch_device, ) # fmt: on torch.testing.assert_close( outputs.last_hidden_state[:, :2, -2:], expected_hidden_states_slice, rtol=1e-3, atol=1e-3 ) def test_inference_encoder_large(self): model = UniSpeechSatModel.from_pretrained("microsoft/unispeech-sat-large") model.to(torch_device) feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("facebook/wav2vec2-large-xlsr-53") input_speech = self._load_datasamples(2) inputs_dict = feature_extractor(input_speech, return_tensors="pt", padding=True) with torch.no_grad(): outputs = model( inputs_dict.input_values.to(torch_device), attention_mask=inputs_dict.attention_mask.to(torch_device), ) # fmt: off expected_hidden_states_slice = torch.tensor( [[[-0.1172, -0.0797], [-0.0012, 0.0213]], [[-0.1225, -0.1277], [-0.0668, -0.0585]]], device=torch_device, ) # fmt: on torch.testing.assert_close( outputs.last_hidden_state[:, :2, -2:], expected_hidden_states_slice, rtol=1e-3, atol=1e-3 ) def test_inference_diarization(self): model = UniSpeechSatForAudioFrameClassification.from_pretrained("microsoft/unispeech-sat-base-plus-sd").to( torch_device ) processor = Wav2Vec2FeatureExtractor.from_pretrained("microsoft/unispeech-sat-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.6119, -5.5845], [-3.7772, -5.4824], [-3.6914, -5.1619], [-4.7560, -5.0496]], [[-6.3785, -4.8365], [-5.5863, -5.4149], [-5.5639, -4.8469], [-6.1511, -4.0052]], [[-6.0355, -3.7414], [-5.5968, -4.8061], [-5.4620, -4.7310], [-5.5864, -4.6078]], [[-5.9493, -4.8963], [-4.4050, -5.4476], [-4.1755, -5.1395], [-4.0272, -4.3705]], ], device=torch_device, ) self.assertEqual(labels[0, :, 0].sum(), 270) 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 = UniSpeechSatForXVector.from_pretrained("microsoft/unispeech-sat-base-plus-sv").to(torch_device) processor = Wav2Vec2FeatureExtractor.from_pretrained("microsoft/unispeech-sat-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.9671, 3) # id10006 vs id10002 self.assertAlmostEqual(cosine_sim(embeddings[0], embeddings[1]).item(), 0.4941, 3) # id10002 vs id10004 self.assertAlmostEqual(cosine_sim(embeddings[2], embeddings[3]).item(), 0.5616, 3) self.assertAlmostEqual(outputs.loss.item(), 18.5925, 2)
transformers/tests/models/unispeech_sat/test_modeling_unispeech_sat.py/0
{ "file_path": "transformers/tests/models/unispeech_sat/test_modeling_unispeech_sat.py", "repo_id": "transformers", "token_count": 17217 }
571
# Copyright 2023 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 VipLlava model.""" import copy import unittest import requests from parameterized import parameterized from transformers import ( AutoProcessor, VipLlavaConfig, VipLlavaForConditionalGeneration, VipLlavaModel, is_torch_available, is_vision_available, ) from transformers.testing_utils import ( cleanup, require_bitsandbytes, require_torch, slow, torch_device, ) from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor if is_torch_available(): import torch if is_vision_available(): from PIL import Image # Copied from transformers.tests.models.llava.test_modeling_llava.LlavaVisionText2TextModelTester with Llava->VipLlava class VipLlavaVisionText2TextModelTester: # Ignore copy def __init__( self, parent, ignore_index=-100, image_token_index=0, projector_hidden_act="gelu", seq_length=7, vision_feature_layers=[0, 0, 1, 1, 0], text_config={ "model_type": "llama", "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": 37, "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, "pad_token_id": 1, }, is_training=True, vision_config={ "batch_size": 12, "image_size": 8, "patch_size": 2, "num_channels": 3, "is_training": True, "hidden_size": 32, "projection_dim": 32, "num_hidden_layers": 2, "num_attention_heads": 4, "intermediate_size": 37, "dropout": 0.1, "attention_dropout": 0.1, "initializer_range": 0.02, }, ): self.parent = parent self.ignore_index = ignore_index self.image_token_index = image_token_index self.projector_hidden_act = projector_hidden_act self.vision_feature_layers = vision_feature_layers self.text_config = text_config self.vision_config = vision_config self.pad_token_id = text_config["pad_token_id"] self.num_hidden_layers = text_config["num_hidden_layers"] self.vocab_size = text_config["vocab_size"] self.hidden_size = text_config["hidden_size"] self.num_attention_heads = text_config["num_attention_heads"] self.is_training = is_training self.batch_size = 3 self.num_channels = 3 self.image_size = 336 self.num_image_tokens = (self.vision_config["image_size"] // self.vision_config["patch_size"]) ** 2 self.seq_length = seq_length + self.num_image_tokens self.encoder_seq_length = self.seq_length def get_config(self): return VipLlavaConfig( text_config=self.text_config, vision_config=self.vision_config, ignore_index=self.ignore_index, image_token_index=self.image_token_index, projector_hidden_act=self.projector_hidden_act, vision_feature_layers=self.vision_feature_layers, image_seq_length=self.num_image_tokens, ) def prepare_config_and_inputs(self): pixel_values = floats_tensor( [ self.batch_size, self.vision_config["num_channels"], self.vision_config["image_size"], self.vision_config["image_size"], ] ) config = self.get_config() return config, pixel_values def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, pixel_values = config_and_inputs input_ids = ids_tensor([self.batch_size, self.seq_length], config.text_config.vocab_size - 1) + 1 attention_mask = input_ids.ne(1).to(torch_device) input_ids[input_ids == config.image_token_index] = self.pad_token_id input_ids[:, : self.num_image_tokens] = config.image_token_index inputs_dict = { "pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask, } return config, inputs_dict @require_torch # Copied from transformers.tests.models.llava.test_modeling_llava.LlavaForConditionalGenerationModelTest with Llava->VipLlava class VipLlavaForConditionalGenerationModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase): """ Model tester for `VipLlavaForConditionalGeneration`. """ all_model_classes = ( ( VipLlavaModel, VipLlavaForConditionalGeneration, ) if is_torch_available() else () ) pipeline_model_mapping = {"image-text-to-text": VipLlavaForConditionalGeneration} if is_torch_available() else {} fx_compatible = False test_pruning = False test_resize_embeddings = True test_head_masking = False _is_composite = True def setUp(self): self.model_tester = VipLlavaVisionText2TextModelTester(self) common_properties = ["image_token_index", "vision_feature_layers", "image_seq_length"] self.config_tester = ConfigTester( self, config_class=VipLlavaConfig, has_text_modality=False, common_properties=common_properties ) def test_config(self): self.config_tester.run_common_tests() # Copied from tests.models.llava.test_modeling_llava.LlavaForConditionalGenerationModelTest.test_mismatching_num_image_tokens def test_mismatching_num_image_tokens(self): """ Tests that VLMs through an error with explicit message saying what is wrong when number of images doesn't match number of image tokens in the text. Also we need to test multi-image cases when one prompr has multiple image tokens. """ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config).to(torch_device) curr_input_dict = copy.deepcopy(input_dict) # in=place modifications further _ = model(**curr_input_dict) # successful forward with no modifications # remove one image but leave the image token in text curr_input_dict["pixel_values"] = curr_input_dict["pixel_values"][-1:, ...] with self.assertRaises(ValueError): _ = model(**curr_input_dict) # simulate multi-image case by concatenating inputs where each has exactly one image/image-token input_ids = curr_input_dict["input_ids"][:1] pixel_values = curr_input_dict["pixel_values"][:1] input_ids = torch.cat([input_ids, input_ids], dim=0) # one image and two image tokens raise an error with self.assertRaises(ValueError): _ = model(input_ids=input_ids, pixel_values=pixel_values) # two images and two image tokens don't raise an error pixel_values = torch.cat([pixel_values, pixel_values], dim=0) _ = model(input_ids=input_ids, pixel_values=pixel_values) @parameterized.expand( [ (-1,), ([-1],), ([-1, -2],), ], ) def test_vision_feature_layers(self, vision_feature_layers): """ Test that we can use either one vision feature layer, or a list of vision feature layers. """ # NOTE: vipllava uses vision_feature_layers instead of vision_feature_layer as the # config key. The reason is that other llava classes supported one vision feature layer # and added support for a list of layers with granite vision support, while vipllava # originally supported multiple feature layers, and added support for a single layer for # for compatibility reasons. config, input_dict = self.model_tester.prepare_config_and_inputs_for_common() config.vision_feature_layers = vision_feature_layers num_feature_layers = 1 if isinstance(vision_feature_layers, int) else len(vision_feature_layers) hidden_size = config.vision_config.hidden_size expected_features = hidden_size * num_feature_layers for model_class in self.all_model_classes: model = model_class(config).to(torch_device) # We should have the right number of input features, # and should be able to run a forward pass without exploding base_model = getattr(model, "model", model) assert base_model.multi_modal_projector.linear_1.in_features == expected_features model(**input_dict) @unittest.skip( reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" ) def test_training_gradient_checkpointing(self): pass @unittest.skip( reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" ) def test_training_gradient_checkpointing_use_reentrant(self): pass @unittest.skip( reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" ) def test_training_gradient_checkpointing_use_reentrant_false(self): pass @unittest.skip( "VLMs need lots of steps to prepare images/mask correctly to get pad-free inputs. Can be tested as part of LLM test" ) def test_flash_attention_2_padding_matches_padding_free_with_position_ids(self): pass @require_torch class VipLlavaForConditionalGenerationIntegrationTest(unittest.TestCase): def setUp(self): self.processor = AutoProcessor.from_pretrained("llava-hf/vip-llava-7b-hf") def tearDown(self): cleanup(torch_device, gc_collect=True) @slow @require_bitsandbytes def test_small_model_integration_test(self): model_id = "llava-hf/vip-llava-7b-hf" model = VipLlavaForConditionalGeneration.from_pretrained(model_id, load_in_4bit=True) processor = AutoProcessor.from_pretrained(model_id) url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/compel-neg.png" image = Image.open(requests.get(url, stream=True).raw) prompt = "USER: <image>\nCan you please describe this image?\nASSISTANT:" inputs = processor(prompt, image, return_tensors="pt").to(torch_device, torch.float16) outputs = model.generate(**inputs, max_new_tokens=10) EXPECTED_OUTPUT = "USER: \nCan you please describe this image?\nASSISTANT: The image features a brown and white cat sitting on" self.assertEqual(processor.decode(outputs[0], skip_special_tokens=True), EXPECTED_OUTPUT)
transformers/tests/models/vipllava/test_modeling_vipllava.py/0
{ "file_path": "transformers/tests/models/vipllava/test_modeling_vipllava.py", "repo_id": "transformers", "token_count": 5162 }
572
# Copyright 2023 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 ViTDet model.""" import unittest from transformers import VitDetConfig from transformers.testing_utils import is_flaky, require_torch, torch_device from transformers.utils import is_torch_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import VitDetBackbone, VitDetModel class VitDetModelTester: def __init__( self, parent, batch_size=13, image_size=30, patch_size=2, num_channels=3, is_training=True, use_labels=True, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=37, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, type_sequence_label_size=10, initializer_range=0.02, scope=None, ): self.parent = parent self.batch_size = batch_size self.image_size = image_size self.patch_size = patch_size self.num_channels = num_channels self.is_training = is_training self.use_labels = use_labels 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.type_sequence_label_size = type_sequence_label_size self.initializer_range = initializer_range self.scope = scope self.num_patches_one_direction = self.image_size // self.patch_size self.seq_length = (self.image_size // self.patch_size) ** 2 def prepare_config_and_inputs(self): pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) labels = None if self.use_labels: labels = ids_tensor([self.batch_size], self.type_sequence_label_size) config = self.get_config() return config, pixel_values, labels def get_config(self): return VitDetConfig( image_size=self.image_size, pretrain_image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, 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, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, is_decoder=False, initializer_range=self.initializer_range, ) def create_and_check_model(self, config, pixel_values, labels): model = VitDetModel(config=config) model.to(torch_device) model.eval() result = model(pixel_values) self.parent.assertEqual( result.last_hidden_state.shape, (self.batch_size, self.hidden_size, self.num_patches_one_direction, self.num_patches_one_direction), ) def create_and_check_backbone(self, config, pixel_values, labels): model = VitDetBackbone(config=config) model.to(torch_device) model.eval() result = model(pixel_values) # verify hidden states self.parent.assertEqual(len(result.feature_maps), len(config.out_features)) self.parent.assertListEqual( list(result.feature_maps[0].shape), [self.batch_size, self.hidden_size, self.num_patches_one_direction, self.num_patches_one_direction], ) # verify channels self.parent.assertEqual(len(model.channels), len(config.out_features)) self.parent.assertListEqual(model.channels, [config.hidden_size]) # verify backbone works with out_features=None config.out_features = None model = VitDetBackbone(config=config) model.to(torch_device) model.eval() result = model(pixel_values) # verify feature maps self.parent.assertEqual(len(result.feature_maps), 1) self.parent.assertListEqual( list(result.feature_maps[0].shape), [self.batch_size, self.hidden_size, self.num_patches_one_direction, self.num_patches_one_direction], ) # verify channels self.parent.assertEqual(len(model.channels), 1) self.parent.assertListEqual(model.channels, [config.hidden_size]) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, pixel_values, labels = config_and_inputs inputs_dict = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class VitDetModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): """ Here we also overwrite some of the tests of test_modeling_common.py, as VitDet does not use input_ids, inputs_embeds, attention_mask and seq_length. """ all_model_classes = (VitDetModel, VitDetBackbone) if is_torch_available() else () pipeline_model_mapping = {"feature-extraction": VitDetModel} if is_torch_available() else {} fx_compatible = False test_pruning = False test_resize_embeddings = False test_head_masking = False test_torch_exportable = True def setUp(self): self.model_tester = VitDetModelTester(self) self.config_tester = ConfigTester(self, config_class=VitDetConfig, has_text_modality=False, hidden_size=37) @is_flaky(max_attempts=3, description="`torch.nn.init.trunc_normal_` is flaky.") def test_initialization(self): super().test_initialization() # TODO: Fix me (once this model gets more usage) @unittest.skip(reason="Does not work on the tiny model as we keep hitting edge cases.") def test_cpu_offload(self): super().test_cpu_offload() # TODO: Fix me (once this model gets more usage) @unittest.skip(reason="Does not work on the tiny model as we keep hitting edge cases.") def test_disk_offload_bin(self): super().test_disk_offload() @unittest.skip(reason="Does not work on the tiny model as we keep hitting edge cases.") def test_disk_offload_safetensors(self): super().test_disk_offload() # TODO: Fix me (once this model gets more usage) @unittest.skip(reason="Does not work on the tiny model as we keep hitting edge cases.") def test_model_parallelism(self): super().test_model_parallelism() def test_config(self): self.config_tester.run_common_tests() @unittest.skip(reason="VitDet does not use inputs_embeds") def test_inputs_embeds(self): pass def test_model_get_set_embeddings(self): config, _ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) self.assertIsInstance(model.get_input_embeddings(), (nn.Module)) x = model.get_output_embeddings() self.assertTrue(x is None or isinstance(x, nn.Linear)) 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_backbone(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*config_and_inputs) def test_hidden_states_output(self): def check_hidden_states_output(inputs_dict, config, model_class): model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) hidden_states = outputs.hidden_states expected_num_stages = self.model_tester.num_hidden_layers self.assertEqual(len(hidden_states), expected_num_stages + 1) # VitDet's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:]), [ self.model_tester.num_patches_one_direction, self.model_tester.num_patches_one_direction, ], ) config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: inputs_dict["output_hidden_states"] = True check_hidden_states_output(inputs_dict, config, model_class) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] config.output_hidden_states = True check_hidden_states_output(inputs_dict, config, model_class) # overwrite since VitDet only supports retraining gradients of hidden states 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 = self.has_attentions # 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) inputs = self._prepare_for_class(inputs_dict, model_class) outputs = model(**inputs) 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) @unittest.skip(reason="VitDet does not support feedforward chunking") def test_feed_forward_chunking(self): pass @unittest.skip(reason="VitDet does not have standalone checkpoints since it used as backbone in other models") def test_model_from_pretrained(self): pass def test_non_square_image(self): non_square_image_size = (32, 40) patch_size = (2, 2) config = self.model_tester.get_config() config.image_size = non_square_image_size config.patch_size = patch_size model = VitDetModel(config=config) model.to(torch_device) model.eval() batch_size = self.model_tester.batch_size # Create a dummy input tensor with non-square spatial dimensions. pixel_values = floats_tensor( [batch_size, config.num_channels, non_square_image_size[0], non_square_image_size[1]] ) result = model(pixel_values) expected_height = non_square_image_size[0] / patch_size[0] expected_width = non_square_image_size[1] / patch_size[1] expected_shape = (batch_size, config.hidden_size, expected_height, expected_width) self.assertEqual(result.last_hidden_state.shape, expected_shape) @require_torch class VitDetBackboneTest(unittest.TestCase, BackboneTesterMixin): all_model_classes = (VitDetBackbone,) if is_torch_available() else () config_class = VitDetConfig has_attentions = False def setUp(self): self.model_tester = VitDetModelTester(self)
transformers/tests/models/vitdet/test_modeling_vitdet.py/0
{ "file_path": "transformers/tests/models/vitdet/test_modeling_vitdet.py", "repo_id": "transformers", "token_count": 5109 }
573
# coding=utf-8 # 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 V-JEPA2 model.""" import unittest import numpy as np from transformers import VJEPA2Config from transformers.testing_utils import ( is_flaky, require_torch, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor from ...test_pipeline_mixin import PipelineTesterMixin from ...test_video_processing_common import ( prepare_video_inputs, ) if is_torch_available(): import torch from torch import nn from transformers import VJEPA2ForVideoClassification, VJEPA2Model if is_vision_available(): from PIL import Image from transformers import AutoVideoProcessor VJEPA_HF_MODEL = "facebook/vjepa2-vitl-fpc64-256" class VJEPA2ModelTester: def __init__( self, parent, batch_size=2, image_size=16, patch_size=16, num_channels=3, hidden_size=32, num_hidden_layers=4, num_attention_heads=2, num_frames=2, mlp_ratio=1, pred_hidden_size=32, pred_num_attention_heads=2, pred_num_hidden_layers=2, pred_num_mask_tokens=10, is_training=False, attn_implementation="sdpa", mask_ratio=0.5, ): self.parent = parent self.batch_size = batch_size self.image_size = image_size self.patch_size = patch_size self.num_channels = num_channels self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.num_frames = num_frames self.mlp_ratio = mlp_ratio self.pred_hidden_size = pred_hidden_size self.pred_num_attention_heads = pred_num_attention_heads self.pred_num_hidden_layers = pred_num_hidden_layers self.pred_num_mask_tokens = pred_num_mask_tokens self.attn_implementation = attn_implementation self.is_training = is_training self.mask_ratio = mask_ratio num_patches = ((image_size // patch_size) ** 2) * (num_frames // 2) self.seq_length = num_patches self.num_masks = int(self.mask_ratio * self.seq_length) self.mask_length = num_patches def prepare_config_and_inputs(self): pixel_values_videos = floats_tensor( [ self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size, ] ) config = self.get_config() return config, pixel_values_videos def get_config(self): return VJEPA2Config( crop_size=self.image_size, frames_per_clip=self.num_frames, hidden_size=self.hidden_size, num_attention_heads=self.num_attention_heads, num_hidden_layers=self.num_hidden_layers, mlp_ratio=self.mlp_ratio, pred_hidden_size=self.pred_hidden_size, pred_num_attention_heads=self.pred_num_attention_heads, pred_num_hidden_layers=self.pred_num_hidden_layers, pred_num_mask_tokens=self.pred_num_mask_tokens, ) def create_and_check_model(self, config, pixel_values_videos): model = VJEPA2Model(config=config) model.to(torch_device) model.eval() result = model(pixel_values_videos) self.parent.assertEqual( result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size), ) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() ( config, pixel_values_videos, ) = config_and_inputs inputs_dict = {"pixel_values_videos": pixel_values_videos} return config, inputs_dict @require_torch class VJEPA2ModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): """ Here we also overwrite some of the tests of test_modeling_common.py, as VJEPA2 does not use input_ids, inputs_embeds, attention_mask and seq_length. """ test_torch_exportable = True all_model_classes = (VJEPA2Model, VJEPA2ForVideoClassification) if is_torch_available() else () fx_compatible = False pipeline_model_mapping = {} test_pruning = False test_resize_embeddings = False test_head_masking = False def setUp(self): self.model_tester = VJEPA2ModelTester(self) self.config_tester = ConfigTester(self, config_class=VJEPA2Config, has_text_modality=False, hidden_size=37) @is_flaky(max_attempts=3, description="`torch.nn.init.trunc_normal_` is flaky.") def test_initialization(self): super().test_initialization() def test_config(self): self.config_tester.run_common_tests() @unittest.skip(reason="VJEPA2 does not use inputs_embeds") def test_inputs_embeds(self): pass @unittest.skip( reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" ) def test_training_gradient_checkpointing(self): pass @unittest.skip( reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" ) def test_training_gradient_checkpointing_use_reentrant(self): pass @unittest.skip( reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124" ) def test_training_gradient_checkpointing_use_reentrant_false(self): pass def test_model_get_set_embeddings(self): config, _ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) self.assertIsInstance(model.get_input_embeddings(), (nn.Module)) x = model.get_output_embeddings() self.assertTrue(x is None or isinstance(x, nn.Linear)) def test_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) @unittest.skip(reason="VJEPA2 does not support feedforward chunking yet") def test_feed_forward_chunking(self): pass @slow def test_model_from_pretrained(self): model = VJEPA2Model.from_pretrained(VJEPA_HF_MODEL) self.assertIsNotNone(model) # We will verify our results on an image of cute cats def prepare_img(): image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") return image def prepare_random_video(image_size=256): videos = prepare_video_inputs( batch_size=1, num_frames=16, num_channels=3, min_resolution=image_size, max_resolution=image_size, equal_resolution=True, return_tensors="torch", ) return videos @require_torch @require_vision class VJEPA2ModelIntegrationTest(unittest.TestCase): @cached_property def default_video_processor(self): return AutoVideoProcessor.from_pretrained(VJEPA_HF_MODEL) if is_vision_available() else None @slow def test_inference_image(self): model = VJEPA2Model.from_pretrained(VJEPA_HF_MODEL).to(torch_device) video_processor = self.default_video_processor image = prepare_img() inputs = video_processor(torch.Tensor(np.array(image)), return_tensors="pt").to(torch_device) pixel_values_videos = inputs.pixel_values_videos pixel_values_videos = pixel_values_videos.repeat(1, model.config.frames_per_clip, 1, 1, 1) # forward pass with torch.no_grad(): outputs = model(pixel_values_videos) # verify the last hidden states expected_shape = torch.Size((1, 8192, 1024)) self.assertEqual(outputs.last_hidden_state.shape, expected_shape) expected_slice = torch.tensor( [[-0.0061, -1.8365, 2.7343], [-2.5938, -2.7181, -0.1663], [-1.7993, -2.2430, -1.1388]], device=torch_device, ) torch.testing.assert_close(outputs.last_hidden_state[0, :3, :3], expected_slice, rtol=8e-2, atol=8e-2) @slow def test_inference_video(self): model = VJEPA2Model.from_pretrained(VJEPA_HF_MODEL).to(torch_device) video_processor = self.default_video_processor video = prepare_random_video() inputs = video_processor(video, return_tensors="pt").to(torch_device) pixel_values_videos = inputs.pixel_values_videos # forward pass with torch.no_grad(): outputs = model(pixel_values_videos) # verify the last hidden states expected_shape = torch.Size((1, 2048, 1024)) self.assertEqual(outputs.last_hidden_state.shape, expected_shape) @slow def test_predictor_outputs(self): model = VJEPA2Model.from_pretrained(VJEPA_HF_MODEL).to(torch_device) video_processor = self.default_video_processor video = prepare_random_video() inputs = video_processor(video, return_tensors="pt").to(torch_device) pixel_values_videos = inputs.pixel_values_videos # forward pass with torch.no_grad(): outputs = model(pixel_values_videos) # verify the last hidden states expected_shape = torch.Size((1, 2048, 1024)) self.assertEqual(outputs.predictor_output.last_hidden_state.shape, expected_shape) @slow def test_predictor_full_mask(self): model = VJEPA2Model.from_pretrained(VJEPA_HF_MODEL).to(torch_device) video_processor = self.default_video_processor video = prepare_random_video() inputs = video_processor(video, return_tensors="pt").to(torch_device) pixel_values_videos = inputs.pixel_values_videos # forward pass with torch.no_grad(): context_mask = [torch.arange(2048, device=pixel_values_videos.device).unsqueeze(0)] predictor_mask = context_mask outputs = model(pixel_values_videos, context_mask=context_mask, target_mask=predictor_mask) # verify the last hidden states expected_shape = torch.Size((1, 2048, 1024)) self.assertEqual(outputs.predictor_output.last_hidden_state.shape, expected_shape) @slow def test_predictor_partial_mask(self): model = VJEPA2Model.from_pretrained(VJEPA_HF_MODEL).to(torch_device) video_processor = self.default_video_processor video = prepare_random_video() inputs = video_processor(video, return_tensors="pt").to(torch_device) pixel_values_videos = inputs.pixel_values_videos num_patches = 2048 num_masks = 100 # forward pass with torch.no_grad(): pos_ids = torch.arange(num_patches, device=pixel_values_videos.device) context_mask = [pos_ids[0 : num_patches - num_masks].unsqueeze(0)] predictor_mask = [pos_ids[num_patches - num_masks :].unsqueeze(0)] outputs = model(pixel_values_videos, context_mask=context_mask, target_mask=predictor_mask) # verify the last hidden states expected_shape = torch.Size((1, num_masks, 1024)) self.assertEqual(outputs.predictor_output.last_hidden_state.shape, expected_shape) @slow def test_video_classification(self): checkpoint = "facebook/vjepa2-vitl-fpc16-256-ssv2" model = VJEPA2ForVideoClassification.from_pretrained(checkpoint).to(torch_device) video_processor = AutoVideoProcessor.from_pretrained(checkpoint) sample_video = np.ones((16, 3, 256, 256)) inputs = video_processor(sample_video, return_tensors="pt").to(torch_device) with torch.no_grad(): outputs = model(**inputs) self.assertEqual(outputs.logits.shape, (1, 174)) expected_logits = torch.tensor([0.8814, -0.1195, -0.6389], device=torch_device) resulted_logits = outputs.logits[0, 100:103] torch.testing.assert_close(resulted_logits, expected_logits, rtol=1e-2, atol=1e-2)
transformers/tests/models/vjepa2/test_modeling_vjepa2.py/0
{ "file_path": "transformers/tests/models/vjepa2/test_modeling_vjepa2.py", "repo_id": "transformers", "token_count": 5524 }
574
# Copyright 2021 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 json import os import shutil import tempfile import unittest from multiprocessing import get_context from pathlib import Path import datasets import numpy as np from datasets import load_dataset from parameterized import parameterized from transformers import AutoFeatureExtractor, AutoProcessor from transformers.models.wav2vec2 import Wav2Vec2CTCTokenizer, Wav2Vec2FeatureExtractor from transformers.models.wav2vec2.tokenization_wav2vec2 import VOCAB_FILES_NAMES from transformers.testing_utils import require_pyctcdecode, require_torch, require_torchaudio, slow from transformers.utils import FEATURE_EXTRACTOR_NAME, is_pyctcdecode_available, is_torch_available from ..wav2vec2.test_feature_extraction_wav2vec2 import floats_list if is_pyctcdecode_available(): from huggingface_hub import snapshot_download from pyctcdecode import BeamSearchDecoderCTC from transformers.models.wav2vec2_with_lm import Wav2Vec2ProcessorWithLM from transformers.models.wav2vec2_with_lm.processing_wav2vec2_with_lm import Wav2Vec2DecoderWithLMOutput if is_torch_available(): from transformers import Wav2Vec2ForCTC @require_pyctcdecode class Wav2Vec2ProcessorWithLMTest(unittest.TestCase): def setUp(self): vocab = "| <pad> <unk> <s> </s> a b c d e f g h i j k".split() vocab_tokens = dict(zip(vocab, range(len(vocab)))) self.add_kwargs_tokens_map = { "unk_token": "<unk>", "bos_token": "<s>", "eos_token": "</s>", } feature_extractor_map = { "feature_size": 1, "padding_value": 0.0, "sampling_rate": 16000, "return_attention_mask": False, "do_normalize": True, } self.tmpdirname = tempfile.mkdtemp() self.vocab_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"]) self.feature_extraction_file = os.path.join(self.tmpdirname, FEATURE_EXTRACTOR_NAME) with open(self.vocab_file, "w", encoding="utf-8") as fp: fp.write(json.dumps(vocab_tokens) + "\n") with open(self.feature_extraction_file, "w", encoding="utf-8") as fp: fp.write(json.dumps(feature_extractor_map) + "\n") # load decoder from hub self.decoder_name = "hf-internal-testing/ngram-beam-search-decoder" def get_tokenizer(self, **kwargs_init): kwargs = self.add_kwargs_tokens_map.copy() kwargs.update(kwargs_init) return Wav2Vec2CTCTokenizer.from_pretrained(self.tmpdirname, **kwargs) def get_feature_extractor(self, **kwargs): return Wav2Vec2FeatureExtractor.from_pretrained(self.tmpdirname, **kwargs) def get_decoder(self, **kwargs): return BeamSearchDecoderCTC.load_from_hf_hub(self.decoder_name, **kwargs) def tearDown(self): shutil.rmtree(self.tmpdirname) def test_save_load_pretrained_default(self): tokenizer = self.get_tokenizer() feature_extractor = self.get_feature_extractor() decoder = self.get_decoder() processor = Wav2Vec2ProcessorWithLM(tokenizer=tokenizer, feature_extractor=feature_extractor, decoder=decoder) processor.save_pretrained(self.tmpdirname) processor = Wav2Vec2ProcessorWithLM.from_pretrained(self.tmpdirname) # tokenizer self.assertEqual(processor.tokenizer.get_vocab(), tokenizer.get_vocab()) self.assertIsInstance(processor.tokenizer, Wav2Vec2CTCTokenizer) # feature extractor self.assertEqual(processor.feature_extractor.to_json_string(), feature_extractor.to_json_string()) self.assertIsInstance(processor.feature_extractor, Wav2Vec2FeatureExtractor) # decoder self.assertEqual(processor.decoder._alphabet.labels, decoder._alphabet.labels) self.assertEqual( processor.decoder.model_container[decoder._model_key]._unigram_set, decoder.model_container[decoder._model_key]._unigram_set, ) self.assertIsInstance(processor.decoder, BeamSearchDecoderCTC) def test_save_load_pretrained_additional_features(self): processor = Wav2Vec2ProcessorWithLM( tokenizer=self.get_tokenizer(), feature_extractor=self.get_feature_extractor(), decoder=self.get_decoder() ) processor.save_pretrained(self.tmpdirname) # make sure that error is thrown when decoder alphabet doesn't match processor = Wav2Vec2ProcessorWithLM.from_pretrained( self.tmpdirname, alpha=5.0, beta=3.0, score_boundary=-7.0, unk_score_offset=3 ) # decoder self.assertEqual(processor.language_model.alpha, 5.0) self.assertEqual(processor.language_model.beta, 3.0) self.assertEqual(processor.language_model.score_boundary, -7.0) self.assertEqual(processor.language_model.unk_score_offset, 3) def test_load_decoder_tokenizer_mismatch_content(self): tokenizer = self.get_tokenizer() # add token to trigger raise tokenizer.add_tokens(["xx"]) with self.assertRaisesRegex(ValueError, "include"): Wav2Vec2ProcessorWithLM( tokenizer=tokenizer, feature_extractor=self.get_feature_extractor(), decoder=self.get_decoder() ) def test_feature_extractor(self): feature_extractor = self.get_feature_extractor() tokenizer = self.get_tokenizer() decoder = self.get_decoder() processor = Wav2Vec2ProcessorWithLM(tokenizer=tokenizer, feature_extractor=feature_extractor, decoder=decoder) raw_speech = floats_list((3, 1000)) input_feat_extract = feature_extractor(raw_speech, return_tensors="np") input_processor = processor(raw_speech, return_tensors="np") for key in input_feat_extract: self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1e-2) def test_another_feature_extractor(self): feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/w2v-bert-2.0") tokenizer = self.get_tokenizer() decoder = self.get_decoder() processor = Wav2Vec2ProcessorWithLM(tokenizer=tokenizer, feature_extractor=feature_extractor, decoder=decoder) raw_speech = floats_list((3, 1000)) input_feat_extract = feature_extractor(raw_speech, return_tensors="np") input_processor = processor(raw_speech, return_tensors="np") for key in input_feat_extract: self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1e-2) self.assertListEqual( processor.model_input_names, feature_extractor.model_input_names, msg="`processor` and `feature_extractor` model input names do not match", ) def test_wrong_feature_extractor_raises_error(self): feature_extractor = AutoFeatureExtractor.from_pretrained("openai/whisper-large-v3") tokenizer = self.get_tokenizer() decoder = self.get_decoder() with self.assertRaises(ValueError): Wav2Vec2ProcessorWithLM(tokenizer=tokenizer, feature_extractor=feature_extractor, decoder=decoder) def test_tokenizer(self): feature_extractor = self.get_feature_extractor() tokenizer = self.get_tokenizer() decoder = self.get_decoder() processor = Wav2Vec2ProcessorWithLM(tokenizer=tokenizer, feature_extractor=feature_extractor, decoder=decoder) input_str = "This is a test string" encoded_processor = processor(text=input_str) encoded_tok = tokenizer(input_str) for key in encoded_tok: self.assertListEqual(encoded_tok[key], encoded_processor[key]) def _get_dummy_logits(self, shape=(2, 10, 16), seed=77): np.random.seed(seed) return np.random.rand(*shape) def test_decoder(self): feature_extractor = self.get_feature_extractor() tokenizer = self.get_tokenizer() decoder = self.get_decoder() processor = Wav2Vec2ProcessorWithLM(tokenizer=tokenizer, feature_extractor=feature_extractor, decoder=decoder) logits = self._get_dummy_logits(shape=(10, 16), seed=13) decoded_processor = processor.decode(logits) decoded_decoder = decoder.decode_beams(logits)[0] self.assertEqual(decoded_decoder[0], decoded_processor.text) self.assertEqual("</s> <s> </s>", decoded_processor.text) self.assertEqual(decoded_decoder[-2], decoded_processor.logit_score) self.assertEqual(decoded_decoder[-1], decoded_processor.lm_score) @parameterized.expand([[None], ["fork"], ["spawn"]]) def test_decoder_batch(self, pool_context): feature_extractor = self.get_feature_extractor() tokenizer = self.get_tokenizer() decoder = self.get_decoder() processor = Wav2Vec2ProcessorWithLM(tokenizer=tokenizer, feature_extractor=feature_extractor, decoder=decoder) logits = self._get_dummy_logits() # note: pool should be instantiated *after* Wav2Vec2ProcessorWithLM. # otherwise, the LM won't be available to the pool's sub-processes. # manual logic used to allow parameterized test for both pool=None and pool=Pool(...) if pool_context is None: decoded_processor = processor.batch_decode(logits) else: with get_context(pool_context).Pool() as pool: decoded_processor = processor.batch_decode(logits, pool) logits_list = list(logits) with get_context("fork").Pool() as p: decoded_beams = decoder.decode_beams_batch(p, logits_list) texts_decoder, logit_scores_decoder, lm_scores_decoder = [], [], [] for beams in decoded_beams: texts_decoder.append(beams[0][0]) logit_scores_decoder.append(beams[0][-2]) lm_scores_decoder.append(beams[0][-1]) self.assertListEqual(texts_decoder, decoded_processor.text) self.assertListEqual(["<s> <s> </s>", "<s> <s> <s>"], decoded_processor.text) self.assertListEqual(logit_scores_decoder, decoded_processor.logit_score) self.assertListEqual(lm_scores_decoder, decoded_processor.lm_score) def test_decoder_with_params(self): feature_extractor = self.get_feature_extractor() tokenizer = self.get_tokenizer() decoder = self.get_decoder() processor = Wav2Vec2ProcessorWithLM(tokenizer=tokenizer, feature_extractor=feature_extractor, decoder=decoder) logits = self._get_dummy_logits() beam_width = 15 beam_prune_logp = -20.0 token_min_logp = -4.0 decoded_processor_out = processor.batch_decode( logits, beam_width=beam_width, beam_prune_logp=beam_prune_logp, token_min_logp=token_min_logp, ) decoded_processor = decoded_processor_out.text logits_list = list(logits) with get_context("fork").Pool() as pool: decoded_decoder_out = decoder.decode_beams_batch( pool, logits_list, beam_width=beam_width, beam_prune_logp=beam_prune_logp, token_min_logp=token_min_logp, ) decoded_decoder = [d[0][0] for d in decoded_decoder_out] logit_scores = [d[0][2] for d in decoded_decoder_out] lm_scores = [d[0][3] for d in decoded_decoder_out] self.assertListEqual(decoded_decoder, decoded_processor) self.assertListEqual(["</s> <s> <s>", "<s> <s> <s>"], decoded_processor) self.assertTrue(np.array_equal(logit_scores, decoded_processor_out.logit_score)) self.assertTrue(np.allclose([-20.054, -18.447], logit_scores, atol=1e-3)) self.assertTrue(np.array_equal(lm_scores, decoded_processor_out.lm_score)) self.assertTrue(np.allclose([-15.554, -13.9474], lm_scores, atol=1e-3)) def test_decoder_with_params_of_lm(self): feature_extractor = self.get_feature_extractor() tokenizer = self.get_tokenizer() decoder = self.get_decoder() processor = Wav2Vec2ProcessorWithLM(tokenizer=tokenizer, feature_extractor=feature_extractor, decoder=decoder) logits = self._get_dummy_logits() alpha = 2.0 beta = 5.0 unk_score_offset = -20.0 lm_score_boundary = True decoded_processor_out = processor.batch_decode( logits, alpha=alpha, beta=beta, unk_score_offset=unk_score_offset, lm_score_boundary=lm_score_boundary, ) decoded_processor = decoded_processor_out.text logits_list = list(logits) decoder.reset_params( alpha=alpha, beta=beta, unk_score_offset=unk_score_offset, lm_score_boundary=lm_score_boundary, ) with get_context("fork").Pool() as pool: decoded_decoder_out = decoder.decode_beams_batch( pool, logits_list, ) decoded_decoder = [d[0][0] for d in decoded_decoder_out] self.assertListEqual(decoded_decoder, decoded_processor) self.assertListEqual(["<s> </s> <s> </s> </s>", "</s> </s> <s> </s> </s>"], decoded_processor) lm_model = processor.decoder.model_container[processor.decoder._model_key] self.assertEqual(lm_model.alpha, 2.0) self.assertEqual(lm_model.beta, 5.0) self.assertEqual(lm_model.unk_score_offset, -20.0) self.assertEqual(lm_model.score_boundary, True) def test_decoder_download_ignores_files(self): processor = Wav2Vec2ProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm") language_model = processor.decoder.model_container[processor.decoder._model_key] path_to_cached_dir = Path(language_model._kenlm_model.path.decode("utf-8")).parent.parent.absolute() downloaded_decoder_files = os.listdir(path_to_cached_dir) expected_decoder_files = ["alphabet.json", "language_model"] downloaded_decoder_files.sort() expected_decoder_files.sort() # test that only decoder relevant files from # https://huggingface.co/hf-internal-testing/processor_with_lm/tree/main # are downloaded and none of the rest (e.g. README.md, ...) self.assertListEqual(downloaded_decoder_files, expected_decoder_files) def test_decoder_local_files(self): local_dir = snapshot_download("hf-internal-testing/processor_with_lm") processor = Wav2Vec2ProcessorWithLM.from_pretrained(local_dir) language_model = processor.decoder.model_container[processor.decoder._model_key] path_to_cached_dir = Path(language_model._kenlm_model.path.decode("utf-8")).parent.parent.absolute() local_decoder_files = os.listdir(local_dir) expected_decoder_files = os.listdir(path_to_cached_dir) local_decoder_files.sort() expected_decoder_files.sort() # test that both decoder form hub and local files in cache are the same self.assertListEqual(local_decoder_files, expected_decoder_files) def test_processor_from_auto_processor(self): processor_wav2vec2 = Wav2Vec2ProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm") processor_auto = AutoProcessor.from_pretrained("hf-internal-testing/processor_with_lm") raw_speech = floats_list((3, 1000)) input_wav2vec2 = processor_wav2vec2(raw_speech, return_tensors="np") input_auto = processor_auto(raw_speech, return_tensors="np") for key in input_wav2vec2: self.assertAlmostEqual(input_wav2vec2[key].sum(), input_auto[key].sum(), delta=1e-2) logits = self._get_dummy_logits() decoded_wav2vec2 = processor_wav2vec2.batch_decode(logits) decoded_auto = processor_auto.batch_decode(logits) self.assertListEqual(decoded_wav2vec2.text, decoded_auto.text) @staticmethod def get_from_offsets(offsets, key): retrieved_list = [d[key] for d in offsets] return retrieved_list def test_offsets_integration_fast(self): processor = Wav2Vec2ProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm") logits = self._get_dummy_logits()[0] outputs = processor.decode(logits, output_word_offsets=True) # check Wav2Vec2CTCTokenizerOutput keys for word self.assertEqual(len(outputs.keys()), 4) self.assertTrue("text" in outputs) self.assertTrue("word_offsets" in outputs) self.assertTrue(isinstance(outputs, Wav2Vec2DecoderWithLMOutput)) self.assertEqual(" ".join(self.get_from_offsets(outputs["word_offsets"], "word")), outputs.text) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"], "word"), ["<s>", "<s>", "</s>"]) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"], "start_offset"), [0, 2, 4]) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"], "end_offset"), [1, 3, 5]) def test_offsets_integration_fast_batch(self): processor = Wav2Vec2ProcessorWithLM.from_pretrained("hf-internal-testing/processor_with_lm") logits = self._get_dummy_logits() outputs = processor.batch_decode(logits, output_word_offsets=True) # check Wav2Vec2CTCTokenizerOutput keys for word self.assertEqual(len(outputs.keys()), 4) self.assertTrue("text" in outputs) self.assertTrue("word_offsets" in outputs) self.assertTrue(isinstance(outputs, Wav2Vec2DecoderWithLMOutput)) self.assertListEqual( [" ".join(self.get_from_offsets(o, "word")) for o in outputs["word_offsets"]], outputs.text ) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"][0], "word"), ["<s>", "<s>", "</s>"]) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"][0], "start_offset"), [0, 2, 4]) self.assertListEqual(self.get_from_offsets(outputs["word_offsets"][0], "end_offset"), [1, 3, 5]) @slow @require_torch @require_torchaudio def test_word_time_stamp_integration(self): import torch ds = load_dataset("mozilla-foundation/common_voice_11_0", "en", split="train", streaming=True) ds = ds.cast_column("audio", datasets.Audio(sampling_rate=16_000)) ds_iter = iter(ds) sample = next(ds_iter) processor = AutoProcessor.from_pretrained("patrickvonplaten/wav2vec2-base-100h-with-lm") model = Wav2Vec2ForCTC.from_pretrained("patrickvonplaten/wav2vec2-base-100h-with-lm") input_values = processor(sample["audio"]["array"], return_tensors="pt").input_values with torch.no_grad(): logits = model(input_values).logits.cpu().numpy() output = processor.decode(logits[0], output_word_offsets=True) time_offset = model.config.inputs_to_logits_ratio / processor.feature_extractor.sampling_rate word_time_stamps = [ { "start_time": d["start_offset"] * time_offset, "end_time": d["end_offset"] * time_offset, "word": d["word"], } for d in output["word_offsets"] ] EXPECTED_TEXT = "WHY DOES MILISANDRA LOOK LIKE SHE WANTS TO CONSUME JOHN SNOW ON THE RIVER AT THE WALL" EXPECTED_TEXT = "THE TRACK APPEARS ON THE COMPILATION ALBUM CRAFT FORKS" # output words self.assertEqual(" ".join(self.get_from_offsets(word_time_stamps, "word")), EXPECTED_TEXT) self.assertEqual(" ".join(self.get_from_offsets(word_time_stamps, "word")), output.text) # output times start_times = torch.tensor(self.get_from_offsets(word_time_stamps, "start_time")) end_times = torch.tensor(self.get_from_offsets(word_time_stamps, "end_time")) # fmt: off expected_start_tensor = torch.tensor([0.6800, 0.8800, 1.1800, 1.8600, 1.9600, 2.1000, 3.0000, 3.5600, 3.9800]) expected_end_tensor = torch.tensor([0.7800, 1.1000, 1.6600, 1.9200, 2.0400, 2.8000, 3.3000, 3.8800, 4.2800]) # fmt: on torch.testing.assert_close(start_times, expected_start_tensor, rtol=0.01, atol=0.01) torch.testing.assert_close(end_times, expected_end_tensor, rtol=0.01, atol=0.01)
transformers/tests/models/wav2vec2_with_lm/test_processing_wav2vec2_with_lm.py/0
{ "file_path": "transformers/tests/models/wav2vec2_with_lm/test_processing_wav2vec2_with_lm.py", "repo_id": "transformers", "token_count": 9099 }
575
# 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 XLMConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin 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 ( XLMForMultipleChoice, XLMForQuestionAnswering, XLMForQuestionAnsweringSimple, XLMForSequenceClassification, XLMForTokenClassification, XLMModel, XLMWithLMHeadModel, ) from transformers.models.xlm.modeling_xlm import create_sinusoidal_embeddings class XLMModelTester: def __init__( self, parent, batch_size=13, seq_length=7, is_training=True, use_input_lengths=True, use_token_type_ids=True, use_labels=True, gelu_activation=True, sinusoidal_embeddings=False, causal=False, asm=False, n_langs=2, vocab_size=99, n_special=0, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_sequence_label_size=2, initializer_range=0.02, num_labels=2, num_choices=4, summary_type="last", use_proj=True, scope=None, bos_token_id=0, ): self.parent = parent self.batch_size = batch_size self.seq_length = seq_length self.is_training = is_training self.use_input_lengths = use_input_lengths self.use_token_type_ids = use_token_type_ids self.use_labels = use_labels self.gelu_activation = gelu_activation self.sinusoidal_embeddings = sinusoidal_embeddings self.causal = causal self.asm = asm self.n_langs = n_langs self.vocab_size = vocab_size self.n_special = n_special self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads 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_sequence_label_size = type_sequence_label_size self.initializer_range = initializer_range self.num_labels = num_labels self.num_choices = num_choices self.summary_type = summary_type self.use_proj = use_proj self.scope = scope self.bos_token_id = bos_token_id def prepare_config_and_inputs(self): input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) input_mask = random_attention_mask([self.batch_size, self.seq_length]) input_lengths = None if self.use_input_lengths: input_lengths = ( ids_tensor([self.batch_size], vocab_size=2) + self.seq_length - 2 ) # small variation of seq_length token_type_ids = None if self.use_token_type_ids: token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.n_langs) sequence_labels = None token_labels = None is_impossible_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) is_impossible_labels = ids_tensor([self.batch_size], 2).float() choice_labels = ids_tensor([self.batch_size], self.num_choices) config = self.get_config() return ( config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) def get_config(self): return XLMConfig( vocab_size=self.vocab_size, n_special=self.n_special, emb_dim=self.hidden_size, n_layers=self.num_hidden_layers, n_heads=self.num_attention_heads, dropout=self.hidden_dropout_prob, attention_dropout=self.attention_probs_dropout_prob, gelu_activation=self.gelu_activation, sinusoidal_embeddings=self.sinusoidal_embeddings, asm=self.asm, causal=self.causal, n_langs=self.n_langs, max_position_embeddings=self.max_position_embeddings, initializer_range=self.initializer_range, summary_type=self.summary_type, use_proj=self.use_proj, num_labels=self.num_labels, bos_token_id=self.bos_token_id, ) def create_and_check_xlm_model( self, config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ): model = XLMModel(config=config) model.to(torch_device) model.eval() result = model(input_ids, lengths=input_lengths, langs=token_type_ids) result = model(input_ids, langs=token_type_ids) 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_xlm_lm_head( self, config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ): model = XLMWithLMHeadModel(config) model.to(torch_device) model.eval() result = model(input_ids, token_type_ids=token_type_ids, labels=token_labels) self.parent.assertEqual(result.loss.shape, ()) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size)) def create_and_check_xlm_simple_qa( self, config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ): model = XLMForQuestionAnsweringSimple(config) model.to(torch_device) model.eval() outputs = model(input_ids) outputs = model(input_ids, start_positions=sequence_labels, end_positions=sequence_labels) result = outputs 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_xlm_qa( self, config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ): model = XLMForQuestionAnswering(config) model.to(torch_device) model.eval() result = model(input_ids) result_with_labels = model( input_ids, start_positions=sequence_labels, end_positions=sequence_labels, cls_index=sequence_labels, is_impossible=is_impossible_labels, p_mask=input_mask, ) result_with_labels = model( input_ids, start_positions=sequence_labels, end_positions=sequence_labels, cls_index=sequence_labels, is_impossible=is_impossible_labels, ) (total_loss,) = result_with_labels.to_tuple() result_with_labels = model(input_ids, start_positions=sequence_labels, end_positions=sequence_labels) (total_loss,) = result_with_labels.to_tuple() self.parent.assertEqual(result_with_labels.loss.shape, ()) self.parent.assertEqual(result.start_top_log_probs.shape, (self.batch_size, model.config.start_n_top)) self.parent.assertEqual(result.start_top_index.shape, (self.batch_size, model.config.start_n_top)) self.parent.assertEqual( result.end_top_log_probs.shape, (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual( result.end_top_index.shape, (self.batch_size, model.config.start_n_top * model.config.end_n_top) ) self.parent.assertEqual(result.cls_logits.shape, (self.batch_size,)) def create_and_check_xlm_sequence_classif( self, config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ): model = XLMForSequenceClassification(config) model.to(torch_device) model.eval() result = model(input_ids) result = model(input_ids, labels=sequence_labels) self.parent.assertEqual(result.loss.shape, ()) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size)) def create_and_check_xlm_token_classif( self, config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ): config.num_labels = self.num_labels model = XLMForTokenClassification(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_xlm_for_multiple_choice( self, config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ): config.num_choices = self.num_choices model = XLMForMultipleChoice(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_token_type_ids = token_type_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, token_type_ids=multiple_choice_token_type_ids, 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, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, choice_labels, input_mask, ) = config_and_inputs inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "lengths": input_lengths} return config, inputs_dict @require_torch class XLMModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = ( ( XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, XLMForSequenceClassification, XLMForQuestionAnsweringSimple, XLMForTokenClassification, XLMForMultipleChoice, ) if is_torch_available() else () ) pipeline_model_mapping = ( { "feature-extraction": XLMModel, "fill-mask": XLMWithLMHeadModel, "question-answering": XLMForQuestionAnsweringSimple, "text-classification": XLMForSequenceClassification, "text-generation": XLMWithLMHeadModel, "token-classification": XLMForTokenClassification, "zero-shot": XLMForSequenceClassification, } if is_torch_available() else {} ) # TODO: Fix the failed tests def is_pipeline_test_to_skip( self, pipeline_test_case_name, config_class, model_architecture, tokenizer_name, image_processor_name, feature_extractor_name, processor_name, ): if ( pipeline_test_case_name == "QAPipelineTests" and tokenizer_name is not None and not tokenizer_name.endswith("Fast") ): # `QAPipelineTests` fails for a few models when the slower tokenizer are used. # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework) # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer return True return False # XLM has 2 QA models -> need to manually set the correct labels for one of them here def _prepare_for_class(self, inputs_dict, model_class, return_labels=False): inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels) if return_labels: if model_class.__name__ == "XLMForQuestionAnswering": inputs_dict["start_positions"] = torch.zeros( self.model_tester.batch_size, dtype=torch.long, device=torch_device ) inputs_dict["end_positions"] = torch.zeros( self.model_tester.batch_size, dtype=torch.long, device=torch_device ) return inputs_dict def setUp(self): self.model_tester = XLMModelTester(self) self.config_tester = ConfigTester(self, config_class=XLMConfig, emb_dim=37) def test_config(self): self.config_tester.run_common_tests() def test_xlm_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_model(*config_and_inputs) # Copied from tests/models/distilbert/test_modeling_distilbert.py with Distilbert->XLM def test_xlm_model_with_sinusoidal_encodings(self): config = XLMConfig(sinusoidal_embeddings=True) model = XLMModel(config=config) sinusoidal_pos_embds = torch.empty((config.max_position_embeddings, config.emb_dim), dtype=torch.float32) create_sinusoidal_embeddings(config.max_position_embeddings, config.emb_dim, sinusoidal_pos_embds) self.model_tester.parent.assertTrue(torch.equal(model.position_embeddings.weight, sinusoidal_pos_embds)) def test_xlm_lm_head(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_lm_head(*config_and_inputs) def test_xlm_simple_qa(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_simple_qa(*config_and_inputs) def test_xlm_qa(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_qa(*config_and_inputs) def test_xlm_sequence_classif(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_sequence_classif(*config_and_inputs) def test_xlm_token_classif(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_token_classif(*config_and_inputs) def test_xlm_for_multiple_choice(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_xlm_for_multiple_choice(*config_and_inputs) def _check_attentions_for_generate( self, batch_size, attentions, prompt_length, output_length, config, decoder_past_key_values ): # adds PAD dummy token, expected shape is off by 1 prompt_length += 1 output_length += 1 super()._check_attentions_for_generate( batch_size, attentions, prompt_length, output_length, config, decoder_past_key_values ) def _check_hidden_states_for_generate( self, batch_size, hidden_states, prompt_length, output_length, config, use_cache=False ): # adds PAD dummy token, expected shape is off by 1 prompt_length += 1 output_length += 1 super()._check_hidden_states_for_generate( batch_size, hidden_states, prompt_length, output_length, config, use_cache ) @slow def test_model_from_pretrained(self): model_name = "FacebookAI/xlm-mlm-en-2048" model = XLMModel.from_pretrained(model_name) self.assertIsNotNone(model) @require_torch class XLMModelLanguageGenerationTest(unittest.TestCase): @slow def test_lm_generate_xlm_mlm_en_2048(self): model = XLMWithLMHeadModel.from_pretrained("FacebookAI/xlm-mlm-en-2048") model.to(torch_device) input_ids = torch.tensor([[14, 447]], dtype=torch.long, device=torch_device) # the president expected_output_ids = [ 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, 14, 447, ] # the president the president the president the president the president the president the president the president the president the president # TODO(PVP): this and other input_ids I tried for generation give pretty bad results. Not sure why. Model might just not be made for auto-regressive inference output_ids = model.generate(input_ids, do_sample=False) self.assertListEqual(output_ids[0].tolist(), expected_output_ids)
transformers/tests/models/xlm/test_modeling_xlm.py/0
{ "file_path": "transformers/tests/models/xlm/test_modeling_xlm.py", "repo_id": "transformers", "token_count": 8956 }
576
# Copyright 2022 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 YOLOS model.""" import unittest from transformers import YolosConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import YolosForObjectDetection, YolosModel if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class YolosModelTester: def __init__( self, parent, batch_size=13, image_size=[30, 30], patch_size=2, num_channels=3, is_training=True, use_labels=True, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=37, hidden_act="gelu", hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, type_sequence_label_size=10, initializer_range=0.02, num_labels=3, scope=None, n_targets=8, num_detection_tokens=10, attn_implementation="eager", ): self.parent = parent self.batch_size = batch_size self.image_size = image_size self.patch_size = patch_size self.num_channels = num_channels self.is_training = is_training self.use_labels = use_labels 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.type_sequence_label_size = type_sequence_label_size self.initializer_range = initializer_range self.num_labels = num_labels self.scope = scope self.n_targets = n_targets self.num_detection_tokens = num_detection_tokens self.attn_implementation = attn_implementation # we set the expected sequence length (which is used in several tests) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) + num_detection_tokens num_patches = (image_size[1] // patch_size) * (image_size[0] // patch_size) self.expected_seq_len = num_patches + 1 + self.num_detection_tokens def prepare_config_and_inputs(self): pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]) labels = None if self.use_labels: # labels is a list of Dict (each Dict being the labels for a given example in the batch) labels = [] for i in range(self.batch_size): target = {} target["class_labels"] = torch.randint( high=self.num_labels, size=(self.n_targets,), device=torch_device ) target["boxes"] = torch.rand(self.n_targets, 4, device=torch_device) labels.append(target) config = self.get_config() return config, pixel_values, labels def get_config(self): return YolosConfig( image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, 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, hidden_dropout_prob=self.hidden_dropout_prob, attention_probs_dropout_prob=self.attention_probs_dropout_prob, is_decoder=False, initializer_range=self.initializer_range, num_detection_tokens=self.num_detection_tokens, num_labels=self.num_labels, attn_implementation=self.attn_implementation, ) def create_and_check_model(self, config, pixel_values, labels): model = YolosModel(config=config) model.to(torch_device) model.eval() result = model(pixel_values) self.parent.assertEqual( result.last_hidden_state.shape, (self.batch_size, self.expected_seq_len, self.hidden_size) ) def create_and_check_for_object_detection(self, config, pixel_values, labels): model = YolosForObjectDetection(config) model.to(torch_device) model.eval() result = model(pixel_values=pixel_values) result = model(pixel_values) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_detection_tokens, self.num_labels + 1)) self.parent.assertEqual(result.pred_boxes.shape, (self.batch_size, self.num_detection_tokens, 4)) result = model(pixel_values=pixel_values, labels=labels) self.parent.assertEqual(result.loss.shape, ()) self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_detection_tokens, self.num_labels + 1)) self.parent.assertEqual(result.pred_boxes.shape, (self.batch_size, self.num_detection_tokens, 4)) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, pixel_values, labels = config_and_inputs inputs_dict = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class YolosModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): """ Here we also overwrite some of the tests of test_modeling_common.py, as YOLOS does not use input_ids, inputs_embeds, attention_mask and seq_length. """ all_model_classes = (YolosModel, YolosForObjectDetection) if is_torch_available() else () pipeline_model_mapping = ( {"image-feature-extraction": YolosModel, "object-detection": YolosForObjectDetection} if is_torch_available() else {} ) test_pruning = False test_resize_embeddings = False test_head_masking = False test_torchscript = False test_torch_exportable = True # special case for head model def _prepare_for_class(self, inputs_dict, model_class, return_labels=False): inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels) if return_labels: if model_class.__name__ == "YolosForObjectDetection": labels = [] for i in range(self.model_tester.batch_size): target = {} target["class_labels"] = torch.ones( size=(self.model_tester.n_targets,), device=torch_device, dtype=torch.long ) target["boxes"] = torch.ones( self.model_tester.n_targets, 4, device=torch_device, dtype=torch.float ) labels.append(target) inputs_dict["labels"] = labels return inputs_dict def setUp(self): self.model_tester = YolosModelTester(self) self.config_tester = ConfigTester(self, config_class=YolosConfig, has_text_modality=False, hidden_size=37) def test_config(self): self.config_tester.run_common_tests() @unittest.skip(reason="YOLOS does not use inputs_embeds") def test_inputs_embeds(self): pass def test_model_get_set_embeddings(self): config, _ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: model = model_class(config) self.assertIsInstance(model.get_input_embeddings(), (nn.Module)) x = model.get_output_embeddings() self.assertTrue(x is None or isinstance(x, nn.Linear)) 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_attention_outputs(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() config.return_dict = True # in YOLOS, the seq_len is different seq_len = self.model_tester.expected_seq_len for model_class in self.all_model_classes: inputs_dict["output_attentions"] = True inputs_dict["output_hidden_states"] = False config.return_dict = True model = model_class._from_config(config, attn_implementation="eager") config = model.config model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) attentions = outputs.attentions self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) # check that output_attentions also work using config del inputs_dict["output_attentions"] config.output_attentions = True model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) attentions = outputs.attentions self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) self.assertListEqual( list(attentions[0].shape[-3:]), [self.model_tester.num_attention_heads, seq_len, seq_len], ) out_len = len(outputs) # Check attention is always last and order is fine inputs_dict["output_attentions"] = True inputs_dict["output_hidden_states"] = True model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) added_hidden_states = 1 self.assertEqual(out_len + added_hidden_states, len(outputs)) self_attentions = outputs.attentions self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers) self.assertListEqual( list(self_attentions[0].shape[-3:]), [self.model_tester.num_attention_heads, seq_len, seq_len], ) def test_hidden_states_output(self): def check_hidden_states_output(inputs_dict, config, model_class): model = model_class(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) hidden_states = outputs.hidden_states expected_num_layers = getattr( self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1 ) self.assertEqual(len(hidden_states), expected_num_layers) # YOLOS has a different seq_length seq_length = self.model_tester.expected_seq_len self.assertListEqual( list(hidden_states[0].shape[-2:]), [seq_length, self.model_tester.hidden_size], ) config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: inputs_dict["output_hidden_states"] = True check_hidden_states_output(inputs_dict, config, model_class) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] config.output_hidden_states = True check_hidden_states_output(inputs_dict, config, model_class) def test_for_object_detection(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_object_detection(*config_and_inputs) @slow def test_model_from_pretrained(self): model_name = "hustvl/yolos-small" model = YolosModel.from_pretrained(model_name) self.assertIsNotNone(model) # We will verify our results on an image of cute cats def prepare_img(): image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") return image @require_torch @require_vision class YolosModelIntegrationTest(unittest.TestCase): @cached_property def default_image_processor(self): return AutoImageProcessor.from_pretrained("hustvl/yolos-small") if is_vision_available() else None @slow def test_inference_object_detection_head(self): model = YolosForObjectDetection.from_pretrained("hustvl/yolos-small").to(torch_device) image_processor = self.default_image_processor image = prepare_img() inputs = image_processor(images=image, return_tensors="pt").to(torch_device) # forward pass with torch.no_grad(): outputs = model(inputs.pixel_values) # verify outputs expected_shape = torch.Size((1, 100, 92)) self.assertEqual(outputs.logits.shape, expected_shape) expected_slice_logits = torch.tensor( [[-23.7219, -10.3165, -14.9083], [-41.5429, -15.2403, -24.1478], [-29.3909, -12.7173, -19.4650]], device=torch_device, ) expected_slice_boxes = torch.tensor( [[0.2536, 0.5449, 0.4643], [0.2037, 0.7735, 0.3672], [0.7692, 0.4056, 0.4549]], device=torch_device ) torch.testing.assert_close(outputs.logits[0, :3, :3], expected_slice_logits, rtol=1e-4, atol=1e-4) torch.testing.assert_close(outputs.pred_boxes[0, :3, :3], expected_slice_boxes, rtol=1e-4, atol=1e-4) # verify postprocessing results = image_processor.post_process_object_detection( outputs, threshold=0.3, target_sizes=[image.size[::-1]] )[0] expected_scores = torch.tensor([0.9991, 0.9801, 0.9978, 0.9875, 0.9848]).to(torch_device) expected_labels = [75, 75, 17, 63, 17] expected_slice_boxes = torch.tensor([331.8438, 80.5440, 369.9546, 188.0579]).to(torch_device) self.assertEqual(len(results["scores"]), 5) torch.testing.assert_close(results["scores"], expected_scores, rtol=1e-4, atol=1e-4) self.assertSequenceEqual(results["labels"].tolist(), expected_labels) torch.testing.assert_close(results["boxes"][0, :], expected_slice_boxes)
transformers/tests/models/yolos/test_modeling_yolos.py/0
{ "file_path": "transformers/tests/models/yolos/test_modeling_yolos.py", "repo_id": "transformers", "token_count": 6843 }
577
# 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 gc import logging import os import sys import tempfile import unittest from pathlib import Path import datasets import numpy as np from huggingface_hub import HfFolder, Repository, delete_repo from requests.exceptions import HTTPError from transformers import ( AutomaticSpeechRecognitionPipeline, AutoModelForSequenceClassification, AutoTokenizer, DistilBertForSequenceClassification, MaskGenerationPipeline, T5ForConditionalGeneration, TextClassificationPipeline, TextGenerationPipeline, TFAutoModelForSequenceClassification, pipeline, ) from transformers.pipelines import PIPELINE_REGISTRY, get_task from transformers.pipelines.base import Pipeline, _pad from transformers.testing_utils import ( TOKEN, USER, CaptureLogger, RequestCounter, backend_empty_cache, is_pipeline_test, is_staging_test, nested_simplify, require_torch, require_torch_accelerator, require_torch_multi_accelerator, require_torch_or_tf, slow, torch_device, ) from transformers.utils import direct_transformers_import, is_tf_available, is_torch_available from transformers.utils import logging as transformers_logging sys.path.append(str(Path(__file__).parent.parent.parent / "utils")) from test_module.custom_pipeline import PairClassificationPipeline # noqa E402 logger = logging.getLogger(__name__) PATH_TO_TRANSFORMERS = os.path.join(Path(__file__).parent.parent.parent, "src/transformers") # Dynamically import the Transformers module to grab the attribute classes of the processor form their names. transformers_module = direct_transformers_import(PATH_TO_TRANSFORMERS) class ANY: def __init__(self, *_types): self._types = _types def __eq__(self, other): return isinstance(other, self._types) def __repr__(self): return f"ANY({', '.join(_type.__name__ for _type in self._types)})" @is_pipeline_test class CommonPipelineTest(unittest.TestCase): @require_torch def test_pipeline_iteration(self): from torch.utils.data import Dataset class MyDataset(Dataset): data = [ "This is a test", "This restaurant is great", "This restaurant is awful", ] def __len__(self): return 3 def __getitem__(self, i): return self.data[i] text_classifier = pipeline( task="text-classification", model="hf-internal-testing/tiny-random-distilbert", framework="pt" ) dataset = MyDataset() for output in text_classifier(dataset): self.assertEqual(output, {"label": ANY(str), "score": ANY(float)}) @require_torch def test_check_task_auto_inference(self): pipe = pipeline(model="hf-internal-testing/tiny-random-distilbert") self.assertIsInstance(pipe, TextClassificationPipeline) @require_torch def test_pipeline_batch_size_global(self): pipe = pipeline(model="hf-internal-testing/tiny-random-distilbert") self.assertEqual(pipe._batch_size, None) self.assertEqual(pipe._num_workers, None) pipe = pipeline(model="hf-internal-testing/tiny-random-distilbert", batch_size=2, num_workers=1) self.assertEqual(pipe._batch_size, 2) self.assertEqual(pipe._num_workers, 1) @require_torch def test_pipeline_pathlike(self): pipe = pipeline(model="hf-internal-testing/tiny-random-distilbert") with tempfile.TemporaryDirectory() as d: pipe.save_pretrained(d) path = Path(d) newpipe = pipeline(task="text-classification", model=path) self.assertIsInstance(newpipe, TextClassificationPipeline) @require_torch def test_pipeline_override(self): class MyPipeline(TextClassificationPipeline): pass text_classifier = pipeline(model="hf-internal-testing/tiny-random-distilbert", pipeline_class=MyPipeline) self.assertIsInstance(text_classifier, MyPipeline) def test_check_task(self): task = get_task("openai-community/gpt2") self.assertEqual(task, "text-generation") with self.assertRaises(RuntimeError): # Wrong framework get_task("espnet/siddhana_slurp_entity_asr_train_asr_conformer_raw_en_word_valid.acc.ave_10best") @require_torch def test_iterator_data(self): def data(n: int): for _ in range(n): yield "This is a test" pipe = pipeline(model="hf-internal-testing/tiny-random-distilbert") results = [] for out in pipe(data(10)): self.assertEqual(nested_simplify(out), {"label": "LABEL_0", "score": 0.504}) results.append(out) self.assertEqual(len(results), 10) # When using multiple workers on streamable data it should still work # This will force using `num_workers=1` with a warning for now. results = [] for out in pipe(data(10), num_workers=2): self.assertEqual(nested_simplify(out), {"label": "LABEL_0", "score": 0.504}) results.append(out) self.assertEqual(len(results), 10) @require_torch def test_unbatch_attentions_hidden_states(self): model = DistilBertForSequenceClassification.from_pretrained( "hf-internal-testing/tiny-random-distilbert", output_hidden_states=True, output_attentions=True ) tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-distilbert") text_classifier = TextClassificationPipeline(model=model, tokenizer=tokenizer) # Used to throw an error because `hidden_states` are a tuple of tensors # instead of the expected tensor. outputs = text_classifier(["This is great !"] * 20, batch_size=32) self.assertEqual(len(outputs), 20) @require_torch def test_dtype_property(self): import torch model_id = "hf-internal-testing/tiny-random-distilbert" # If dtype is specified in the pipeline constructor, the property should return that type pipe = pipeline(model=model_id, dtype=torch.float16) self.assertEqual(pipe.dtype, torch.float16) # If the underlying model changes dtype, the property should return the new type pipe.model.to(torch.bfloat16) self.assertEqual(pipe.dtype, torch.bfloat16) # If dtype is NOT specified in the pipeline constructor, the property should just return # the dtype of the underlying model (default) pipe = pipeline(model=model_id) self.assertEqual(pipe.dtype, torch.float32) # If underlying model doesn't have dtype property, simply return None pipe.model = None self.assertIsNone(pipe.dtype) @require_torch def test_auto_model_pipeline_registration_from_local_dir(self): with tempfile.TemporaryDirectory() as tmp_dir: _ = Repository(local_dir=tmp_dir, clone_from="hf-internal-testing/tiny-random-custom-architecture") pipe = pipeline("text-generation", tmp_dir, trust_remote_code=True) self.assertIsInstance(pipe, TextGenerationPipeline) # Assert successful load @require_torch def test_pipeline_with_task_parameters_no_side_effects(self): """ Regression test: certain pipeline flags, like `task`, modified the model configuration, causing unexpected side-effects """ # This checkpoint has task-specific parameters that will modify the behavior of the pipeline model = T5ForConditionalGeneration.from_pretrained("t5-small") self.assertTrue(model.config.num_beams == 1) # The task-specific parameters used to cause side-effects on `model.config` -- not anymore pipe = pipeline(model=model, tokenizer=AutoTokenizer.from_pretrained("t5-small"), task="translation_en_to_de") self.assertTrue(model.config.num_beams == 1) self.assertTrue(model.generation_config.num_beams == 1) # Under the hood: we now store a generation config in the pipeline. This generation config stores the # task-specific parameters. self.assertTrue(pipe.generation_config.num_beams == 4) # We can confirm that the task-specific parameters have an effect. (In this case, the default is `num_beams=1`, # which would crash when `num_return_sequences=4` is passed.) pipe("Hugging Face doesn't sell hugs.", num_return_sequences=4) with self.assertRaises(ValueError): pipe("Hugging Face doesn't sell hugs.", num_return_sequences=4, num_beams=1) @is_pipeline_test @require_torch class PipelineScikitCompatTest(unittest.TestCase): def test_pipeline_predict(self): data = ["This is a test"] text_classifier = pipeline( task="text-classification", model="hf-internal-testing/tiny-random-distilbert", framework="pt" ) expected_output = [{"label": ANY(str), "score": ANY(float)}] actual_output = text_classifier.predict(data) self.assertEqual(expected_output, actual_output) def test_pipeline_transform(self): data = ["This is a test"] text_classifier = pipeline( task="text-classification", model="hf-internal-testing/tiny-random-distilbert", framework="pt" ) expected_output = [{"label": ANY(str), "score": ANY(float)}] actual_output = text_classifier.transform(data) self.assertEqual(expected_output, actual_output) @is_pipeline_test class PipelinePadTest(unittest.TestCase): @require_torch def test_pipeline_padding(self): import torch items = [ { "label": "label1", "input_ids": torch.LongTensor([[1, 23, 24, 2]]), "attention_mask": torch.LongTensor([[0, 1, 1, 0]]), }, { "label": "label2", "input_ids": torch.LongTensor([[1, 23, 24, 43, 44, 2]]), "attention_mask": torch.LongTensor([[0, 1, 1, 1, 1, 0]]), }, ] self.assertEqual(_pad(items, "label", 0, "right"), ["label1", "label2"]) self.assertTrue( torch.allclose( _pad(items, "input_ids", 10, "right"), torch.LongTensor([[1, 23, 24, 2, 10, 10], [1, 23, 24, 43, 44, 2]]), ) ) self.assertTrue( torch.allclose( _pad(items, "input_ids", 10, "left"), torch.LongTensor([[10, 10, 1, 23, 24, 2], [1, 23, 24, 43, 44, 2]]), ) ) self.assertTrue( torch.allclose( _pad(items, "attention_mask", 0, "right"), torch.LongTensor([[0, 1, 1, 0, 0, 0], [0, 1, 1, 1, 1, 0]]) ) ) @require_torch def test_pipeline_image_padding(self): import torch items = [ { "label": "label1", "pixel_values": torch.zeros((1, 3, 10, 10)), }, { "label": "label2", "pixel_values": torch.zeros((1, 3, 10, 10)), }, ] self.assertEqual(_pad(items, "label", 0, "right"), ["label1", "label2"]) self.assertTrue( torch.allclose( _pad(items, "pixel_values", 10, "right"), torch.zeros((2, 3, 10, 10)), ) ) @require_torch def test_pipeline_offset_mapping(self): import torch items = [ { "offset_mappings": torch.zeros([1, 11, 2], dtype=torch.long), }, { "offset_mappings": torch.zeros([1, 4, 2], dtype=torch.long), }, ] self.assertTrue( torch.allclose( _pad(items, "offset_mappings", 0, "right"), torch.zeros((2, 11, 2), dtype=torch.long), ), ) @is_pipeline_test class PipelineUtilsTest(unittest.TestCase): @require_torch def test_pipeline_dataset(self): from transformers.pipelines.pt_utils import PipelineDataset dummy_dataset = [0, 1, 2, 3] def add(number, extra=0): return number + extra dataset = PipelineDataset(dummy_dataset, add, {"extra": 2}) self.assertEqual(len(dataset), 4) outputs = [dataset[i] for i in range(4)] self.assertEqual(outputs, [2, 3, 4, 5]) @require_torch def test_pipeline_iterator(self): from transformers.pipelines.pt_utils import PipelineIterator dummy_dataset = [0, 1, 2, 3] def add(number, extra=0): return number + extra dataset = PipelineIterator(dummy_dataset, add, {"extra": 2}) self.assertEqual(len(dataset), 4) outputs = list(dataset) self.assertEqual(outputs, [2, 3, 4, 5]) @require_torch def test_pipeline_iterator_no_len(self): from transformers.pipelines.pt_utils import PipelineIterator def dummy_dataset(): yield from range(4) def add(number, extra=0): return number + extra dataset = PipelineIterator(dummy_dataset(), add, {"extra": 2}) with self.assertRaises(TypeError): len(dataset) outputs = list(dataset) self.assertEqual(outputs, [2, 3, 4, 5]) @require_torch def test_pipeline_batch_unbatch_iterator(self): from transformers.pipelines.pt_utils import PipelineIterator dummy_dataset = [{"id": [0, 1, 2]}, {"id": [3]}] def add(number, extra=0): return {"id": [i + extra for i in number["id"]]} dataset = PipelineIterator(dummy_dataset, add, {"extra": 2}, loader_batch_size=3) outputs = list(dataset) self.assertEqual(outputs, [{"id": 2}, {"id": 3}, {"id": 4}, {"id": 5}]) @require_torch def test_pipeline_batch_unbatch_iterator_tensors(self): import torch from transformers.pipelines.pt_utils import PipelineIterator dummy_dataset = [{"id": torch.LongTensor([[10, 20], [0, 1], [0, 2]])}, {"id": torch.LongTensor([[3]])}] def add(number, extra=0): return {"id": number["id"] + extra} dataset = PipelineIterator(dummy_dataset, add, {"extra": 2}, loader_batch_size=3) outputs = list(dataset) self.assertEqual( nested_simplify(outputs), [{"id": [[12, 22]]}, {"id": [[2, 3]]}, {"id": [[2, 4]]}, {"id": [[5]]}] ) @require_torch def test_pipeline_chunk_iterator(self): from transformers.pipelines.pt_utils import PipelineChunkIterator def preprocess_chunk(n: int): yield from range(n) dataset = [2, 3] dataset = PipelineChunkIterator(dataset, preprocess_chunk, {}, loader_batch_size=3) outputs = list(dataset) self.assertEqual(outputs, [0, 1, 0, 1, 2]) @require_torch def test_pipeline_pack_iterator(self): from transformers.pipelines.pt_utils import PipelinePackIterator def pack(item): return {"id": item["id"] + 1, "is_last": item["is_last"]} dataset = [ {"id": 0, "is_last": False}, {"id": 1, "is_last": True}, {"id": 0, "is_last": False}, {"id": 1, "is_last": False}, {"id": 2, "is_last": True}, ] dataset = PipelinePackIterator(dataset, pack, {}) outputs = list(dataset) self.assertEqual( outputs, [ [ {"id": 1}, {"id": 2}, ], [ {"id": 1}, {"id": 2}, {"id": 3}, ], ], ) @require_torch def test_pipeline_pack_unbatch_iterator(self): from transformers.pipelines.pt_utils import PipelinePackIterator dummy_dataset = [{"id": [0, 1, 2], "is_last": [False, True, False]}, {"id": [3], "is_last": [True]}] def add(number, extra=0): return {"id": [i + extra for i in number["id"]], "is_last": number["is_last"]} dataset = PipelinePackIterator(dummy_dataset, add, {"extra": 2}, loader_batch_size=3) outputs = list(dataset) self.assertEqual(outputs, [[{"id": 2}, {"id": 3}], [{"id": 4}, {"id": 5}]]) # is_false Across batch dummy_dataset = [{"id": [0, 1, 2], "is_last": [False, False, False]}, {"id": [3], "is_last": [True]}] def add(number, extra=0): return {"id": [i + extra for i in number["id"]], "is_last": number["is_last"]} dataset = PipelinePackIterator(dummy_dataset, add, {"extra": 2}, loader_batch_size=3) outputs = list(dataset) self.assertEqual(outputs, [[{"id": 2}, {"id": 3}, {"id": 4}, {"id": 5}]]) def test_pipeline_negative_device(self): # To avoid regressing, pipeline used to accept device=-1 classifier = pipeline("text-generation", "hf-internal-testing/tiny-random-bert", device=-1) expected_output = [{"generated_text": ANY(str)}] actual_output = classifier("Test input.") self.assertEqual(expected_output, actual_output) @require_torch_accelerator def test_pipeline_no_device(self): # Test when no device is passed to pipeline import torch from transformers import AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert") # Case 1: Model is manually moved to device model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-bert", dtype=torch.float16).to( torch_device ) model_device = model.device pipe = pipeline("text-generation", model=model, tokenizer=tokenizer) self.assertEqual(pipe.model.device, model_device) # Case 2: Model is loaded by accelerate model = AutoModelForCausalLM.from_pretrained( "hf-internal-testing/tiny-random-bert", device_map=torch_device, dtype=torch.float16 ) model_device = model.device pipe = pipeline("text-generation", model=model, tokenizer=tokenizer) self.assertEqual(pipe.model.device, model_device) # Case 3: device_map is passed to model and device is passed to pipeline model = AutoModelForCausalLM.from_pretrained( "hf-internal-testing/tiny-random-bert", device_map=torch_device, dtype=torch.float16 ) with self.assertRaises(ValueError): pipe = pipeline("text-generation", model=model, device="cpu", tokenizer=tokenizer) @require_torch_multi_accelerator def test_pipeline_device_not_equal_model_device(self): # Test when device ids are different, pipeline should move the model to the passed device id import torch from transformers import AutoModelForCausalLM tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert") model_device = f"{torch_device}:1" model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-bert", dtype=torch.float16).to( model_device ) target_device = f"{torch_device}:0" self.assertNotEqual(model_device, target_device) pipe = pipeline("text-generation", model=model, device=target_device, tokenizer=tokenizer) self.assertEqual(pipe.model.device, torch.device(target_device)) @slow @require_torch def test_load_default_pipelines_pt(self): import torch from transformers.pipelines import SUPPORTED_TASKS set_seed_fn = lambda: torch.manual_seed(0) # noqa: E731 for task in SUPPORTED_TASKS: if task == "table-question-answering": # test table in separate test due to more dependencies continue self.check_default_pipeline(task, "pt", set_seed_fn, self.check_models_equal_pt) # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() backend_empty_cache(torch_device) @slow @require_torch def test_load_default_pipelines_pt_table_qa(self): import torch set_seed_fn = lambda: torch.manual_seed(0) # noqa: E731 self.check_default_pipeline("table-question-answering", "pt", set_seed_fn, self.check_models_equal_pt) # clean-up as much as possible GPU memory occupied by PyTorch gc.collect() backend_empty_cache(torch_device) @slow @require_torch @require_torch_accelerator def test_pipeline_accelerator(self): pipe = pipeline("text-generation", device=torch_device) _ = pipe("Hello") @slow @require_torch @require_torch_accelerator def test_pipeline_accelerator_indexed(self): pipe = pipeline("text-generation", device=torch_device) _ = pipe("Hello") @slow @require_torch def test_bc_torch_device(self): import torch from transformers.pipelines import get_supported_tasks for task in get_supported_tasks(): # Check that it works for all dtypes for dtype in ["float16", "bfloat16", "float32", "auto", torch.float16, torch.bfloat16, torch.float32]: pipe_torch_dtype = pipeline(task, torch_dtype=dtype) pipe_dtype = pipeline(task, dtype=dtype) # Make sure all parameters have the same dtype for (k1, v1), (k2, v2) in zip( pipe_torch_dtype.model.named_parameters(), pipe_dtype.model.named_parameters() ): self.assertEqual(k1, k2) self.assertEqual(v1.dtype, v2.dtype) pipe_torch_dtype = pipeline(task, model_kwargs={"torch_dtype": dtype}) pipe_dtype = pipeline(task, model_kwargs={"dtype": dtype}) # Make sure all parameters have the same dtype for (k1, v1), (k2, v2) in zip( pipe_torch_dtype.model.named_parameters(), pipe_dtype.model.named_parameters() ): self.assertEqual(k1, k2) self.assertEqual(v1.dtype, v2.dtype) def check_default_pipeline(self, task, framework, set_seed_fn, check_models_equal_fn): from transformers.pipelines import SUPPORTED_TASKS, pipeline task_dict = SUPPORTED_TASKS[task] # test to compare pipeline to manually loading the respective model model = None relevant_auto_classes = task_dict[framework] if len(relevant_auto_classes) == 0: # task has no default logger.debug(f"{task} in {framework} has no default") self.skipTest(f"{task} in {framework} has no default") # by default use first class auto_model_cls = relevant_auto_classes[0] # retrieve correct model ids if task == "translation": # special case for translation pipeline which has multiple languages model_ids = [] revisions = [] tasks = [] for translation_pair in task_dict["default"]: model_id, revision = task_dict["default"][translation_pair]["model"][framework] model_ids.append(model_id) revisions.append(revision) tasks.append(task + f"_{'_to_'.join(translation_pair)}") else: # normal case - non-translation pipeline model_id, revision = task_dict["default"]["model"][framework] model_ids = [model_id] revisions = [revision] tasks = [task] # check for equality for model_id, revision, task in zip(model_ids, revisions, tasks): # load default model try: set_seed_fn() model = auto_model_cls.from_pretrained(model_id, revision=revision) except ValueError: # first auto class is possible not compatible with model, go to next model class auto_model_cls = relevant_auto_classes[1] set_seed_fn() model = auto_model_cls.from_pretrained(model_id, revision=revision) # load default pipeline set_seed_fn() default_pipeline = pipeline(task, framework=framework) # compare pipeline model with default model models_are_equal = check_models_equal_fn(default_pipeline.model, model) self.assertTrue(models_are_equal, f"{task} model doesn't match pipeline.") logger.debug(f"{task} in {framework} succeeded with {model_id}.") def check_models_equal_pt(self, model1, model2): models_are_equal = True for model1_p, model2_p in zip(model1.parameters(), model2.parameters()): if model1_p.data.ne(model2_p.data).sum() > 0: models_are_equal = False return models_are_equal def check_models_equal_tf(self, model1, model2): models_are_equal = True for model1_p, model2_p in zip(model1.weights, model2.weights): if np.abs(model1_p.numpy() - model2_p.numpy()).sum() > 1e-5: models_are_equal = False return models_are_equal class CustomPipeline(Pipeline): def _sanitize_parameters(self, **kwargs): preprocess_kwargs = {} if "maybe_arg" in kwargs: preprocess_kwargs["maybe_arg"] = kwargs["maybe_arg"] return preprocess_kwargs, {}, {} def preprocess(self, text, maybe_arg=2): input_ids = self.tokenizer(text, return_tensors="pt") return input_ids def _forward(self, model_inputs): outputs = self.model(**model_inputs) return outputs def postprocess(self, model_outputs): return model_outputs["logits"].softmax(-1).numpy() @is_pipeline_test class CustomPipelineTest(unittest.TestCase): def test_warning_logs(self): transformers_logging.set_verbosity_debug() logger_ = transformers_logging.get_logger("transformers.pipelines.base") alias = "text-classification" # Get the original task, so we can restore it at the end. # (otherwise the subsequential tests in `TextClassificationPipelineTests` will fail) _, original_task, _ = PIPELINE_REGISTRY.check_task(alias) try: with CaptureLogger(logger_) as cm: PIPELINE_REGISTRY.register_pipeline(alias, PairClassificationPipeline) self.assertIn(f"{alias} is already registered", cm.out) finally: # restore PIPELINE_REGISTRY.supported_tasks[alias] = original_task def test_register_pipeline(self): PIPELINE_REGISTRY.register_pipeline( "custom-text-classification", pipeline_class=PairClassificationPipeline, pt_model=AutoModelForSequenceClassification if is_torch_available() else None, tf_model=TFAutoModelForSequenceClassification if is_tf_available() else None, default={"pt": ("hf-internal-testing/tiny-random-distilbert", "2ef615d")}, type="text", ) assert "custom-text-classification" in PIPELINE_REGISTRY.get_supported_tasks() _, task_def, _ = PIPELINE_REGISTRY.check_task("custom-text-classification") self.assertEqual(task_def["pt"], (AutoModelForSequenceClassification,) if is_torch_available() else ()) self.assertEqual(task_def["tf"], (TFAutoModelForSequenceClassification,) if is_tf_available() else ()) self.assertEqual(task_def["type"], "text") self.assertEqual(task_def["impl"], PairClassificationPipeline) self.assertEqual( task_def["default"], {"model": {"pt": ("hf-internal-testing/tiny-random-distilbert", "2ef615d")}} ) # Clean registry for next tests. del PIPELINE_REGISTRY.supported_tasks["custom-text-classification"] @require_torch_or_tf def test_dynamic_pipeline(self): PIPELINE_REGISTRY.register_pipeline( "pair-classification", pipeline_class=PairClassificationPipeline, pt_model=AutoModelForSequenceClassification if is_torch_available() else None, tf_model=TFAutoModelForSequenceClassification if is_tf_available() else None, ) classifier = pipeline("pair-classification", model="hf-internal-testing/tiny-random-bert") # Clean registry as we won't need the pipeline to be in it for the rest to work. del PIPELINE_REGISTRY.supported_tasks["pair-classification"] with tempfile.TemporaryDirectory() as tmp_dir: classifier.save_pretrained(tmp_dir) # checks self.assertDictEqual( classifier.model.config.custom_pipelines, { "pair-classification": { "impl": "custom_pipeline.PairClassificationPipeline", "pt": ("AutoModelForSequenceClassification",) if is_torch_available() else (), "tf": ("TFAutoModelForSequenceClassification",) if is_tf_available() else (), } }, ) # Fails if the user forget to pass along `trust_remote_code=True` with self.assertRaises(ValueError): _ = pipeline(model=tmp_dir) new_classifier = pipeline(model=tmp_dir, trust_remote_code=True) # Using trust_remote_code=False forces the traditional pipeline tag old_classifier = pipeline("text-classification", model=tmp_dir, trust_remote_code=False) # Can't make an isinstance check because the new_classifier is from the PairClassificationPipeline class of a # dynamic module self.assertEqual(new_classifier.__class__.__name__, "PairClassificationPipeline") self.assertEqual(new_classifier.task, "pair-classification") results = new_classifier("I hate you", second_text="I love you") self.assertDictEqual( nested_simplify(results), {"label": "LABEL_0", "score": 0.505, "logits": [-0.003, -0.024]}, ) self.assertEqual(old_classifier.__class__.__name__, "TextClassificationPipeline") self.assertEqual(old_classifier.task, "text-classification") results = old_classifier("I hate you", text_pair="I love you") self.assertListEqual( nested_simplify(results), [{"label": "LABEL_0", "score": 0.505}], ) @require_torch_or_tf def test_cached_pipeline_has_minimum_calls_to_head(self): # Make sure we have cached the pipeline. _ = pipeline("text-classification", model="hf-internal-testing/tiny-random-bert") with RequestCounter() as counter: _ = pipeline("text-classification", model="hf-internal-testing/tiny-random-bert") self.assertEqual(counter["GET"], 0) self.assertEqual(counter["HEAD"], 1) self.assertEqual(counter.total_calls, 1) @require_torch def test_chunk_pipeline_batching_single_file(self): # Make sure we have cached the pipeline. pipe = pipeline(model="hf-internal-testing/tiny-random-Wav2Vec2ForCTC") ds = datasets.load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation").sort("id") audio = ds[40]["audio"]["array"] pipe = pipeline(model="hf-internal-testing/tiny-random-Wav2Vec2ForCTC") # For some reason scoping doesn't work if not using `self.` self.COUNT = 0 forward = pipe.model.forward def new_forward(*args, **kwargs): self.COUNT += 1 return forward(*args, **kwargs) pipe.model.forward = new_forward for out in pipe(audio, return_timestamps="char", chunk_length_s=3, stride_length_s=[1, 1], batch_size=1024): pass self.assertEqual(self.COUNT, 1) @require_torch def test_custom_code_with_string_tokenizer(self): # This test checks for an edge case - tokenizer loading used to fail when using a custom code model # with a separate tokenizer that was passed as a repo name rather than a tokenizer object. # See https://github.com/huggingface/transformers/issues/31669 text_generator = pipeline( "text-generation", model="hf-internal-testing/tiny-random-custom-architecture", tokenizer="hf-internal-testing/tiny-random-custom-architecture", trust_remote_code=True, ) self.assertIsInstance(text_generator, TextGenerationPipeline) # Assert successful loading @require_torch def test_custom_code_with_string_feature_extractor(self): speech_recognizer = pipeline( "automatic-speech-recognition", model="hf-internal-testing/fake-custom-wav2vec2", feature_extractor="hf-internal-testing/fake-custom-wav2vec2", tokenizer="facebook/wav2vec2-base-960h", # Test workaround - the pipeline requires a tokenizer trust_remote_code=True, ) self.assertIsInstance(speech_recognizer, AutomaticSpeechRecognitionPipeline) # Assert successful loading @require_torch def test_custom_code_with_string_preprocessor(self): mask_generator = pipeline( "mask-generation", model="hf-internal-testing/fake-custom-sam", processor="hf-internal-testing/fake-custom-sam", trust_remote_code=True, ) self.assertIsInstance(mask_generator, MaskGenerationPipeline) # Assert successful loading @require_torch @is_staging_test class DynamicPipelineTester(unittest.TestCase): vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "I", "love", "hate", "you"] @classmethod def setUpClass(cls): cls._token = TOKEN HfFolder.save_token(TOKEN) @classmethod def tearDownClass(cls): try: delete_repo(token=cls._token, repo_id="test-dynamic-pipeline") except HTTPError: pass @unittest.skip("Broken, TODO @Yih-Dar") def test_push_to_hub_dynamic_pipeline(self): from transformers import BertConfig, BertForSequenceClassification, BertTokenizer PIPELINE_REGISTRY.register_pipeline( "pair-classification", pipeline_class=PairClassificationPipeline, pt_model=AutoModelForSequenceClassification, ) config = BertConfig( vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 ) model = BertForSequenceClassification(config).eval() with tempfile.TemporaryDirectory() as tmp_dir: vocab_file = os.path.join(tmp_dir, "vocab.txt") with open(vocab_file, "w", encoding="utf-8") as vocab_writer: vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens])) tokenizer = BertTokenizer(vocab_file) classifier = pipeline("pair-classification", model=model, tokenizer=tokenizer) # Clean registry as we won't need the pipeline to be in it for the rest to work. del PIPELINE_REGISTRY.supported_tasks["pair-classification"] classifier.save_pretrained(tmp_dir) # checks if the configuration has been added after calling the save_pretrained method self.assertDictEqual( classifier.model.config.custom_pipelines, { "pair-classification": { "impl": "custom_pipeline.PairClassificationPipeline", "pt": ("AutoModelForSequenceClassification",), "tf": (), } }, ) # use push_to_hub method to push the pipeline classifier.push_to_hub(f"{USER}/test-dynamic-pipeline", token=self._token) # Fails if the user forget to pass along `trust_remote_code=True` with self.assertRaises(ValueError): _ = pipeline(model=f"{USER}/test-dynamic-pipeline") new_classifier = pipeline(model=f"{USER}/test-dynamic-pipeline", trust_remote_code=True) # Can't make an isinstance check because the new_classifier is from the PairClassificationPipeline class of a # dynamic module self.assertEqual(new_classifier.__class__.__name__, "PairClassificationPipeline") # check for tag exitence, tag needs to be added when we are calling a custom pipeline from the hub # useful for cases such as finetuning self.assertDictEqual( new_classifier.model.config.custom_pipelines, { "pair-classification": { "impl": f"{USER}/test-dynamic-pipeline--custom_pipeline.PairClassificationPipeline", "pt": ("AutoModelForSequenceClassification",), "tf": (), } }, ) # test if the pipeline still works after the model is finetuned # (we are actually testing if the pipeline still works from the final repo) # this is where the user/repo--module.class is used for new_classifier.model.push_to_hub(repo_name=f"{USER}/test-pipeline-for-a-finetuned-model", token=self._token) del new_classifier # free up memory new_classifier = pipeline(model=f"{USER}/test-pipeline-for-a-finetuned-model", trust_remote_code=True) results = classifier("I hate you", second_text="I love you") new_results = new_classifier("I hate you", second_text="I love you") self.assertDictEqual(nested_simplify(results), nested_simplify(new_results)) # Using trust_remote_code=False forces the traditional pipeline tag old_classifier = pipeline( "text-classification", model=f"{USER}/test-dynamic-pipeline", trust_remote_code=False ) self.assertEqual(old_classifier.__class__.__name__, "TextClassificationPipeline") self.assertEqual(old_classifier.task, "text-classification") new_results = old_classifier("I hate you", text_pair="I love you") self.assertListEqual( nested_simplify([{"label": results["label"], "score": results["score"]}]), nested_simplify(new_results) )
transformers/tests/pipelines/test_pipelines_common.py/0
{ "file_path": "transformers/tests/pipelines/test_pipelines_common.py", "repo_id": "transformers", "token_count": 17111 }
578
# 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_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, Text2TextGenerationPipeline, pipeline, ) from transformers.testing_utils import is_pipeline_test, require_torch from transformers.utils import is_torch_available from .test_pipelines_common import ANY if is_torch_available(): import torch @is_pipeline_test class Text2TextGenerationPipelineTests(unittest.TestCase): model_mapping = MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING tf_model_mapping = TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING def get_test_pipeline( self, model, tokenizer=None, image_processor=None, feature_extractor=None, processor=None, dtype="float32", ): generator = Text2TextGenerationPipeline( model=model, tokenizer=tokenizer, feature_extractor=feature_extractor, image_processor=image_processor, processor=processor, dtype=dtype, max_new_tokens=20, ) return generator, ["Something to write", "Something else"] def run_pipeline_test(self, generator, _): outputs = generator("Something there") self.assertEqual(outputs, [{"generated_text": ANY(str)}]) # These are encoder decoder, they don't just append to incoming string self.assertFalse(outputs[0]["generated_text"].startswith("Something there")) outputs = 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)}], ], ) outputs = 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(TypeError): generator(4) @require_torch def test_small_model_pt(self): generator = pipeline( "text2text-generation", model="patrickvonplaten/t5-tiny-random", framework="pt", num_beams=1, max_new_tokens=9, ) # do_sample=False necessary for reproducibility outputs = generator("Something there", do_sample=False) self.assertEqual(outputs, [{"generated_text": ""}]) num_return_sequences = 3 outputs = generator( "Something there", num_return_sequences=num_return_sequences, num_beams=num_return_sequences, ) target_outputs = [ {"generated_text": "Beide Beide Beide Beide Beide Beide Beide Beide Beide"}, {"generated_text": "Beide Beide Beide Beide Beide Beide Beide Beide"}, {"generated_text": ""}, ] self.assertEqual(outputs, target_outputs) outputs = generator("This is a test", do_sample=True, num_return_sequences=2, return_tensors=True) self.assertEqual( outputs, [ {"generated_token_ids": ANY(torch.Tensor)}, {"generated_token_ids": ANY(torch.Tensor)}, ], ) generator.tokenizer.pad_token_id = generator.model.config.eos_token_id generator.tokenizer.pad_token = "<pad>" outputs = generator( ["This is a test", "This is a second test"], do_sample=True, num_return_sequences=2, batch_size=2, return_tensors=True, ) self.assertEqual( outputs, [ [ {"generated_token_ids": ANY(torch.Tensor)}, {"generated_token_ids": ANY(torch.Tensor)}, ], [ {"generated_token_ids": ANY(torch.Tensor)}, {"generated_token_ids": ANY(torch.Tensor)}, ], ], )
transformers/tests/pipelines/test_pipelines_text2text_generation.py/0
{ "file_path": "transformers/tests/pipelines/test_pipelines_text2text_generation.py", "repo_id": "transformers", "token_count": 2284 }
579
# 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 AutoConfig, AutoModelForCausalLM, AutoTokenizer, FineGrainedFP8Config, OPTForCausalLM from transformers.testing_utils import ( backend_empty_cache, get_device_properties, require_accelerate, require_read_token, require_torch_accelerator, require_torch_multi_accelerator, slow, torch_device, ) from transformers.utils import is_accelerate_available, is_torch_available if is_torch_available(): import torch if is_accelerate_available(): from accelerate import init_empty_weights @require_torch_accelerator class FineGrainedFP8ConfigTest(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 = FineGrainedFP8Config() 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": ["lm_head.weight"], "quant_method": "fp8"} quantization_config = FineGrainedFP8Config.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_accelerate @require_read_token @require_torch_accelerator class FP8QuantizerTest(unittest.TestCase): model_name = "meta-llama/Llama-3.2-1B" input_text = "Once upon a time" max_new_tokens = 10 EXPECTED_OUTPUT = "Once upon a time, there was a man who was very rich." device_map = torch_device offload_device_map = { "model.embed_tokens": 0, "model.layers.0": 0, "model.layers.1": 0, "model.layers.2": 0, "model.layers.3": 0, "model.layers.4": 0, "model.layers.5": 0, "model.layers.6": 0, "model.layers.7": "cpu", "model.layers.8": "cpu", "model.layers.9": "cpu", "model.layers.10": "cpu", "model.layers.11": "cpu", "model.layers.12": "cpu", "model.layers.13": "cpu", "model.layers.14": "cpu", "model.layers.15": "cpu", "model.rotary_emb": "disk", "model.norm": "disk", "lm_head": 0, } @classmethod def setUpClass(cls): """ Setup quantized model """ cls.quantization_config = FineGrainedFP8Config() cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name) cls.quantized_model = AutoModelForCausalLM.from_pretrained( cls.model_name, device_map=cls.device_map, quantization_config=cls.quantization_config ) def tearDown(self): gc.collect() backend_empty_cache(torch_device) gc.collect() def test_quantized_model_conversion(self): """ Simple test that checks if the quantized model has been converted properly """ from transformers.integrations import FP8Linear, replace_with_fp8_linear model_id = "facebook/opt-350m" config = AutoConfig.from_pretrained(model_id, revision="cb32f77e905cccbca1d970436fb0f5e6b58ee3c5") quantization_config = FineGrainedFP8Config() with init_empty_weights(): model = OPTForCausalLM(config) nb_linears = 0 for module in model.modules(): if isinstance(module, torch.nn.Linear): nb_linears += 1 model = replace_with_fp8_linear(model, quantization_config=quantization_config) nb_fp8_linear = 0 for module in model.modules(): if isinstance(module, FP8Linear): nb_fp8_linear += 1 self.assertEqual(nb_linears - 1, nb_fp8_linear) with init_empty_weights(): model = OPTForCausalLM(config) quantization_config = FineGrainedFP8Config(modules_to_not_convert=["fc1"]) model = replace_with_fp8_linear(model, quantization_config=quantization_config) nb_fp8_linear = 0 for module in model.modules(): if isinstance(module, FP8Linear): nb_fp8_linear += 1 self.assertEqual(nb_linears - 25, nb_fp8_linear) 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(self.device_map) output = self.quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens, do_sample=False) output_tokens = self.tokenizer.decode(output[0], skip_special_tokens=True) self.assertEqual(output_tokens, 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(self.device_map) output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens, do_sample=False) self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) def test_weight_and_weight_scale_inv(self): """ Simple test that checks if the weight and weight_scale_inv are working properly """ weight = self.quantized_model.model.layers[0].self_attn.q_proj.weight weight_scale_inv = self.quantized_model.model.layers[0].self_attn.q_proj.weight_scale_inv self.assertEqual(weight.dtype, torch.float8_e4m3fn) self.assertEqual(weight_scale_inv.dtype, torch.float32) self.assertEqual(weight.shape, (weight_scale_inv.shape[0] * 128, weight_scale_inv.shape[1] * 128)) def test_block_size(self): """ Simple test that checks if the block size is working properly """ self.assertEqual(self.quantized_model.config.quantization_config.weight_block_size, (128, 128)) quantization_config = FineGrainedFP8Config(weight_block_size=(32, 32)) quantized_model = AutoModelForCausalLM.from_pretrained( self.model_name, device_map=self.device_map, quantization_config=quantization_config ) self.assertEqual(quantized_model.config.quantization_config.weight_block_size, (32, 32)) @require_torch_multi_accelerator def test_quantized_model_multi_accelerator(self): """ Simple test that checks if the quantized model is working properly with multiple accelerators set CUDA_VISIBLE_DEVICES=0,1 if you have more than 2 GPUs; or set ZE_AFFINITY_MASK=0,1 if you have more than 2 XPUs. """ input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(self.device_map) quantization_config = FineGrainedFP8Config() 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, do_sample=False) self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) @require_torch_multi_accelerator def test_save_pretrained_multi_accelerators(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(self.device_map) output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens, do_sample=False) self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) def test_quantized_model_offload(self): """ Simple test that checks if the quantized model returns an error when loading with cpu/disk offloaded """ with self.assertRaisesRegex( ValueError, "You are attempting to load an FP8 model with a device_map that contains a cpu/disk device." ): AutoModelForCausalLM.from_pretrained( self.model_name, device_map=self.offload_device_map, quantization_config=self.quantization_config ) def test_save_pretrained_offload(self): """ Simple test that checks if the saved quantized model is working properly cpu/disk offload """ with tempfile.TemporaryDirectory() as tmpdirname: self.quantized_model.save_pretrained(tmpdirname) input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(self.device_map) quantized_model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=self.offload_device_map) output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens, do_sample=False) self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) @require_torch_accelerator class FP8LinearTest(unittest.TestCase): device = torch_device @unittest.skipIf( get_device_properties()[0] == "cuda" and get_device_properties()[1] < 9, "Skipping FP8LinearTest because it is not supported on GPU with capability < 9.0", ) def test_linear_preserves_shape(self): """ Test that FP8Linear preserves shape when in_features == out_features. """ from transformers.integrations import FP8Linear linear = FP8Linear(256, 256, block_size=(128, 128), device=self.device) x = torch.rand((1, 5, 256)).to(self.device) x_ = linear(x) self.assertEqual(x_.shape, x.shape) @unittest.skipIf( get_device_properties()[0] == "cuda" and get_device_properties()[1] < 9, "Skipping FP8LinearTest because it is not supported on GPU with capability < 9.0", ) def test_linear_with_diff_feature_size_preserves_shape(self): """ Test that FP8Linear generates the correct shape when in_features != out_features. """ from transformers.integrations import FP8Linear linear = FP8Linear(128, 256, block_size=(128, 128), device=self.device) x = torch.rand((1, 5, 128)).to(self.device) x_ = linear(x) self.assertEqual(x_.shape, (1, 5, 256))
transformers/tests/quantization/finegrained_fp8/test_fp8.py/0
{ "file_path": "transformers/tests/quantization/finegrained_fp8/test_fp8.py", "repo_id": "transformers", "token_count": 4902 }
580
#!/usr/bin/env python # 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. """Finetuning the library models for sequence classification on GLUE.""" # You can also adapt this script on your own text classification task. Pointers for this are left as comments. import logging import os import random import sys from dataclasses import dataclass, field from typing import Optional import numpy as np from datasets import load_dataset, load_metric import transformers from transformers import ( # Trainer,; TrainingArguments, AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, PretrainedConfig, default_data_collator, set_seed, ) # Will import SageMaker Model parallelism specific Trainer from transformers.sagemaker import SageMakerTrainer as Trainer from transformers.sagemaker import SageMakerTrainingArguments as TrainingArguments from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version("4.4.2") task_to_keys = { "cola": ("sentence", None), "mnli": ("premise", "hypothesis"), "mrpc": ("sentence1", "sentence2"), "qnli": ("question", "sentence"), "qqp": ("question1", "question2"), "rte": ("sentence1", "sentence2"), "sst2": ("sentence", None), "stsb": ("sentence1", "sentence2"), "wnli": ("sentence1", "sentence2"), } logger = logging.getLogger(__name__) @dataclass class DataTrainingArguments: """ Arguments pertaining to what data we are going to input our model for training and eval. Using `HfArgumentParser` we can turn this class into argparse arguments to be able to specify them on the command line. """ task_name: Optional[str] = field( default=None, metadata={"help": "The name of the task to train on: " + ", ".join(task_to_keys.keys())}, ) max_seq_length: int = field( default=128, metadata={ "help": ( "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." ) }, ) overwrite_cache: bool = field( default=False, metadata={"help": "Overwrite the cached preprocessed datasets or not."} ) pad_to_max_length: bool = field( default=True, metadata={ "help": ( "Whether to pad all samples to `max_seq_length`. " "If False, will pad the samples dynamically when batching to the maximum length in the batch." ) }, ) max_train_samples: Optional[int] = field( default=None, metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of training examples to this " "value if set." ) }, ) max_val_samples: Optional[int] = field( default=None, metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of validation examples to this " "value if set." ) }, ) max_test_samples: Optional[int] = field( default=None, metadata={ "help": ( "For debugging purposes or quicker training, truncate the number of test examples to this " "value if set." ) }, ) train_file: Optional[str] = field( default=None, metadata={"help": "A csv or a json file containing the training data."} ) validation_file: Optional[str] = field( default=None, metadata={"help": "A csv or a json file containing the validation data."} ) test_file: Optional[str] = field(default=None, metadata={"help": "A csv or a json file containing the test data."}) def __post_init__(self): if self.task_name is not None: self.task_name = self.task_name.lower() if self.task_name not in task_to_keys: raise ValueError("Unknown task, you should pick one in " + ",".join(task_to_keys.keys())) elif self.train_file is None or self.validation_file is None: raise ValueError("Need either a GLUE task or a training/validation file.") else: train_extension = self.train_file.split(".")[-1] assert train_extension in ["csv", "json"], "`train_file` should be a csv or a json file." validation_extension = self.validation_file.split(".")[-1] assert validation_extension == train_extension, ( "`validation_file` should have the same extension (csv or json) as `train_file`." ) @dataclass class ModelArguments: """ Arguments pertaining to which model/config/tokenizer we are going to fine-tune from. """ model_name_or_path: str = field( metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} ) config_name: Optional[str] = field( default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"} ) tokenizer_name: Optional[str] = field( default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} ) cache_dir: Optional[str] = field( default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}, ) use_fast_tokenizer: bool = field( default=True, metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."}, ) model_revision: str = field( default="main", metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}, ) use_auth_token: bool = field( default=False, metadata={ "help": ( "Will use the token generated when running `hf auth login` (necessary to use this script " "with private models)." ) }, ) def main(): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) else: model_args, data_args, training_args = parser.parse_args_into_dataclasses() # Detecting last checkpoint. last_checkpoint = None if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir: last_checkpoint = get_last_checkpoint(training_args.output_dir) if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: raise ValueError( f"Output directory ({training_args.output_dir}) already exists and is not empty. " "Use --overwrite_output_dir to overcome." ) elif last_checkpoint is not None: logger.info( f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", datefmt="%m/%d/%Y %H:%M:%S", handlers=[logging.StreamHandler(sys.stdout)], ) logger.setLevel(logging.INFO if training_args.should_log else logging.WARN) # Log on each process the small summary: logger.warning( f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}" + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}" ) # Set the verbosity to info of the Transformers logger (on main process only): if training_args.should_log: transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info(f"Training/evaluation parameters {training_args}") # Set seed before initializing model. set_seed(training_args.seed) # Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below) # or specify a GLUE benchmark task (the dataset will be downloaded automatically from the datasets Hub). # # For CSV/JSON files, this script will use as labels the column called 'label' and as pair of sentences the # sentences in columns called 'sentence1' and 'sentence2' if such column exists or the first two columns not named # label if at least two columns are provided. # # If the CSVs/JSONs contain only one non-label column, the script does single sentence classification on this # single column. You can easily tweak this behavior (see below) # # In distributed training, the load_dataset function guarantee that only one local process can concurrently # download the dataset. if data_args.task_name is not None: # Downloading and loading a dataset from the hub. datasets = load_dataset("nyu-mll/glue", data_args.task_name) else: # Loading a dataset from your local files. # CSV/JSON training and evaluation files are needed. data_files = {"train": data_args.train_file, "validation": data_args.validation_file} # Get the test dataset: you can provide your own CSV/JSON test file (see below) # when you use `do_predict` without specifying a GLUE benchmark task. if training_args.do_predict: if data_args.test_file is not None: train_extension = data_args.train_file.split(".")[-1] test_extension = data_args.test_file.split(".")[-1] assert test_extension == train_extension, ( "`test_file` should have the same extension (csv or json) as `train_file`." ) data_files["test"] = data_args.test_file else: raise ValueError("Need either a GLUE task or a test file for `do_predict`.") for key in data_files: logger.info(f"load a local file for {key}: {data_files[key]}") if data_args.train_file.endswith(".csv"): # Loading a dataset from local csv files datasets = load_dataset("csv", data_files=data_files) else: # Loading a dataset from local json files datasets = load_dataset("json", data_files=data_files) # See more about loading any type of standard or custom dataset at # https://huggingface.co/docs/datasets/loading_datasets. # Labels if data_args.task_name is not None: is_regression = data_args.task_name == "stsb" if not is_regression: label_list = datasets["train"].features["label"].names num_labels = len(label_list) else: num_labels = 1 else: # Trying to have good defaults here, don't hesitate to tweak to your needs. is_regression = datasets["train"].features["label"].dtype in ["float32", "float64"] if is_regression: num_labels = 1 else: # A useful fast method: # https://huggingface.co/docs/datasets/package_reference/main_classes#datasets.Dataset.unique label_list = datasets["train"].unique("label") label_list.sort() # Let's sort it for determinism num_labels = len(label_list) # Load pretrained model and tokenizer # # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. config = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path, num_labels=num_labels, finetuning_task=data_args.task_name, cache_dir=model_args.cache_dir, revision=model_args.model_revision, token=True if model_args.use_auth_token else None, ) tokenizer = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, cache_dir=model_args.cache_dir, use_fast=model_args.use_fast_tokenizer, revision=model_args.model_revision, token=True if model_args.use_auth_token else None, ) model = AutoModelForSequenceClassification.from_pretrained( model_args.model_name_or_path, from_tf=bool(".ckpt" in model_args.model_name_or_path), config=config, cache_dir=model_args.cache_dir, revision=model_args.model_revision, token=True if model_args.use_auth_token else None, ) # Preprocessing the datasets if data_args.task_name is not None: sentence1_key, sentence2_key = task_to_keys[data_args.task_name] else: # Again, we try to have some nice defaults but don't hesitate to tweak to your use case. non_label_column_names = [name for name in datasets["train"].column_names if name != "label"] if "sentence1" in non_label_column_names and "sentence2" in non_label_column_names: sentence1_key, sentence2_key = "sentence1", "sentence2" else: if len(non_label_column_names) >= 2: sentence1_key, sentence2_key = non_label_column_names[:2] else: sentence1_key, sentence2_key = non_label_column_names[0], None # Padding strategy if data_args.pad_to_max_length: padding = "max_length" else: # We will pad later, dynamically at batch creation, to the max sequence length in each batch padding = False # Some models have set the order of the labels to use, so let's make sure we do use it. label_to_id = None if ( model.config.label2id != PretrainedConfig(num_labels=num_labels).label2id and data_args.task_name is not None and not is_regression ): # Some have all caps in their config, some don't. label_name_to_id = {k.lower(): v for k, v in model.config.label2id.items()} if sorted(label_name_to_id.keys()) == sorted(label_list): label_to_id = {i: int(label_name_to_id[label_list[i]]) for i in range(num_labels)} else: logger.warning( "Your model seems to have been trained with labels, but they don't match the dataset: " f"model labels: {sorted(label_name_to_id.keys())}, dataset labels: {sorted(label_list)}." "\nIgnoring the model labels as a result.", ) elif data_args.task_name is None and not is_regression: label_to_id = {v: i for i, v in enumerate(label_list)} if data_args.max_seq_length > tokenizer.model_max_length: logger.warning( f"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the " f"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}." ) max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length) def preprocess_function(examples): # Tokenize the texts args = ( (examples[sentence1_key],) if sentence2_key is None else (examples[sentence1_key], examples[sentence2_key]) ) result = tokenizer(*args, padding=padding, max_length=max_seq_length, truncation=True) # Map labels to IDs (not necessary for GLUE tasks) if label_to_id is not None and "label" in examples: result["label"] = [(label_to_id[l] if l != -1 else -1) for l in examples["label"]] return result datasets = datasets.map(preprocess_function, batched=True, load_from_cache_file=not data_args.overwrite_cache) if training_args.do_train: if "train" not in datasets: raise ValueError("--do_train requires a train dataset") train_dataset = datasets["train"] if data_args.max_train_samples is not None: train_dataset = train_dataset.select(range(data_args.max_train_samples)) if training_args.do_eval: if "validation" not in datasets and "validation_matched" not in datasets: raise ValueError("--do_eval requires a validation dataset") eval_dataset = datasets["validation_matched" if data_args.task_name == "mnli" else "validation"] if data_args.max_val_samples is not None: eval_dataset = eval_dataset.select(range(data_args.max_val_samples)) if training_args.do_predict or data_args.task_name is not None or data_args.test_file is not None: if "test" not in datasets and "test_matched" not in datasets: raise ValueError("--do_predict requires a test dataset") test_dataset = datasets["test_matched" if data_args.task_name == "mnli" else "test"] if data_args.max_test_samples is not None: test_dataset = test_dataset.select(range(data_args.max_test_samples)) # Log a few random samples from the training set: if training_args.do_train: for index in random.sample(range(len(train_dataset)), 3): logger.info(f"Sample {index} of the training set: {train_dataset[index]}.") # Get the metric function if data_args.task_name is not None: metric = load_metric("glue", data_args.task_name) # TODO: When datasets metrics include regular accuracy, make an else here and remove special branch from # compute_metrics # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a # predictions and label_ids field) and has to return a dictionary string to float. def compute_metrics(p: EvalPrediction): preds = p.predictions[0] if isinstance(p.predictions, tuple) else p.predictions preds = np.squeeze(preds) if is_regression else np.argmax(preds, axis=1) if data_args.task_name is not None: result = metric.compute(predictions=preds, references=p.label_ids) if len(result) > 1: result["combined_score"] = np.mean(list(result.values())).item() return result elif is_regression: return {"mse": ((preds - p.label_ids) ** 2).mean().item()} else: return {"accuracy": (preds == p.label_ids).astype(np.float32).mean().item()} # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. if data_args.pad_to_max_length: data_collator = default_data_collator elif training_args.fp16: data_collator = DataCollatorWithPadding(tokenizer, pad_to_multiple_of=8) else: data_collator = None # Initialize our Trainer trainer = Trainer( model=model, args=training_args, train_dataset=train_dataset if training_args.do_train else None, eval_dataset=eval_dataset if training_args.do_eval else None, compute_metrics=compute_metrics, processing_class=tokenizer, data_collator=data_collator, ) # Training if training_args.do_train: checkpoint = None if last_checkpoint is not None: checkpoint = last_checkpoint elif os.path.isdir(model_args.model_name_or_path): # Check the config from that potential checkpoint has the right number of labels before using it as a # checkpoint. if AutoConfig.from_pretrained(model_args.model_name_or_path).num_labels == num_labels: checkpoint = model_args.model_name_or_path train_result = trainer.train(resume_from_checkpoint=checkpoint) metrics = train_result.metrics max_train_samples = ( data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset) ) metrics["train_samples"] = min(max_train_samples, len(train_dataset)) trainer.save_model() # Saves the tokenizer too for easy upload trainer.log_metrics("train", metrics) trainer.save_metrics("train", metrics) trainer.save_state() # Evaluation if training_args.do_eval: logger.info("*** Evaluate ***") # Loop to handle MNLI double evaluation (matched, mis-matched) tasks = [data_args.task_name] eval_datasets = [eval_dataset] if data_args.task_name == "mnli": tasks.append("mnli-mm") eval_datasets.append(datasets["validation_mismatched"]) for eval_dataset, task in zip(eval_datasets, tasks): metrics = trainer.evaluate(eval_dataset=eval_dataset) max_val_samples = data_args.max_val_samples if data_args.max_val_samples is not None else len(eval_dataset) metrics["eval_samples"] = min(max_val_samples, len(eval_dataset)) trainer.log_metrics("eval", metrics) trainer.save_metrics("eval", metrics) if training_args.do_predict: logger.info("*** Test ***") # Loop to handle MNLI double evaluation (matched, mis-matched) tasks = [data_args.task_name] test_datasets = [test_dataset] if data_args.task_name == "mnli": tasks.append("mnli-mm") test_datasets.append(datasets["test_mismatched"]) for test_dataset, task in zip(test_datasets, tasks): # Removing the `label` columns because it contains -1 and Trainer won't like that. test_dataset = test_dataset.remove_columns("label") predictions = trainer.predict(test_dataset=test_dataset).predictions predictions = np.squeeze(predictions) if is_regression else np.argmax(predictions, axis=1) output_test_file = os.path.join(training_args.output_dir, f"test_results_{task}.txt") if trainer.is_world_process_zero(): with open(output_test_file, "w") as writer: logger.info(f"***** Test results {task} *****") writer.write("index\tprediction\n") for index, item in enumerate(predictions): if is_regression: writer.write(f"{index}\t{item:3.3f}\n") else: item = label_list[item] writer.write(f"{index}\t{item}\n") def _mp_fn(index): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
transformers/tests/sagemaker/scripts/pytorch/run_glue_model_parallelism.py/0
{ "file_path": "transformers/tests/sagemaker/scripts/pytorch/run_glue_model_parallelism.py", "repo_id": "transformers", "token_count": 9566 }
581
# 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 numpy as np from transformers import BatchFeature from transformers.testing_utils import require_torch from .test_feature_extraction_common import FeatureExtractionSavingTestMixin class SequenceFeatureExtractionTestMixin(FeatureExtractionSavingTestMixin): # to overwrite at feature extractactor specific tests feat_extract_tester = None feature_extraction_class = None @property def feat_extract_dict(self): return self.feat_extract_tester.prepare_feat_extract_dict() def test_feat_extract_common_properties(self): feat_extract = self.feature_extraction_class(**self.feat_extract_dict) self.assertTrue(hasattr(feat_extract, "feature_size")) self.assertTrue(hasattr(feat_extract, "sampling_rate")) self.assertTrue(hasattr(feat_extract, "padding_value")) def test_batch_feature(self): speech_inputs = self.feat_extract_tester.prepare_inputs_for_common() feat_extract = self.feature_extraction_class(**self.feat_extract_dict) input_name = feat_extract.model_input_names[0] processed_features = BatchFeature({input_name: speech_inputs}) self.assertTrue(all(len(x) == len(y) for x, y in zip(speech_inputs, processed_features[input_name]))) speech_inputs = self.feat_extract_tester.prepare_inputs_for_common(equal_length=True) processed_features = BatchFeature({input_name: speech_inputs}, tensor_type="np") batch_features_input = processed_features[input_name] if len(batch_features_input.shape) < 3: batch_features_input = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0]), self.feat_extract_tester.feature_size) ) @require_torch def test_batch_feature_pt(self): speech_inputs = self.feat_extract_tester.prepare_inputs_for_common(equal_length=True) feat_extract = self.feature_extraction_class(**self.feat_extract_dict) input_name = feat_extract.model_input_names[0] processed_features = BatchFeature({input_name: speech_inputs}, tensor_type="pt") batch_features_input = processed_features[input_name] if len(batch_features_input.shape) < 3: batch_features_input = batch_features_input[:, :, None] self.assertTrue( batch_features_input.shape == (self.feat_extract_tester.batch_size, len(speech_inputs[0]), self.feat_extract_tester.feature_size) ) def _check_padding(self, numpify=False): def _inputs_have_equal_length(input): length = len(input[0]) for input_slice in input[1:]: if len(input_slice) != length: return False return True def _inputs_are_equal(input_1, input_2): if len(input_1) != len(input_2): return False for input_slice_1, input_slice_2 in zip(input_1, input_2): if not np.allclose(np.asarray(input_slice_1), np.asarray(input_slice_2), atol=1e-3): return False return True feat_extract = self.feature_extraction_class(**self.feat_extract_dict) speech_inputs = self.feat_extract_tester.prepare_inputs_for_common(numpify=numpify) input_name = feat_extract.model_input_names[0] processed_features = BatchFeature({input_name: speech_inputs}) pad_diff = self.feat_extract_tester.seq_length_diff pad_max_length = self.feat_extract_tester.max_seq_length + pad_diff pad_min_length = self.feat_extract_tester.min_seq_length batch_size = self.feat_extract_tester.batch_size feature_size = self.feat_extract_tester.feature_size # test padding for list[int] + numpy input_1 = feat_extract.pad(processed_features, padding=False) input_1 = input_1[input_name] input_2 = feat_extract.pad(processed_features, padding="longest") input_2 = input_2[input_name] input_3 = feat_extract.pad(processed_features, padding="max_length", max_length=len(speech_inputs[-1])) input_3 = input_3[input_name] input_4 = feat_extract.pad(processed_features, padding="longest", return_tensors="np") input_4 = input_4[input_name] # max_length parameter has to be provided when setting `padding="max_length"` with self.assertRaises(ValueError): feat_extract.pad(processed_features, padding="max_length")[input_name] input_5 = feat_extract.pad( processed_features, padding="max_length", max_length=pad_max_length, return_tensors="np" ) input_5 = input_5[input_name] self.assertFalse(_inputs_have_equal_length(input_1)) self.assertTrue(_inputs_have_equal_length(input_2)) self.assertTrue(_inputs_have_equal_length(input_3)) self.assertTrue(_inputs_are_equal(input_2, input_3)) self.assertTrue(len(input_1[0]) == pad_min_length) self.assertTrue(len(input_1[1]) == pad_min_length + pad_diff) self.assertTrue(input_4.shape[:2] == (batch_size, len(input_3[0]))) self.assertTrue(input_5.shape[:2] == (batch_size, pad_max_length)) if feature_size > 1: self.assertTrue(input_4.shape[2] == input_5.shape[2] == feature_size) # test padding for `pad_to_multiple_of` for list[int] + numpy input_6 = feat_extract.pad(processed_features, pad_to_multiple_of=10) input_6 = input_6[input_name] input_7 = feat_extract.pad(processed_features, padding="longest", pad_to_multiple_of=10) input_7 = input_7[input_name] input_8 = feat_extract.pad( processed_features, padding="max_length", pad_to_multiple_of=10, max_length=pad_max_length ) input_8 = input_8[input_name] input_9 = feat_extract.pad( processed_features, padding="max_length", pad_to_multiple_of=10, max_length=pad_max_length, return_tensors="np", ) input_9 = input_9[input_name] self.assertTrue(all(len(x) % 10 == 0 for x in input_6)) self.assertTrue(_inputs_are_equal(input_6, input_7)) expected_mult_pad_length = pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10 self.assertTrue(all(len(x) == expected_mult_pad_length for x in input_8)) self.assertEqual(input_9.shape[:2], (batch_size, expected_mult_pad_length)) if feature_size > 1: self.assertTrue(input_9.shape[2] == feature_size) # Check padding value is correct padding_vector_sum = (np.ones(self.feat_extract_tester.feature_size) * feat_extract.padding_value).sum() self.assertTrue( abs(np.asarray(input_2[0])[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length)) < 1e-3 ) self.assertTrue( abs( np.asarray(input_2[1])[pad_min_length + pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) ) < 1e-3 ) self.assertTrue( abs( np.asarray(input_2[2])[pad_min_length + 2 * pad_diff :].sum() - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) ) < 1e-3 ) self.assertTrue( abs(input_5[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length)) < 1e-3 ) self.assertTrue( abs(input_9[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length)) < 1e-3 ) def _check_truncation(self, numpify=False): def _inputs_have_equal_length(input): length = len(input[0]) for input_slice in input[1:]: if len(input_slice) != length: return False return True def _inputs_are_equal(input_1, input_2): if len(input_1) != len(input_2): return False for input_slice_1, input_slice_2 in zip(input_1, input_2): if not np.allclose(np.asarray(input_slice_1), np.asarray(input_slice_2), atol=1e-3): return False return True feat_extract = self.feature_extraction_class(**self.feat_extract_dict) speech_inputs = self.feat_extract_tester.prepare_inputs_for_common(numpify=numpify) input_name = feat_extract.model_input_names[0] processed_features = BatchFeature({input_name: speech_inputs}) # truncate to smallest input_1 = feat_extract.pad( processed_features, padding="max_length", max_length=len(speech_inputs[0]), truncation=True ) input_1 = input_1[input_name] input_2 = feat_extract.pad(processed_features, padding="max_length", max_length=len(speech_inputs[0])) input_2 = input_2[input_name] self.assertTrue(_inputs_have_equal_length(input_1)) self.assertFalse(_inputs_have_equal_length(input_2)) # truncate to smallest with np input_3 = feat_extract.pad( processed_features, padding="max_length", max_length=len(speech_inputs[0]), return_tensors="np", truncation=True, ) input_3 = input_3[input_name] input_4 = feat_extract.pad( processed_features, padding="max_length", max_length=len(speech_inputs[0]), return_tensors="np" ) input_4 = input_4[input_name] self.assertTrue(_inputs_have_equal_length(input_3)) self.assertTrue(input_3.shape[1] == len(speech_inputs[0])) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(input_4)) # truncate to middle input_5 = feat_extract.pad( processed_features, padding="max_length", max_length=len(speech_inputs[1]), truncation=True, return_tensors="np", ) input_5 = input_5[input_name] input_6 = feat_extract.pad( processed_features, padding="max_length", max_length=len(speech_inputs[1]), truncation=True ) input_6 = input_6[input_name] input_7 = feat_extract.pad( processed_features, padding="max_length", max_length=len(speech_inputs[1]), return_tensors="np" ) input_7 = input_7[input_name] self.assertTrue(input_5.shape[1] == len(speech_inputs[1])) self.assertTrue(_inputs_have_equal_length(input_5)) self.assertTrue(_inputs_have_equal_length(input_6)) self.assertTrue(_inputs_are_equal(input_5, input_6)) # since truncation forces padding to be smaller than longest input # function can't return `np.ndarray`, but has to return list self.assertFalse(_inputs_have_equal_length(input_7)) self.assertTrue(len(input_7[-1]) == len(speech_inputs[-1])) # padding has to be max_length when setting `truncation=True` with self.assertRaises(ValueError): feat_extract.pad(processed_features, truncation=True)[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(ValueError): feat_extract.pad(processed_features, padding="longest", truncation=True)[input_name] # padding has to be max_length when setting `truncation=True` with self.assertRaises(ValueError): feat_extract.pad(processed_features, padding="longest", truncation=True)[input_name] # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" with self.assertRaises(ValueError): feat_extract.pad(processed_features, padding="max_length", truncation=True)[input_name] # test truncation for `pad_to_multiple_of` for list[int] + numpy pad_to_multiple_of = 12 input_8 = feat_extract.pad( processed_features, padding="max_length", max_length=len(speech_inputs[0]), pad_to_multiple_of=pad_to_multiple_of, truncation=True, ) input_8 = input_8[input_name] input_9 = feat_extract.pad( processed_features, padding="max_length", max_length=len(speech_inputs[0]), pad_to_multiple_of=pad_to_multiple_of, ) input_9 = input_9[input_name] # retrieve expected_length as multiple of pad_to_multiple_of expected_length = len(speech_inputs[0]) if expected_length % pad_to_multiple_of != 0: expected_length = ((len(speech_inputs[0]) // pad_to_multiple_of) + 1) * pad_to_multiple_of self.assertTrue(len(input_8[0]) == expected_length) self.assertTrue(_inputs_have_equal_length(input_8)) self.assertFalse(_inputs_have_equal_length(input_9)) def test_padding_from_list(self): self._check_padding(numpify=False) def test_padding_from_array(self): self._check_padding(numpify=True) def test_truncation_from_list(self): self._check_truncation(numpify=False) def test_truncation_from_array(self): self._check_truncation(numpify=True) @require_torch def test_padding_accepts_tensors_pt(self): feat_extract = self.feature_extraction_class(**self.feat_extract_dict) speech_inputs = self.feat_extract_tester.prepare_inputs_for_common() input_name = feat_extract.model_input_names[0] processed_features = BatchFeature({input_name: speech_inputs}) input_np = feat_extract.pad(processed_features, padding="longest", return_tensors="np")[input_name] input_pt = feat_extract.pad(processed_features, padding="longest", return_tensors="pt")[input_name] self.assertTrue(abs(input_np.astype(np.float32).sum() - input_pt.numpy().astype(np.float32).sum()) < 1e-2) def test_attention_mask(self): feat_dict = self.feat_extract_dict feat_dict["return_attention_mask"] = True feat_extract = self.feature_extraction_class(**feat_dict) speech_inputs = self.feat_extract_tester.prepare_inputs_for_common() input_lengths = [len(x) for x in speech_inputs] input_name = feat_extract.model_input_names[0] processed = BatchFeature({input_name: speech_inputs}) processed = feat_extract.pad(processed, padding="longest", return_tensors="np") self.assertIn("attention_mask", processed) self.assertListEqual(list(processed.attention_mask.shape), list(processed[input_name].shape[:2])) self.assertListEqual(processed.attention_mask.sum(-1).tolist(), input_lengths) def test_attention_mask_with_truncation(self): feat_dict = self.feat_extract_dict feat_dict["return_attention_mask"] = True feat_extract = self.feature_extraction_class(**feat_dict) speech_inputs = self.feat_extract_tester.prepare_inputs_for_common() input_lengths = [len(x) for x in speech_inputs] input_name = feat_extract.model_input_names[0] processed = BatchFeature({input_name: speech_inputs}) max_length = min(input_lengths) processed_pad = feat_extract.pad( processed, padding="max_length", max_length=max_length, truncation=True, return_tensors="np" ) self.assertIn("attention_mask", processed_pad) self.assertListEqual( list(processed_pad.attention_mask.shape), [processed_pad[input_name].shape[0], max_length] ) self.assertListEqual( processed_pad.attention_mask[:, :max_length].sum(-1).tolist(), [max_length for x in speech_inputs] )
transformers/tests/test_sequence_feature_extraction_common.py/0
{ "file_path": "transformers/tests/test_sequence_feature_extraction_common.py", "repo_id": "transformers", "token_count": 7322 }
582
# Copyright 2020 the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from transformers import ( AutoModelForSeq2SeqLM, BertTokenizer, DataCollatorForSeq2Seq, EncoderDecoderModel, GenerationConfig, Seq2SeqTrainer, Seq2SeqTrainingArguments, T5Tokenizer, ) from transformers.testing_utils import TestCasePlus, require_sentencepiece, require_torch, slow from transformers.utils import is_datasets_available if is_datasets_available(): import datasets @require_sentencepiece class Seq2seqTrainerTester(TestCasePlus): @slow @require_torch def test_finetune_bert2bert(self): bert2bert = EncoderDecoderModel.from_encoder_decoder_pretrained("prajjwal1/bert-tiny", "prajjwal1/bert-tiny") tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased") bert2bert.config.vocab_size = bert2bert.config.encoder.vocab_size bert2bert.config.eos_token_id = tokenizer.sep_token_id bert2bert.config.decoder_start_token_id = tokenizer.cls_token_id bert2bert.config.max_length = 128 train_dataset = datasets.load_dataset("abisee/cnn_dailymail", "3.0.0", split="train[:1%]") val_dataset = datasets.load_dataset("abisee/cnn_dailymail", "3.0.0", split="validation[:1%]") train_dataset = train_dataset.select(range(32)) val_dataset = val_dataset.select(range(16)) batch_size = 4 def _map_to_encoder_decoder_inputs(batch): # Tokenizer will automatically set [BOS] <text> [EOS] inputs = tokenizer(batch["article"], padding="max_length", truncation=True, max_length=512) outputs = tokenizer(batch["highlights"], padding="max_length", truncation=True, max_length=128) batch["input_ids"] = inputs.input_ids batch["attention_mask"] = inputs.attention_mask batch["decoder_input_ids"] = outputs.input_ids batch["labels"] = outputs.input_ids.copy() batch["labels"] = [ [-100 if token == tokenizer.pad_token_id else token for token in labels] for labels in batch["labels"] ] batch["decoder_attention_mask"] = outputs.attention_mask assert all(len(x) == 512 for x in inputs.input_ids) assert all(len(x) == 128 for x in outputs.input_ids) return batch def _compute_metrics(pred): labels_ids = pred.label_ids pred_ids = pred.predictions # all unnecessary tokens are removed pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True) label_str = tokenizer.batch_decode(labels_ids, skip_special_tokens=True) accuracy = sum([int(pred_str[i] == label_str[i]) for i in range(len(pred_str))]) / len(pred_str) return {"accuracy": accuracy} # map train dataset train_dataset = train_dataset.map( _map_to_encoder_decoder_inputs, batched=True, batch_size=batch_size, remove_columns=["article", "highlights"], ) train_dataset.set_format( type="torch", columns=["input_ids", "attention_mask", "decoder_input_ids", "decoder_attention_mask", "labels"], ) # same for validation dataset val_dataset = val_dataset.map( _map_to_encoder_decoder_inputs, batched=True, batch_size=batch_size, remove_columns=["article", "highlights"], ) val_dataset.set_format( type="torch", columns=["input_ids", "attention_mask", "decoder_input_ids", "decoder_attention_mask", "labels"], ) output_dir = self.get_auto_remove_tmp_dir() training_args = Seq2SeqTrainingArguments( output_dir=output_dir, per_device_train_batch_size=batch_size, per_device_eval_batch_size=batch_size, predict_with_generate=True, eval_strategy="steps", do_train=True, do_eval=True, warmup_steps=0, eval_steps=2, logging_steps=2, report_to="none", ) # instantiate trainer trainer = Seq2SeqTrainer( model=bert2bert, args=training_args, compute_metrics=_compute_metrics, train_dataset=train_dataset, eval_dataset=val_dataset, processing_class=tokenizer, ) # start training trainer.train() @slow @require_torch def test_return_sequences(self): # Tests that the number of generated sequences is correct when num_return_sequences > 1 # and essentially ensuring that `accelerator.gather()` is used instead of `gather_for_metrics` INPUT_COLUMN = "question" TARGET_COLUMN = "answer" MAX_INPUT_LENGTH = 256 MAX_TARGET_LENGTH = 256 dataset = datasets.load_dataset("openai/gsm8k", "main", split="train[:38]") model = AutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-small") tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-small") data_collator = DataCollatorForSeq2Seq(tokenizer, model=model, return_tensors="pt", padding="longest") gen_config = GenerationConfig.from_pretrained( "google-t5/t5-small", max_length=None, min_length=None, max_new_tokens=256, min_new_tokens=1, num_beams=5 ) training_args = Seq2SeqTrainingArguments(".", predict_with_generate=True, report_to="none") trainer = Seq2SeqTrainer( model=model, args=training_args, processing_class=tokenizer, data_collator=data_collator, compute_metrics=lambda x: {"samples": x[0].shape[0]}, ) def prepare_data(examples): # Remove pairs where at least one record is none inputs = examples[INPUT_COLUMN] targets = examples[TARGET_COLUMN] model_inputs = tokenizer(inputs, max_length=MAX_INPUT_LENGTH, truncation=True) labels = tokenizer(text_target=targets, max_length=MAX_TARGET_LENGTH, truncation=True) model_inputs["labels"] = labels["input_ids"] return model_inputs prepared_dataset = dataset.map(prepare_data, batched=True, remove_columns=[INPUT_COLUMN, TARGET_COLUMN]) dataset_len = len(prepared_dataset) # 38 for num_return_sequences in range(3, 0, -1): gen_config.num_return_sequences = num_return_sequences metrics = trainer.evaluate(eval_dataset=prepared_dataset, generation_config=gen_config) assert metrics["eval_samples"] == dataset_len * num_return_sequences, ( f"Got {metrics['eval_samples']}, expected: {dataset_len * num_return_sequences}" ) @require_torch def test_bad_generation_config_fail_early(self): # Tests that a bad generation config causes the trainer to fail early model = AutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-small") tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-small") data_collator = DataCollatorForSeq2Seq(tokenizer, model=model, return_tensors="pt", padding="longest") gen_config = GenerationConfig(do_sample=False, top_p=0.9) # bad: top_p is not compatible with do_sample=False training_args = Seq2SeqTrainingArguments( ".", predict_with_generate=True, generation_config=gen_config, report_to="none" ) with self.assertRaises(ValueError) as exc: _ = Seq2SeqTrainer( model=model, args=training_args, processing_class=tokenizer, data_collator=data_collator, compute_metrics=lambda x: {"samples": x[0].shape[0]}, ) self.assertIn("Fix these issues to train your model", str(exc.exception))
transformers/tests/trainer/test_trainer_seq2seq.py/0
{ "file_path": "transformers/tests/trainer/test_trainer_seq2seq.py", "repo_id": "transformers", "token_count": 3777 }
583
# Copyright 2024 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from typing import Literal, Optional, Union from transformers.utils import DocstringParsingException, TypeHintParsingException, get_json_schema class JsonSchemaGeneratorTest(unittest.TestCase): def test_simple_function(self): def fn(x: int): """ Test function Args: x: The input """ return x schema = get_json_schema(fn) expected_schema = { "name": "fn", "description": "Test function", "parameters": { "type": "object", "properties": {"x": {"type": "integer", "description": "The input"}}, "required": ["x"], }, } self.assertEqual(schema["function"], expected_schema) def test_no_arguments(self): def fn(): """ Test function """ return True schema = get_json_schema(fn) expected_schema = { "name": "fn", "description": "Test function", "parameters": {"type": "object", "properties": {}}, } self.assertEqual(schema["function"], expected_schema) def test_union(self): def fn(x: Union[int, float]): """ Test function Args: x: The input """ return x schema = get_json_schema(fn) expected_schema = { "name": "fn", "description": "Test function", "parameters": { "type": "object", "properties": {"x": {"type": ["integer", "number"], "description": "The input"}}, "required": ["x"], }, } self.assertEqual(schema["function"], expected_schema) def test_optional(self): def fn(x: Optional[int]): """ Test function Args: x: The input """ return x schema = get_json_schema(fn) expected_schema = { "name": "fn", "description": "Test function", "parameters": { "type": "object", "properties": {"x": {"type": "integer", "description": "The input", "nullable": True}}, "required": ["x"], }, } self.assertEqual(schema["function"], expected_schema) def test_default_arg(self): def fn(x: int = 42): """ Test function Args: x: The input """ return x schema = get_json_schema(fn) expected_schema = { "name": "fn", "description": "Test function", "parameters": {"type": "object", "properties": {"x": {"type": "integer", "description": "The input"}}}, } self.assertEqual(schema["function"], expected_schema) def test_nested_list(self): def fn(x: list[list[Union[str, int]]]): """ Test function Args: x: The input """ return x schema = get_json_schema(fn) expected_schema = { "name": "fn", "description": "Test function", "parameters": { "type": "object", "properties": { "x": { "type": "array", "items": {"type": "array", "items": {"type": ["integer", "string"]}}, "description": "The input", } }, "required": ["x"], }, } self.assertEqual(schema["function"], expected_schema) def test_multiple_arguments(self): def fn(x: int, y: str): """ Test function Args: x: The input y: Also the input """ return x schema = get_json_schema(fn) expected_schema = { "name": "fn", "description": "Test function", "parameters": { "type": "object", "properties": { "x": {"type": "integer", "description": "The input"}, "y": {"type": "string", "description": "Also the input"}, }, "required": ["x", "y"], }, } self.assertEqual(schema["function"], expected_schema) def test_multiple_complex_arguments(self): def fn(x: list[Union[int, float]], y: Optional[Union[int, str]] = None): """ Test function Args: x: The input y: Also the input """ return x schema = get_json_schema(fn) expected_schema = { "name": "fn", "description": "Test function", "parameters": { "type": "object", "properties": { "x": {"type": "array", "items": {"type": ["integer", "number"]}, "description": "The input"}, "y": { "type": ["integer", "string"], "nullable": True, "description": "Also the input", }, }, "required": ["x"], }, } self.assertEqual(schema["function"], expected_schema) def test_missing_docstring(self): def fn(x: int): return x with self.assertRaises(DocstringParsingException): get_json_schema(fn) def test_missing_param_docstring(self): def fn(x: int): """ Test function """ return x with self.assertRaises(DocstringParsingException): get_json_schema(fn) def test_missing_type_hint(self): def fn(x): """ Test function Args: x: The input """ return x with self.assertRaises(TypeHintParsingException): get_json_schema(fn) def test_return_value(self): def fn(x: int) -> int: """ Test function Args: x: The input """ return x schema = get_json_schema(fn) expected_schema = { "name": "fn", "description": "Test function", "parameters": { "type": "object", "properties": {"x": {"type": "integer", "description": "The input"}}, "required": ["x"], }, "return": {"type": "integer"}, } self.assertEqual(schema["function"], expected_schema) def test_return_value_docstring(self): def fn(x: int) -> int: """ Test function Args: x: The input Returns: The output """ return x schema = get_json_schema(fn) expected_schema = { "name": "fn", "description": "Test function", "parameters": { "type": "object", "properties": {"x": {"type": "integer", "description": "The input"}}, "required": ["x"], }, "return": {"type": "integer", "description": "The output"}, } self.assertEqual(schema["function"], expected_schema) def test_tuple(self): def fn(x: tuple[int, str]): """ Test function Args: x: The input Returns: The output """ return x schema = get_json_schema(fn) expected_schema = { "name": "fn", "description": "Test function", "parameters": { "type": "object", "properties": { "x": { "type": "array", "prefixItems": [{"type": "integer"}, {"type": "string"}], "description": "The input", } }, "required": ["x"], }, } self.assertEqual(schema["function"], expected_schema) def test_single_element_tuple_fails(self): def fn(x: tuple[int]): """ Test function Args: x: The input Returns: The output """ return x # Single-element tuples should just be the type itself, or List[type] for variable-length inputs with self.assertRaises(TypeHintParsingException): get_json_schema(fn) def test_ellipsis_type_fails(self): def fn(x: tuple[int, ...]): """ Test function Args: x: The input Returns: The output """ return x # Variable length inputs should be specified with List[type], not Tuple[type, ...] with self.assertRaises(TypeHintParsingException): get_json_schema(fn) def test_enum_extraction(self): def fn(temperature_format: str): """ Test function Args: temperature_format: The temperature format to use (Choices: ["celsius", "fahrenheit"]) Returns: The temperature """ return -40.0 # Let's see if that gets correctly parsed as an enum schema = get_json_schema(fn) expected_schema = { "name": "fn", "description": "Test function", "parameters": { "type": "object", "properties": { "temperature_format": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "The temperature format to use", } }, "required": ["temperature_format"], }, } self.assertEqual(schema["function"], expected_schema) def test_literal(self): def fn( temperature_format: Literal["celsius", "fahrenheit"], booleanish: Literal[True, False, 0, 1, "y", "n"] = False, ): """ Test function Args: temperature_format: The temperature format to use booleanish: A value that can be regarded as boolean Returns: The temperature """ return -40.0 # Let's see if that gets correctly parsed as an enum schema = get_json_schema(fn) expected_schema = { "name": "fn", "description": "Test function", "parameters": { "type": "object", "properties": { "temperature_format": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "The temperature format to use", }, "booleanish": { "type": ["boolean", "integer", "string"], "enum": [True, False, 0, 1, "y", "n"], "description": "A value that can be regarded as boolean", }, }, "required": ["temperature_format"], }, } self.assertEqual(schema["function"], expected_schema) def test_multiline_docstring_with_types(self): def fn(x: int, y: int): """ Test function Args: x: The first input y: The second input. This is a longer description that spans multiple lines with indentation and stuff. Returns: God knows what """ pass schema = get_json_schema(fn) expected_schema = { "name": "fn", "description": "Test function", "parameters": { "type": "object", "properties": { "x": {"type": "integer", "description": "The first input"}, "y": { "type": "integer", "description": "The second input. This is a longer description that spans multiple lines with indentation and stuff.", }, }, "required": ["x", "y"], }, } self.assertEqual(schema["function"], expected_schema) def test_return_none(self): def fn(x: int) -> None: """ Test function Args: x: The first input """ pass schema = get_json_schema(fn) expected_schema = { "name": "fn", "description": "Test function", "parameters": { "type": "object", "properties": { "x": {"type": "integer", "description": "The first input"}, }, "required": ["x"], }, "return": {"type": "null"}, } self.assertEqual(schema["function"], expected_schema) def test_everything_all_at_once(self): def fn( x: str, y: Optional[list[Union[str, int]]], z: tuple[Union[str, int], str] = (42, "hello") ) -> tuple[int, str]: """ Test function with multiple args, and docstring args that we have to strip out. Args: x: The first input. It's got a big multiline description and also contains (choices: ["a", "b", "c"]) y: The second input. It's a big list with a single-line description. z: The third input. It's some kind of tuple with a default arg. Returns: The output. The return description is also a big multiline description that spans multiple lines. """ pass schema = get_json_schema(fn) expected_schema = { "name": "fn", "description": "Test function with multiple args, and docstring args that we have to strip out.", "parameters": { "type": "object", "properties": { "x": { "type": "string", "enum": ["a", "b", "c"], "description": "The first input. It's got a big multiline description and also contains", }, "y": { "type": "array", "items": {"type": ["integer", "string"]}, "nullable": True, "description": "The second input. It's a big list with a single-line description.", }, "z": { "type": "array", "prefixItems": [{"type": ["integer", "string"]}, {"type": "string"}], "description": "The third input. It's some kind of tuple with a default arg.", }, }, "required": ["x", "y"], }, "return": { "type": "array", "prefixItems": [{"type": "integer"}, {"type": "string"}], "description": "The output. The return description is also a big multiline\n description that spans multiple lines.", }, } self.assertEqual(schema["function"], expected_schema)
transformers/tests/utils/test_chat_template_utils.py/0
{ "file_path": "transformers/tests/utils/test_chat_template_utils.py", "repo_id": "transformers", "token_count": 8910 }
584
import sys from transformers.testing_utils import run_test_using_subprocess from transformers.utils.import_utils import clear_import_cache @run_test_using_subprocess def test_clear_import_cache(): """Test the clear_import_cache function.""" # Save initial state initial_modules = {name: mod for name, mod in sys.modules.items() if name.startswith("transformers.")} assert len(initial_modules) > 0, "No transformers modules loaded before test" # Execute clear_import_cache() function clear_import_cache() # Verify modules were removed remaining_modules = {name: mod for name, mod in sys.modules.items() if name.startswith("transformers.")} assert len(remaining_modules) < len(initial_modules), "No modules were removed" # Import and verify module exists from transformers.models.auto import modeling_auto assert "transformers.models.auto.modeling_auto" in sys.modules assert modeling_auto.__name__ == "transformers.models.auto.modeling_auto"
transformers/tests/utils/test_import_utils.py/0
{ "file_path": "transformers/tests/utils/test_import_utils.py", "repo_id": "transformers", "token_count": 303 }
585
#!/usr/bin/env python # coding=utf-8 # Copyright 2024 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. import argparse import json import os import re import subprocess import requests def create_script(target_test): """Create a python script to be run by `git bisect run` to determine if `target_test` passes or fails. If a test is not found in a commit, the script with exit code `0` (i.e. `Success`). Args: target_test (`str`): The test to check. Returns: `str`: The script to be run by `git bisect run`. """ script = f""" import os import subprocess result = subprocess.run( ["python3", "-m", "pytest", "-v", "-rfEp", f"{target_test}"], capture_output = True, text=True, ) print(result.stdout) if f"PASSED {target_test}" in result.stdout: print("test passed") exit(0) elif len(result.stderr) > 0: if "ERROR: file or directory not found: " in result.stderr: print("test file or directory not found in this commit") exit(0) elif "ERROR: not found: " in result.stderr: print("test not found in this commit") exit(0) else: print(f"pytest failed to run: {{result.stderr}}") exit(-1) elif f"FAILED {target_test}" in result.stdout: print("test failed") exit(2) exit(0) """ with open("target_script.py", "w") as fp: fp.write(script.strip()) def find_bad_commit(target_test, start_commit, end_commit): """Find (backward) the earliest commit between `start_commit` and `end_commit` at which `target_test` fails. Args: target_test (`str`): The test to check. start_commit (`str`): The latest commit. end_commit (`str`): The earliest commit. Returns: `str`: The earliest commit at which `target_test` fails. """ if start_commit == end_commit: return start_commit create_script(target_test=target_test) bash = f""" git bisect reset git bisect start {start_commit} {end_commit} git bisect run python3 target_script.py """ with open("run_git_bisect.sh", "w") as fp: fp.write(bash.strip()) result = subprocess.run( ["bash", "run_git_bisect.sh"], check=False, capture_output=True, text=True, ) print(result.stdout) if "error: bisect run failed" in result.stderr: index = result.stderr.find("error: bisect run failed") bash_error = result.stderr[index:] error_msg = f"Error when running git bisect:\nbash error: {bash_error}" pattern = "pytest failed to run: .+" pytest_errors = re.findall(pattern, result.stdout) if len(pytest_errors) > 0: pytest_error = pytest_errors[0] index = pytest_error.find("pytest failed to run: ") index += len("pytest failed to run: ") pytest_error = pytest_error[index:] error_msg += f"pytest error: {pytest_error}" raise ValueError(error_msg) pattern = r"(.+) is the first bad commit" commits = re.findall(pattern, result.stdout) bad_commit = None if len(commits) > 0: bad_commit = commits[0] print(f"Between `start_commit` {start_commit} and `end_commit` {end_commit}") print(f"bad_commit: {bad_commit}\n") return bad_commit def get_commit_info(commit): """Get information for a commit via `api.github.com`.""" pr_number = None author = None merged_author = None url = f"https://api.github.com/repos/huggingface/transformers/commits/{commit}/pulls" pr_info_for_commit = requests.get(url).json() if len(pr_info_for_commit) > 0: pr_number = pr_info_for_commit[0]["number"] url = f"https://api.github.com/repos/huggingface/transformers/pulls/{pr_number}" pr_for_commit = requests.get(url).json() author = pr_for_commit["user"]["login"] if pr_for_commit["merged_by"] is not None: merged_author = pr_for_commit["merged_by"]["login"] if author is None: url = f"https://api.github.com/repos/huggingface/transformers/commits/{commit}" commit_info = requests.get(url).json() author = commit_info["author"]["login"] return {"commit": commit, "pr_number": pr_number, "author": author, "merged_by": merged_author} if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--start_commit", type=str, required=True, help="The latest commit hash to check.") parser.add_argument("--end_commit", type=str, required=True, help="The earliest commit hash to check.") parser.add_argument("--test", type=str, help="The test to check.") parser.add_argument("--file", type=str, help="The report file.") parser.add_argument("--output_file", type=str, required=True, help="The path of the output file.") args = parser.parse_args() print(f"start_commit: {args.start_commit}") print(f"end_commit: {args.end_commit}") # `get_commit_info` uses `requests.get()` to request info. via `api.github.com` without using token. # If there are many new failed tests in a workflow run, this script may fail at some point with `KeyError` at # `pr_number = pr_info_for_commit[0]["number"]` due to the rate limit. # Let's cache the commit info. and reuse them whenever possible. commit_info_cache = {} if len({args.test is None, args.file is None}) != 2: raise ValueError("Exactly one argument `test` or `file` must be specified.") if args.test is not None: commit = find_bad_commit(target_test=args.test, start_commit=args.start_commit, end_commit=args.end_commit) with open(args.output_file, "w", encoding="UTF-8") as fp: fp.write(f"{args.test}\n{commit}") elif os.path.isfile(args.file): with open(args.file, "r", encoding="UTF-8") as fp: reports = json.load(fp) for model in reports: # TODO: make this script able to deal with both `single-gpu` and `multi-gpu` via a new argument. reports[model].pop("multi-gpu", None) failed_tests = reports[model]["single-gpu"] failed_tests_with_bad_commits = [] for test in failed_tests: commit = find_bad_commit(target_test=test, start_commit=args.start_commit, end_commit=args.end_commit) info = {"test": test, "commit": commit} if commit in commit_info_cache: commit_info = commit_info_cache[commit] else: commit_info = get_commit_info(commit) commit_info_cache[commit] = commit_info info.update(commit_info) failed_tests_with_bad_commits.append(info) # If no single-gpu test failures, remove the key if len(failed_tests_with_bad_commits) > 0: reports[model]["single-gpu"] = failed_tests_with_bad_commits else: reports[model].pop("single-gpu", None) # remove the models without any test failure reports = {k: v for k, v in reports.items() if len(v) > 0} with open(args.output_file, "w", encoding="UTF-8") as fp: json.dump(reports, fp, ensure_ascii=False, indent=4)
transformers/utils/check_bad_commit.py/0
{ "file_path": "transformers/utils/check_bad_commit.py", "repo_id": "transformers", "token_count": 3137 }
586
# 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 argparse import json import subprocess from dataclasses import dataclass from pathlib import Path DEFAULT_GPU_NAMES = ["mi300", "mi325", "mi355", "h100", "a10"] def simplify_gpu_name(gpu_name: str, simplified_names: list[str]) -> str: matches = [] for simplified_name in simplified_names: if simplified_name in gpu_name: matches.append(simplified_name) if len(matches) == 1: return matches[0] return gpu_name def parse_short_summary_line(line: str) -> tuple[str | None, int]: if line.startswith("PASSED"): return "passed", 1 if line.startswith("FAILED"): return "failed", 1 if line.startswith("SKIPPED"): line = line.split("[", maxsplit=1)[1] line = line.split("]", maxsplit=1)[0] return "skipped", int(line) if line.startswith("ERROR"): return "error", 1 return None, 0 def validate_path(p: str) -> Path: # Validate path and apply glob pattern if provided path = Path(p) assert path.is_dir(), f"Path {path} is not a directory" return path def get_gpu_name(gpu_name: str | None) -> str: # Get GPU name if available if gpu_name is None: try: import torch gpu_name = torch.cuda.get_device_name() except Exception as e: print(f"Failed to get GPU name with {e}") gpu_name = "unknown" else: gpu_name = gpu_name.replace(" ", "_").lower() gpu_name = simplify_gpu_name(gpu_name, DEFAULT_GPU_NAMES) return gpu_name def get_commit_hash(commit_hash: str | None) -> str: # Get commit hash if available if commit_hash is None: try: commit_hash = subprocess.check_output(["git", "rev-parse", "HEAD"]).decode("utf-8").strip() except Exception as e: print(f"Failed to get commit hash with {e}") commit_hash = "unknown" return commit_hash[:7] @dataclass class Args: path: Path machine_type: str gpu_name: str commit_hash: str job: str | None report_repo_id: str | None def get_arguments(args: argparse.Namespace) -> Args: path = validate_path(args.path) machine_type = args.machine_type gpu_name = get_gpu_name(args.gpu_name) commit_hash = get_commit_hash(args.commit_hash) job = args.job report_repo_id = args.report_repo_id return Args(path, machine_type, gpu_name, commit_hash, job, report_repo_id) def upload_collated_report(job: str, report_repo_id: str, filename: str): # Alternatively we can check for the existence of the collated_reports file and upload in notification_service.py import os from get_previous_daily_ci import get_last_daily_ci_run from huggingface_hub import HfApi api = HfApi() # if it is not a scheduled run, upload the reports to a subfolder under `report_repo_folder` report_repo_subfolder = "" if os.getenv("GITHUB_EVENT_NAME") != "schedule": report_repo_subfolder = f"{os.getenv('GITHUB_RUN_NUMBER')}-{os.getenv('GITHUB_RUN_ID')}" report_repo_subfolder = f"runs/{report_repo_subfolder}" workflow_run = get_last_daily_ci_run( token=os.environ["ACCESS_REPO_INFO_TOKEN"], workflow_run_id=os.getenv("GITHUB_RUN_ID") ) workflow_run_created_time = workflow_run["created_at"] report_repo_folder = workflow_run_created_time.split("T")[0] if report_repo_subfolder: report_repo_folder = f"{report_repo_folder}/{report_repo_subfolder}" api.upload_file( path_or_fileobj=f"ci_results_{job}/{filename}", path_in_repo=f"{report_repo_folder}/ci_results_{job}/{filename}", repo_id=report_repo_id, repo_type="dataset", token=os.getenv("TRANSFORMERS_CI_RESULTS_UPLOAD_TOKEN"), ) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Post process models test reports.") parser.add_argument("--path", "-p", help="Path to the reports folder") parser.add_argument( "--machine-type", "-m", help="Process single or multi GPU results", choices=["single-gpu", "multi-gpu"] ) parser.add_argument("--gpu-name", "-g", help="GPU name", default=None) parser.add_argument("--commit-hash", "-c", help="Commit hash", default=None) parser.add_argument("--job", "-j", help="Optional job name required for uploading reports", default=None) parser.add_argument( "--report-repo-id", "-r", help="Optional report repository ID required for uploading reports", default=None ) args = get_arguments(parser.parse_args()) # Initialize accumulators for collated report total_status_count = { "passed": 0, "failed": 0, "skipped": 0, "error": 0, None: 0, } collated_report_buffer = [] path = args.path machine_type = args.machine_type gpu_name = args.gpu_name commit_hash = args.commit_hash job = args.job report_repo_id = args.report_repo_id # Find the origin directory based on machine type origin = path for p in path.iterdir(): if machine_type in p.name: origin = p break # Loop through model directories and create collated reports for model_dir in sorted(origin.iterdir()): # Create a new entry for the model model_name = model_dir.name.removesuffix("_test_reports") report = {"model": model_name, "results": []} results = [] # Read short summary with open(model_dir / "summary_short.txt", "r") as f: short_summary_lines = f.readlines() # Parse short summary for line in short_summary_lines[1:]: status, count = parse_short_summary_line(line) total_status_count[status] += count if status: result = { "status": status, "test": line.split(status.upper(), maxsplit=1)[1].strip(), "count": count, } results.append(result) # Add short summaries to report report["results"] = results collated_report_buffer.append(report) # Write collated report with open(f"collated_reports_{commit_hash}.json", "w") as f: json.dump( { "gpu_name": gpu_name, "machine_type": machine_type, "commit_hash": commit_hash, "total_status_count": total_status_count, "results": collated_report_buffer, }, f, indent=2, ) if job and report_repo_id: upload_collated_report(job, report_repo_id, f"collated_reports_{commit_hash}.json")
transformers/utils/collated_reports.py/0
{ "file_path": "transformers/utils/collated_reports.py", "repo_id": "transformers", "token_count": 3047 }
587
# 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 importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append(".") r""" The argument `test_file` in this file refers to a model test file. This should be a string of the from `tests/models/*/test_modeling_*.py`. """ def get_module_path(test_file): """Return the module path of a model test file.""" components = test_file.split(os.path.sep) if components[0:2] != ["tests", "models"]: raise ValueError( "`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got " f"{test_file} instead." ) test_fn = components[-1] if not test_fn.endswith("py"): raise ValueError(f"`test_file` should be a python file. Got {test_fn} instead.") if not test_fn.startswith("test_modeling_"): raise ValueError( f"`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead." ) components = components[:-1] + [test_fn.replace(".py", "")] test_module_path = ".".join(components) return test_module_path def get_test_module(test_file): """Get the module of a model test file.""" test_module_path = get_module_path(test_file) try: test_module = importlib.import_module(test_module_path) except AttributeError as exc: # e.g. if you have a `tests` folder in `site-packages`, created by another package, when trying to import # `tests.models...` raise ValueError( f"Could not import module {test_module_path}. Confirm that you don't have a package with the same root " "name installed or in your environment's `site-packages`." ) from exc return test_module def get_tester_classes(test_file): """Get all classes in a model test file whose names ends with `ModelTester`.""" tester_classes = [] test_module = get_test_module(test_file) for attr in dir(test_module): if attr.endswith("ModelTester"): tester_classes.append(getattr(test_module, attr)) # sort with class names return sorted(tester_classes, key=lambda x: x.__name__) def get_test_classes(test_file): """Get all [test] classes in a model test file with attribute `all_model_classes` that are non-empty. These are usually the (model) test classes containing the (non-slow) tests to run and are subclasses of one of the classes `ModelTesterMixin`, `TFModelTesterMixin` or `FlaxModelTesterMixin`, as well as a subclass of `unittest.TestCase`. Exceptions include `RagTestMixin` (and its subclasses). """ test_classes = [] test_module = get_test_module(test_file) for attr in dir(test_module): attr_value = getattr(test_module, attr) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). model_classes = getattr(attr_value, "all_model_classes", []) if len(model_classes) > 0: test_classes.append(attr_value) # sort with class names return sorted(test_classes, key=lambda x: x.__name__) def get_model_classes(test_file): """Get all model classes that appear in `all_model_classes` attributes in a model test file.""" test_classes = get_test_classes(test_file) model_classes = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes) # sort with class names return sorted(model_classes, key=lambda x: x.__name__) def get_model_tester_from_test_class(test_class): """Get the model tester class of a model test class.""" test = test_class() if hasattr(test, "setUp"): test.setUp() model_tester = None if hasattr(test, "model_tester"): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: model_tester = test.model_tester.__class__ return model_tester def get_test_classes_for_model(test_file, model_class): """Get all [test] classes in `test_file` that have `model_class` in their `all_model_classes`.""" test_classes = get_test_classes(test_file) target_test_classes = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(test_class) # sort with class names return sorted(target_test_classes, key=lambda x: x.__name__) def get_tester_classes_for_model(test_file, model_class): """Get all model tester classes in `test_file` that are associated to `model_class`.""" test_classes = get_test_classes_for_model(test_file, model_class) tester_classes = [] for test_class in test_classes: tester_class = get_model_tester_from_test_class(test_class) if tester_class is not None: tester_classes.append(tester_class) # sort with class names return sorted(tester_classes, key=lambda x: x.__name__) def get_test_to_tester_mapping(test_file): """Get a mapping from [test] classes to model tester classes in `test_file`. This uses `get_test_classes` which may return classes that are NOT subclasses of `unittest.TestCase`. """ test_classes = get_test_classes(test_file) test_tester_mapping = {test_class: get_model_tester_from_test_class(test_class) for test_class in test_classes} return test_tester_mapping def get_model_to_test_mapping(test_file): """Get a mapping from model classes to test classes in `test_file`.""" model_classes = get_model_classes(test_file) model_test_mapping = { model_class: get_test_classes_for_model(test_file, model_class) for model_class in model_classes } return model_test_mapping def get_model_to_tester_mapping(test_file): """Get a mapping from model classes to model tester classes in `test_file`.""" model_classes = get_model_classes(test_file) model_to_tester_mapping = { model_class: get_tester_classes_for_model(test_file, model_class) for model_class in model_classes } return model_to_tester_mapping def to_json(o): """Make the information succinct and easy to read. Avoid the full class representation like `<class 'transformers.models.bert.modeling_bert.BertForMaskedLM'>` when displaying the results. Instead, we use class name (`BertForMaskedLM`) for the readability. """ if isinstance(o, str): return o elif isinstance(o, type): return o.__name__ elif isinstance(o, (list, tuple)): return [to_json(x) for x in o] elif isinstance(o, dict): return {to_json(k): to_json(v) for k, v in o.items()} else: return o
transformers/utils/get_test_info.py/0
{ "file_path": "transformers/utils/get_test_info.py", "repo_id": "transformers", "token_count": 2737 }
588
"""A simple script to set flexibly CUDA_VISIBLE_DEVICES in GitHub Actions CI workflow files.""" import argparse import os if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--test_folder", type=str, default=None, help="The test folder name of the model being tested. For example, `models/cohere`.", ) args = parser.parse_args() # `test_eager_matches_sdpa_generate` for `cohere` needs a lot of GPU memory! # This depends on the runners. At this moment we are targeting our AWS CI runners. if args.test_folder == "models/cohere": cuda_visible_devices = "0,1,2,3" elif "CUDA_VISIBLE_DEVICES" in os.environ: cuda_visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES") else: cuda_visible_devices = "0" print(cuda_visible_devices)
transformers/utils/set_cuda_devices_for_ci.py/0
{ "file_path": "transformers/utils/set_cuda_devices_for_ci.py", "repo_id": "transformers", "token_count": 338 }
589
{ "opsets": { "1": [ "Abs", "Add", "AddV2", "ArgMax", "ArgMin", "AvgPool", "AvgPool3D", "BatchMatMul", "BatchMatMulV2", "BatchToSpaceND", "BiasAdd", "BiasAddV1", "Cast", "Ceil", "CheckNumerics", "ComplexAbs", "Concat", "ConcatV2", "Const", "ConstV2", "Conv1D", "Conv2D", "Conv2DBackpropInput", "Conv3D", "Conv3DBackpropInputV2", "DepthToSpace", "DepthwiseConv2d", "DepthwiseConv2dNative", "Div", "Dropout", "Elu", "Equal", "Erf", "Exp", "ExpandDims", "Flatten", "Floor", "Gather", "GatherNd", "GatherV2", "Greater", "Identity", "IdentityN", "If", "LRN", "LSTMBlockCell", "LeakyRelu", "Less", "Log", "LogSoftmax", "LogicalAnd", "LogicalNot", "LogicalOr", "LookupTableSizeV2", "MatMul", "Max", "MaxPool", "MaxPool3D", "MaxPoolV2", "Maximum", "Mean", "Min", "Minimum", "MirrorPad", "Mul", "Neg", "NoOp", "NotEqual", "OneHot", "Pack", "Pad", "PadV2", "Placeholder", "PlaceholderV2", "PlaceholderWithDefault", "Pow", "Prod", "RFFT", "RandomNormal", "RandomNormalLike", "RandomUniform", "RandomUniformLike", "RealDiv", "Reciprocal", "Relu", "Relu6", "Reshape", "Rsqrt", "Selu", "Shape", "Sigmoid", "Sign", "Size", "Slice", "Softmax", "Softplus", "Softsign", "SpaceToBatchND", "SpaceToDepth", "Split", "SplitV", "Sqrt", "Square", "SquaredDifference", "Squeeze", "StatelessIf", "StopGradient", "StridedSlice", "StringJoin", "Sub", "Sum", "Tanh", "Tile", "TopKV2", "Transpose", "TruncateDiv", "Unpack", "ZerosLike" ], "2": [], "3": [], "4": [], "5": [], "6": [ "AddN", "All", "Any", "FloorDiv", "FusedBatchNorm", "FusedBatchNormV2", "FusedBatchNormV3" ], "7": [ "Acos", "Asin", "Atan", "Cos", "Fill", "FloorMod", "GreaterEqual", "LessEqual", "Loop", "MatrixBandPart", "Multinomial", "Range", "ResizeBilinear", "ResizeNearestNeighbor", "Scan", "Select", "SelectV2", "Sin", "SoftmaxCrossEntropyWithLogits", "SparseSoftmaxCrossEntropyWithLogits", "StatelessWhile", "Tan", "TensorListFromTensor", "TensorListGetItem", "TensorListLength", "TensorListReserve", "TensorListResize", "TensorListSetItem", "TensorListStack", "While" ], "8": [ "BroadcastTo", "ClipByValue", "FIFOQueueV2", "HashTableV2", "IteratorGetNext", "IteratorV2", "LookupTableFindV2", "MaxPoolWithArgmax", "QueueDequeueManyV2", "QueueDequeueUpToV2", "QueueDequeueV2", "ReverseSequence" ], "9": [ "SegmentMax", "SegmentMean", "SegmentMin", "SegmentProd", "SegmentSum", "Sinh", "SparseSegmentMean", "SparseSegmentMeanWithNumSegments", "SparseSegmentSqrtN", "SparseSegmentSqrtNWithNumSegments", "SparseSegmentSum", "SparseSegmentSumWithNumSegments", "UnsortedSegmentMax", "UnsortedSegmentMin", "UnsortedSegmentProd", "UnsortedSegmentSum", "Where" ], "10": [ "CropAndResize", "CudnnRNN", "DynamicStitch", "FakeQuantWithMinMaxArgs", "IsFinite", "IsInf", "NonMaxSuppressionV2", "NonMaxSuppressionV3", "NonMaxSuppressionV4", "NonMaxSuppressionV5", "ParallelDynamicStitch", "ReverseV2", "Roll" ], "11": [ "Bincount", "Cumsum", "InvertPermutation", "LeftShift", "MatrixDeterminant", "MatrixDiagPart", "MatrixDiagPartV2", "MatrixDiagPartV3", "RaggedRange", "RightShift", "Round", "ScatterNd", "SparseFillEmptyRows", "SparseReshape", "SparseToDense", "TensorScatterUpdate", "Unique" ], "12": [ "Einsum", "MatrixDiag", "MatrixDiagV2", "MatrixDiagV3", "MatrixSetDiagV3", "SquaredDistance" ], "13": [] } }
transformers/utils/tf_ops/onnx.json/0
{ "file_path": "transformers/utils/tf_ops/onnx.json", "repo_id": "transformers", "token_count": 4081 }
590
# Best of N sampling: Alternative ways to get better model output without RL based fine-tuning Within the extras module is the `best-of-n` sampler class that serves as an alternative method of generating better model output. As to how it fares against the RL based fine-tuning, please look in the `examples` directory for a comparison example ## Usage To get started quickly, instantiate an instance of the class with a model, a length sampler, a tokenizer and a callable that serves as a proxy reward pipeline that outputs reward scores for input queries ```python from transformers import pipeline, AutoTokenizer from trl import AutoModelForCausalLMWithValueHead from trl.core import LengthSampler from trl.extras import BestOfNSampler ref_model = AutoModelForCausalLMWithValueHead.from_pretrained(ref_model_name) reward_pipe = pipeline("sentiment-analysis", model=reward_model, device=device) tokenizer = AutoTokenizer.from_pretrained(ref_model_name) tokenizer.pad_token = tokenizer.eos_token # callable that takes a list of raw text and returns a list of corresponding reward scores def queries_to_scores(list_of_strings): return [output["score"] for output in reward_pipe(list_of_strings)] best_of_n = BestOfNSampler(model, tokenizer, queries_to_scores, length_sampler=output_length_sampler) ``` And assuming you have a list/tensor of tokenized queries, you can generate better output by calling the `generate` method ```python best_of_n.generate(query_tensors, device=device, **gen_kwargs) ``` The default sample size is 4, but you can change it at the time of instance initialization like so ```python best_of_n = BestOfNSampler(model, tokenizer, queries_to_scores, length_sampler=output_length_sampler, sample_size=8) ``` The default output is the result of taking the top scored output for each query, but you can change it to top 2 and so on by passing the `n_candidates` argument at the time of instance initialization ```python best_of_n = BestOfNSampler(model, tokenizer, queries_to_scores, length_sampler=output_length_sampler, n_candidates=2) ``` There is the option of setting the generation settings (like `temperature`, `pad_token_id`) at the time of instance creation as opposed to when calling the `generate` method. This is done by passing a `GenerationConfig` from the `transformers` library at the time of initialization ```python from transformers import GenerationConfig generation_config = GenerationConfig(min_length= -1, top_k=0.0, top_p= 1.0, do_sample= True, pad_token_id=tokenizer.eos_token_id) best_of_n = BestOfNSampler(model, tokenizer, queries_to_scores, length_sampler=output_length_sampler, generation_config=generation_config) best_of_n.generate(query_tensors, device=device) ``` Furthermore, at the time of initialization you can set the seed to control the repeatability of the generation process and the number of samples to generate for each query
trl/docs/source/best_of_n.md/0
{ "file_path": "trl/docs/source/best_of_n.md", "repo_id": "trl", "token_count": 841 }
591
# Examples of using peft with trl to finetune 8-bit models with Low Rank Adaption (LoRA) The notebooks and scripts in this examples show how to use Low Rank Adaptation (LoRA) to fine-tune models in a memory efficient manner. Most of PEFT methods supported in peft library but note that some PEFT methods such as Prompt tuning are not supported. For more information on LoRA, see the [original paper](https://huggingface.co/papers/2106.09685). Here's an overview of the `peft`-enabled notebooks and scripts in the [trl repository](https://github.com/huggingface/trl/tree/main/examples): | File | Task | Description | Colab link | |---|---| --- | | [`stack_llama/rl_training.py`](https://github.com/huggingface/trl/blob/main/examples/research_projects/stack_llama/scripts/rl_training.py) | RLHF | Distributed fine-tuning of the 7b parameter LLaMA models with a learned reward model and `peft`. | | | [`stack_llama/reward_modeling.py`](https://github.com/huggingface/trl/blob/main/examples/research_projects/stack_llama/scripts/reward_modeling.py) | Reward Modeling | Distributed training of the 7b parameter LLaMA reward model with `peft`. | | | [`stack_llama/supervised_finetuning.py`](https://github.com/huggingface/trl/blob/main/examples/research_projects/stack_llama/scripts/supervised_finetuning.py) | SFT | Distributed instruction/supervised fine-tuning of the 7b parameter LLaMA model with `peft`. | | ## Installation Note: peft is in active development, so we install directly from their Github page. Peft also relies on the latest version of transformers. ```bash pip install trl[peft] pip install bitsandbytes loralib pip install git+https://github.com/huggingface/transformers.git@main #optional: wandb pip install wandb ``` Note: if you don't want to log with `wandb` remove `log_with="wandb"` in the scripts/notebooks. You can also replace it with your favourite experiment tracker that's [supported by `accelerate`](https://huggingface.co/docs/accelerate/usage_guides/tracking). ## How to use it? Simply declare a `PeftConfig` object in your script and pass it through `.from_pretrained` to load the TRL+PEFT model. ```python from peft import LoraConfig from trl import AutoModelForCausalLMWithValueHead model_id = "edbeeching/gpt-neo-125M-imdb" lora_config = LoraConfig( r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM", ) model = AutoModelForCausalLMWithValueHead.from_pretrained( model_id, peft_config=lora_config, ) ``` And if you want to load your model in 8bit precision: ```python pretrained_model = AutoModelForCausalLMWithValueHead.from_pretrained( config.model_name, load_in_8bit=True, peft_config=lora_config, ) ``` ... or in 4bit precision: ```python pretrained_model = AutoModelForCausalLMWithValueHead.from_pretrained( config.model_name, peft_config=lora_config, load_in_4bit=True, ) ``` ## Launch scripts The `trl` library is powered by `accelerate`. As such it is best to configure and launch trainings with the following commands: ```bash accelerate config # will prompt you to define the training configuration accelerate launch examples/scripts/ppo.py --use_peft # launch`es training ``` ## Using `trl` + `peft` and Data Parallelism You can scale up to as many GPUs as you want, as long as you are able to fit the training process in a single device. The only tweak you need to apply is to load the model as follows: ```python from peft import LoraConfig ... lora_config = LoraConfig( r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM", ) pretrained_model = AutoModelForCausalLMWithValueHead.from_pretrained( config.model_name, peft_config=lora_config, ) ``` And if you want to load your model in 8bit precision: ```python pretrained_model = AutoModelForCausalLMWithValueHead.from_pretrained( config.model_name, peft_config=lora_config, load_in_8bit=True, ) ``` ... or in 4bit precision: ```python pretrained_model = AutoModelForCausalLMWithValueHead.from_pretrained( config.model_name, peft_config=lora_config, load_in_4bit=True, ) ``` Finally, make sure that the rewards are computed on correct device as well, for that you can use `ppo_trainer.model.current_device`. ## Naive pipeline parallelism (NPP) for large models (>60B models) The `trl` library also supports naive pipeline parallelism (NPP) for large models (>60B models). This is a simple way to parallelize the model across multiple GPUs. This paradigm, termed as "Naive Pipeline Parallelism" (NPP) is a simple way to parallelize the model across multiple GPUs. We load the model and the adapters across multiple GPUs and the activations and gradients will be naively communicated across the GPUs. This supports `int8` models as well as other `dtype` models. <div style="text-align: center"> <img src="https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/trl-npp.png"> </div> ### How to use NPP? Simply load your model with a custom `device_map` argument on the `from_pretrained` to split your model across multiple devices. Check out this [nice tutorial](https://github.com/huggingface/blog/blob/main/accelerate-large-models.md) on how to properly create a `device_map` for your model. Also make sure to have the `lm_head` module on the first GPU device as it may throw an error if it is not on the first device. As this time of writing, you need to install the `main` branch of `accelerate`: `pip install git+https://github.com/huggingface/accelerate.git@main` and `peft`: `pip install git+https://github.com/huggingface/peft.git@main`. ### Launch scripts Although `trl` library is powered by `accelerate`, you should run your training script in a single process. Note that we do not support Data Parallelism together with NPP yet. ```bash python PATH_TO_SCRIPT ``` ## Fine-tuning Llama-2 model You can easily fine-tune Llama2 model using `SFTTrainer` and the official script! For example to fine-tune llama2-7b on the Guanaco dataset, run (tested on a single NVIDIA T4-16GB): ```bash python trl/scripts/sft.py --output_dir sft_openassistant-guanaco --model_name meta-llama/Llama-2-7b-hf --dataset_name timdettmers/openassistant-guanaco --load_in_4bit --use_peft --per_device_train_batch_size 4 --gradient_accumulation_steps 2 ```
trl/docs/source/peft_integration.md/0
{ "file_path": "trl/docs/source/peft_integration.md", "repo_id": "trl", "token_count": 2079 }
592
# 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 features, 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/rlaif-v"`): 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/rlaif-v", 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_conversational(example): """ Convert prompt from "xxx" to [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "xxx"}]}] and chosen and rejected from "xxx" to [{"role": "assistant", "content": [{"type": "text", "text": "xxx"}]}]. Images are wrapped into a list. """ prompt = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": example["question"]}]}] chosen = [{"role": "assistant", "content": [{"type": "text", "text": example["chosen"]}]}] rejected = [{"role": "assistant", "content": [{"type": "text", "text": example["rejected"]}]}] return {"prompt": prompt, "images": [example["image"]], "chosen": chosen, "rejected": rejected} model_card = ModelCard(""" --- tags: [trl] --- # RLAIF-V Dataset ## Summary The RLAIF-V dataset is a processed version of the [openbmb/RLAIF-V-Dataset](https://huggingface.co/datasets/openbmb/RLAIF-V-Dataset#dataset-card-for-rlaif-v-dataset), specifically curated to train vision-language models using the [TRL library](https://github.com/huggingface/trl) for preference learning tasks. It contains 83,132 high-quality comparison pairs, each comprising an image and two textual descriptions: one preferred and one rejected. This dataset enables models to learn human preferences in visual contexts, enhancing their ability to generate and evaluate image captions. ## Data Structure - **Format**: [Conversational](https://huggingface.co/docs/trl/main/dataset_formats#conversational) - **Type**: [Preference](https://huggingface.co/docs/trl/main/dataset_formats#preference) Columns: - `"prompt"`: The task related to the image. - `"images"`: The image. - `"chosen"`: The preferred answer. - `"rejected"`: An alternative answer that was not preferred. This structure allows models to learn to prefer the _chosen_ response over the _rejected_ one, thereby aligning with human preferences in visual tasks. ## Generation script The script used to generate this dataset can be found [here](https://github.com/huggingface/trl/blob/main/examples/datasets/rlaif-v.py). """) if __name__ == "__main__": parser = HfArgumentParser(ScriptArguments) script_args = parser.parse_args_into_dataclasses()[0] dataset = load_dataset("openbmb/RLAIF-V-Dataset", split="train") dataset = dataset.map( to_conversational, num_proc=script_args.dataset_num_proc, remove_columns=dataset.column_names, writer_batch_size=128, ) # Cast the images to Sequence[Image] to avoid bytes format f = dataset.features f["images"] = features.Sequence(features.Image(decode=True)) dataset = dataset.cast(f) dataset = dataset.train_test_split(test_size=0.01, writer_batch_size=128) 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/rlaif-v.py/0
{ "file_path": "trl/examples/datasets/rlaif-v.py", "repo_id": "trl", "token_count": 1597 }
593
# 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 peft import PeftConfig, PeftModel from transformers import AutoModelForCausalLM, AutoModelForSequenceClassification, AutoTokenizer, HfArgumentParser @dataclass class ScriptArguments: """ The input names representing the Adapter and Base model fine-tuned with PEFT, and the output name representing the merged model. """ adapter_model_name: Optional[str] = field(default=None, metadata={"help": "the adapter name"}) base_model_name: Optional[str] = field(default=None, metadata={"help": "the base model name"}) output_name: Optional[str] = field(default=None, metadata={"help": "the merged model name"}) parser = HfArgumentParser(ScriptArguments) script_args = parser.parse_args_into_dataclasses()[0] assert script_args.adapter_model_name is not None, "please provide the name of the Adapter you would like to merge" assert script_args.base_model_name is not None, "please provide the name of the Base model" assert script_args.output_name is not None, "please provide the output name of the merged model" peft_config = PeftConfig.from_pretrained(script_args.adapter_model_name) if peft_config.task_type == "SEQ_CLS": # The sequence classification task is used for the reward model in PPO model = AutoModelForSequenceClassification.from_pretrained( script_args.base_model_name, num_labels=1, torch_dtype=torch.bfloat16 ) else: model = AutoModelForCausalLM.from_pretrained( script_args.base_model_name, return_dict=True, torch_dtype=torch.bfloat16 ) tokenizer = AutoTokenizer.from_pretrained(script_args.base_model_name) # Load the PEFT model model = PeftModel.from_pretrained(model, script_args.adapter_model_name) model.eval() model = model.merge_and_unload() model.save_pretrained(f"{script_args.output_name}") tokenizer.save_pretrained(f"{script_args.output_name}") model.push_to_hub(f"{script_args.output_name}", use_temp_dir=False)
trl/examples/research_projects/stack_llama/scripts/merge_peft_adapter.py/0
{ "file_path": "trl/examples/research_projects/stack_llama/scripts/merge_peft_adapter.py", "repo_id": "trl", "token_count": 817 }
594
# 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 shutil from accelerate import PartialState from datasets import load_dataset from transformers import ( AutoModelForCausalLM, AutoModelForSequenceClassification, AutoTokenizer, HfArgumentParser, ) from trl import ModelConfig, RLOOConfig, RLOOTrainer, ScriptArguments from trl.trainer.utils import SIMPLE_CHAT_TEMPLATE """ python examples/scripts/rloo/rloo_tldr.py \ --dataset_name trl-internal-testing/tldr-preference-sft-trl-style \ --dataset_test_split validation \ --learning_rate 3e-6 \ --output_dir models/minimal/ppo \ --per_device_train_batch_size 1 \ --gradient_accumulation_steps 64 \ --total_episodes 30000 \ --model_name_or_path EleutherAI/pythia-1b-deduped \ --sft_model_path cleanrl/EleutherAI_pythia-1b-deduped__sft__tldr \ --reward_model_path cleanrl/EleutherAI_pythia-1b-deduped__reward__tldr \ --missing_eos_penalty 1.0 \ --stop_token eos \ --response_length 53 accelerate launch --config_file examples/accelerate_configs/deepspeed_zero2.yaml \ examples/scripts/rloo/rloo_tldr.py \ --dataset_name trl-internal-testing/tldr-preference-sft-trl-style \ --dataset_test_split validation \ --output_dir models/minimal/rloo_tldr \ --num_ppo_epochs 1 \ --num_mini_batches 1 \ --learning_rate 3e-6 \ --per_device_train_batch_size 16 \ --gradient_accumulation_steps 4 \ --total_episodes 1000000 \ --model_name_or_path EleutherAI/pythia-1b-deduped \ --sft_model_path cleanrl/EleutherAI_pythia-1b-deduped__sft__tldr \ --reward_model_path cleanrl/EleutherAI_pythia-1b-deduped__reward__tldr \ --local_rollout_forward_batch_size 16 \ --missing_eos_penalty 1.0 \ --stop_token eos """ if __name__ == "__main__": parser = HfArgumentParser((ScriptArguments, RLOOConfig, ModelConfig)) script_args, training_args, model_args = parser.parse_args_into_dataclasses() # remove output_dir if exists shutil.rmtree(training_args.output_dir, ignore_errors=True) ################ # Model & Tokenizer ################ tokenizer = AutoTokenizer.from_pretrained( model_args.model_name_or_path, padding_side="left", trust_remote_code=model_args.trust_remote_code ) tokenizer.add_special_tokens({"pad_token": "[PAD]"}) if tokenizer.chat_template is None: tokenizer.chat_template = SIMPLE_CHAT_TEMPLATE reward_model = AutoModelForSequenceClassification.from_pretrained( training_args.reward_model_path, trust_remote_code=model_args.trust_remote_code, num_labels=1 ) ref_policy = AutoModelForCausalLM.from_pretrained( training_args.sft_model_path, trust_remote_code=model_args.trust_remote_code ) policy = AutoModelForCausalLM.from_pretrained( training_args.sft_model_path, trust_remote_code=model_args.trust_remote_code ) ################ # Dataset ################ dataset = load_dataset(script_args.dataset_name, name=script_args.dataset_config) train_dataset = dataset[script_args.dataset_train_split] eval_dataset = dataset[script_args.dataset_test_split] if training_args.eval_strategy != "no" else None def prepare_dataset(dataset, tokenizer): """pre-tokenize the dataset before training; only collate during training""" def tokenize(element): input_ids = tokenizer.apply_chat_template( element["messages"][:1], padding=False, add_generation_prompt=True, ) return {"input_ids": input_ids, "lengths": len(input_ids)} return dataset.map( tokenize, remove_columns=dataset.column_names, num_proc=training_args.dataset_num_proc, ) # Compute that only on the main process for faster data processing. # see: https://github.com/huggingface/trl/pull/1255 with PartialState().local_main_process_first(): train_dataset = prepare_dataset(train_dataset, tokenizer) eval_dataset = prepare_dataset(eval_dataset, tokenizer) # filtering train_dataset = train_dataset.filter(lambda x: x["lengths"] <= 512, num_proc=training_args.dataset_num_proc) eval_dataset = eval_dataset.filter(lambda x: x["lengths"] <= 512, num_proc=training_args.dataset_num_proc) assert train_dataset[0]["input_ids"][-1] != tokenizer.eos_token_id, "The last token should not be an EOS token" ################ # Training ################ trainer = RLOOTrainer( config=training_args, processing_class=tokenizer, policy=policy, ref_policy=ref_policy, reward_model=reward_model, train_dataset=train_dataset, eval_dataset=eval_dataset, ) trainer.train() # Save and push to hub trainer.save_model(training_args.output_dir) if training_args.push_to_hub: trainer.push_to_hub(dataset_name=script_args.dataset_name) trainer.generate_completions()
trl/examples/scripts/rloo/rloo_tldr.py/0
{ "file_path": "trl/examples/scripts/rloo/rloo_tldr.py", "repo_id": "trl", "token_count": 2280 }
595
# 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 import numpy as np from datasets import Dataset, Features, Image, List, Value from transformers import HfArgumentParser Message = List({"content": List({"text": Value("string"), "type": Value("string")}), "role": Value("string")}) @dataclass class ScriptArguments: r""" Arguments for the script. Args: test_size (`float`, *optional*, defaults to `0.1`): Fraction of the dataset to include in the test split. push_to_hub (`bool`, *optional*, defaults to `False`): Whether to push the dataset to the Hugging Face Hub. repo_id (`str`, *optional*, defaults to `"trl-internal-testing/zen-multi-image"`): Hugging Face repository ID to push the dataset to. """ test_size: float = field( default=0.1, metadata={"help": "Fraction of the dataset to include in the test split."}, ) push_to_hub: bool = field( default=False, metadata={"help": "Whether to push the dataset to the Hugging Face Hub."}, ) repo_id: str = field( default="trl-internal-testing/zen-multi-image", metadata={"help": "Hugging Face repository ID to push the dataset to."}, ) def main(test_size, push_to_hub, repo_id): # fmt: off messages = [ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is better than ugly?"}]}, {"role": "assistant", "content": [{"type": "text", "text": "Beautiful."}]}], [{"role": "user", "content": [{"type": "text", "text": "What is better than implicit?"}, {"type": "image"}]}, {"role": "assistant", "content": [{"type": "text", "text": "Explicit."}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is better than complex?"}, {"type": "image"}]}, {"role": "assistant", "content": [{"type": "text", "text": "Simple."}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "image"}, {"type": "text", "text": "What is better than complicated?"}]}, {"role": "assistant", "content": [{"type": "text", "text": "Complex."}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is better than nested?"}]}, {"role": "assistant", "content": [{"type": "text", "text": "Flat."}]}], [{"role": "user", "content": [{"type": "text", "text": "What is better than dense?"}, {"type": "image"}]}, {"role": "assistant", "content": [{"type": "text", "text": "Sparse."}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What counts?"}, {"type": "image"}]}, {"role": "assistant", "content": [{"type": "text", "text": "Readability."}]}], [{"role": "user", "content": [{"type": "text", "text": "Are special cases enough to break the rules?"}]}, {"role": "assistant", "content": [{"type": "text", "text": "No, special cases aren't special enough to break the rules."}]}], [{"role": "user", "content": [{"type": "text", "text": "What beats purity?"}, {"type": "image"}, {"type": "image"}]}, {"role": "assistant", "content": [{"type": "text", "text": "Practicality."}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "image"}, {"type": "text", "text": "What should never pass silently?"}, {"type": "image"}]}, {"role": "assistant", "content": [{"type": "text", "text": "Errors."}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "When can errors pass silently?"}]}, {"role": "assistant", "content": [{"type": "text", "text": "When explicitly silenced."}]}], [{"role": "user", "content": [{"type": "text", "text": "What should you do in the face of ambiguity?"}, {"type": "image"}]}, {"role": "assistant", "content": [{"type": "text", "text": "Refuse the temptation to guess."}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "How many ways should there be to do it?"}, {"type": "image"}, {"type": "image"}]}, {"role": "assistant", "content": [{"type": "text", "text": "One, and preferably only one."}]}], [{"role": "user", "content": [{"type": "text", "text": "For whom may the way not be obvious at first?"}]}, {"role": "assistant", "content": [{"type": "text", "text": "Dutch."}]}], [{"role": "user", "content": [{"type": "text", "text": "What is better than never?"}, {"type": "image"}]}, {"role": "assistant", "content": [{"type": "text", "text": "Now is better than never."}]}], [{"role": "user", "content": [{"type": "text", "text": "Is"}, {"type": "image"}, {"type": "text", "text": " never better than *right* now?"}]}, {"role": "assistant", "content": [{"type": "text", "text": "Yes, often."}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What does it mean if the implementation is hard to explain?"}]}, {"role": "assistant", "content": [{"type": "text", "text": "It means it's a bad idea."}]}], [{"role": "user", "content": [{"type": "text", "text": "What does it mean if the implementation is easy to explain?"}, {"type": "image"}]}, {"role": "assistant", "content": [{"type": "text", "text": "It means it may be a good idea."}]}], [{"role": "user", "content": [{"type": "text", "text": "Any great ideas?"}]}, {"role": "assistant", "content": [{"type": "text", "text": "Namespaces are one honking great idea."}]}], ] # Create the images number_of_images = [sum(1 for part in row[0]["content"] if part.get("type") == "image") for row in messages] sizes = [np.random.randint(32, 64, size=(num_images, 2)) for num_images in number_of_images] images = [[np.random.uniform(low=0.0, high=255.0, size=(h, w, 3)).astype(np.uint8) for h, w in s] for s in sizes] conversational_language_modeling_dataset = Dataset.from_dict({"messages": messages, "images": images}, features=Features(messages=Message, images=List(Image()))) conversational_language_modeling_dataset = conversational_language_modeling_dataset.train_test_split(test_size=test_size, shuffle=False) if push_to_hub: conversational_language_modeling_dataset.push_to_hub(repo_id, config_name="conversational_language_modeling") prompt = [ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is better than ugly?"}]}], [{"role": "user", "content": [{"type": "text", "text": "What is better than implicit?"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is better than complex?"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "image"}, {"type": "text", "text": "What is better than complicated?"}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is better than nested?"}]}], [{"role": "user", "content": [{"type": "text", "text": "What is better than dense?"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What counts?"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "text", "text": "Are special cases enough to break the rules?"}]}], [{"role": "user", "content": [{"type": "text", "text": "What beats purity?"}, {"type": "image"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "image"}, {"type": "text", "text": "What should never pass silently?"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "When can errors pass silently?"}]}], [{"role": "user", "content": [{"type": "text", "text": "What should you do in the face of ambiguity?"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "How many ways should there be to do it?"}, {"type": "image"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "text", "text": "For whom may the way not be obvious at first?"}]}], [{"role": "user", "content": [{"type": "text", "text": "What is better than never?"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "text", "text": "Is"}, {"type": "image"}, {"type": "text", "text": " never better than *right* now?"}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What does it mean if the implementation is hard to explain?"}]}], [{"role": "user", "content": [{"type": "text", "text": "What does it mean if the implementation is easy to explain?"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "text", "text": "Any great ideas?"}]}], ] # Create the images number_of_images = [sum(1 for part in row[0]["content"] if part.get("type") == "image") for row in prompt] sizes = [np.random.randint(32, 64, size=(num_images, 2)) for num_images in number_of_images] images = [[np.random.uniform(low=0.0, high=255.0, size=(h, w, 3)).astype(np.uint8) for h, w in s] for s in sizes] conversational_prompt_only_dataset = Dataset.from_dict({"prompt": prompt, "images": images}, features=Features(prompt=Message, images=List(Image()))) conversational_prompt_only_dataset = conversational_prompt_only_dataset.train_test_split(test_size=test_size, shuffle=False) if push_to_hub: conversational_prompt_only_dataset.push_to_hub(repo_id, config_name="conversational_prompt_only") prompt = [ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is better than ugly?"}]}], [{"role": "user", "content": [{"type": "text", "text": "What is better than implicit?"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is better than complex?"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "image"}, {"type": "text", "text": "What is better than complicated?"}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is better than nested?"}]}], [{"role": "user", "content": [{"type": "text", "text": "What is better than dense?"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What counts?"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "text", "text": "Are special cases enough to break the rules?"}]}], [{"role": "user", "content": [{"type": "text", "text": "What beats purity?"}, {"type": "image"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "image"}, {"type": "text", "text": "What should never pass silently?"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "When can errors pass silently?"}]}], [{"role": "user", "content": [{"type": "text", "text": "What should you do in the face of ambiguity?"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "How many ways should there be to do it?"}, {"type": "image"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "text", "text": "For whom may the way not be obvious at first?"}]}], [{"role": "user", "content": [{"type": "text", "text": "What is better than never?"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "text", "text": "Is"}, {"type": "image"}, {"type": "text", "text": " never better than *right* now?"}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What does it mean if the implementation is hard to explain?"}]}], [{"role": "user", "content": [{"type": "text", "text": "What does it mean if the implementation is easy to explain?"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "text", "text": "Any great ideas?"}]}], ] completion = [ [{"role": "assistant", "content": [{"type": "text", "text": "Beautiful."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Explicit."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Simple."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Complex."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Flat."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Sparse."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Readability."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "No, special cases aren't special enough to break the rules."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Practicality."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Errors."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "When explicitly silenced."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Refuse the temptation to guess."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "One, and preferably only one."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Dutch."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Now is better than never."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Yes, often."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "It means it's a bad idea."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "It means it may be a good idea."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Namespaces are one honking great idea."}]}], ] # Create the images number_of_images = [sum(1 for part in row[0]["content"] if part.get("type") == "image") for row in prompt] sizes = [np.random.randint(32, 64, size=(num_images, 2)) for num_images in number_of_images] images = [[np.random.uniform(low=0.0, high=255.0, size=(h, w, 3)).astype(np.uint8) for h, w in s] for s in sizes] conversational_prompt_completion_dataset = Dataset.from_dict({"prompt": prompt, "completion": completion, "images": images}, features=Features(prompt=Message, completion=Message, images=List(Image()))) conversational_prompt_completion_dataset = conversational_prompt_completion_dataset.train_test_split(test_size=test_size, shuffle=False) if push_to_hub: conversational_prompt_completion_dataset.push_to_hub(repo_id, config_name="conversational_prompt_completion") prompt = [ [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is better than ugly?"}]}], [{"role": "user", "content": [{"type": "text", "text": "What is better than implicit?"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is better than complex?"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "image"}, {"type": "text", "text": "What is better than complicated?"}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What is better than nested?"}]}], [{"role": "user", "content": [{"type": "text", "text": "What is better than dense?"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What counts?"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "text", "text": "Are special cases enough to break the rules?"}]}], [{"role": "user", "content": [{"type": "text", "text": "What beats purity?"}, {"type": "image"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "image"}, {"type": "text", "text": "What should never pass silently?"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "When can errors pass silently?"}]}], [{"role": "user", "content": [{"type": "text", "text": "What should you do in the face of ambiguity?"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "How many ways should there be to do it?"}, {"type": "image"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "text", "text": "For whom may the way not be obvious at first?"}]}], [{"role": "user", "content": [{"type": "text", "text": "What is better than never?"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "text", "text": "Is"}, {"type": "image"}, {"type": "text", "text": " never better than *right* now?"}]}], [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "What does it mean if the implementation is hard to explain?"}]}], [{"role": "user", "content": [{"type": "text", "text": "What does it mean if the implementation is easy to explain?"}, {"type": "image"}]}], [{"role": "user", "content": [{"type": "text", "text": "Any great ideas?"}]}], ] chosen = [ [{"role": "assistant", "content": [{"type": "text", "text": "Beautiful."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Explicit."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Simple."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Complex."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Flat."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Sparse."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Readability."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "No, special cases aren't special enough to break the rules."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Practicality."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Errors."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "When explicitly silenced."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Refuse the temptation to guess."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "One, and preferably only one."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Dutch."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Now is better than never."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Yes, often."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "It means it's a bad idea."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "It means it may be a good idea."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Namespaces are one honking great idea."}]}], ] rejected = [ [{"role": "assistant", "content": [{"type": "text", "text": "Acceptable."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Explained."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Very complex."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Very complicated."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Circular."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Heavy."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Looking complicated."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Yes, special cases are special enough to break the rules."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Nothing."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Warnings."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Never."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Give up."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "As many as possible."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "French."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Some day."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "No, never."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "It means it's a good idea."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "It means it's a bad idea."}]}], [{"role": "assistant", "content": [{"type": "text", "text": "Recursion."}]}], ], # Create the images number_of_images = [sum(1 for part in row[0]["content"] if part.get("type") == "image") for row in prompt] sizes = [np.random.randint(32, 64, size=(num_images, 2)) for num_images in number_of_images] images = [[np.random.uniform(low=0.0, high=255.0, size=(h, w, 3)).astype(np.uint8) for h, w in s] for s in sizes] conversational_preference_dataset = Dataset.from_dict({"prompt": prompt, "chosen": chosen, "rejected": rejected, "images": images}, features=Features(prompt=Message, chosen=Message, rejected=Message, images=List(Image()))) conversational_preference_dataset = conversational_preference_dataset.train_test_split(test_size=test_size, shuffle=False) if push_to_hub: conversational_preference_dataset.push_to_hub(repo_id, config_name="conversational_preference") # fmt: on if __name__ == "__main__": parser = HfArgumentParser(ScriptArguments) script_args = parser.parse_args_into_dataclasses()[0] main(script_args.test_size, script_args.push_to_hub, script_args.repo_id)
trl/scripts/generate_zen_multi_image_dataset.py/0
{ "file_path": "trl/scripts/generate_zen_multi_image_dataset.py", "repo_id": "trl", "token_count": 8319 }
596
# 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 json import os from unittest.mock import call, patch from datasets import load_dataset from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig, Trainer, TrainingArguments from transformers.testing_utils import require_peft, require_wandb from transformers.trainer_utils import get_last_checkpoint from transformers.utils import is_peft_available from tests.testing_utils import require_comet, require_mergekit from trl import ( BasePairwiseJudge, BEMACallback, DPOConfig, DPOTrainer, LogCompletionsCallback, MergeModelCallback, WinRateCallback, ) from trl.mergekit_utils import MergeConfig from .testing_utils import TrlTestCase if is_peft_available(): from peft import LoraConfig class HalfPairwiseJudge(BasePairwiseJudge): """Naive pairwise judge that always returns [1, 0] for two prompts""" def judge(self, prompts, completions, shuffle_order=True, return_scores=False): # just check that the batch size is 2 assert len(prompts) == 2 if return_scores: return [0.3, 0.9] return [1, 0] class TrainerWithRefModel(Trainer): # This is a dummy class to test the callback. Compared to the Trainer class, it only has an additional # ref_model attribute def __init__(self, model, ref_model, args, train_dataset, eval_dataset, processing_class): super().__init__( model=model, args=args, train_dataset=train_dataset, eval_dataset=eval_dataset, processing_class=processing_class, ) self.ref_model = ref_model class WinRateCallbackTester(TrlTestCase): def setUp(self): super().setUp() self.model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5") self.ref_model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5") self.tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5") self.tokenizer.pad_token = self.tokenizer.eos_token dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only") dataset["train"] = dataset["train"].select(range(8)) self.expected_winrates = [ {"eval_win_rate": 0.5, "epoch": 0.0, "step": 0}, {"eval_win_rate": 0.5, "epoch": 0.5, "step": 2}, {"eval_win_rate": 0.5, "epoch": 1.0, "step": 4}, {"eval_win_rate": 0.5, "epoch": 1.5, "step": 6}, {"eval_win_rate": 0.5, "epoch": 2.0, "step": 8}, {"eval_win_rate": 0.5, "epoch": 2.5, "step": 10}, {"eval_win_rate": 0.5, "epoch": 3.0, "step": 12}, ] def tokenize_function(examples): out = self.tokenizer(examples["prompt"], padding="max_length", max_length=16, truncation=True) out["labels"] = out["input_ids"].copy() return out self.dataset = dataset.map(tokenize_function, batched=True) self.generation_config = GenerationConfig(max_length=32) self.judge = HalfPairwiseJudge() def test_basic(self): training_args = TrainingArguments( output_dir=self.tmp_dir, eval_strategy="steps", eval_steps=2, # evaluate every 2 steps per_device_train_batch_size=2, # 8 samples in total so 4 batches of 2 per epoch per_device_eval_batch_size=2, report_to="none", ) trainer = TrainerWithRefModel( model=self.model, ref_model=self.ref_model, args=training_args, train_dataset=self.dataset["train"], eval_dataset=self.dataset["test"], processing_class=self.tokenizer, ) win_rate_callback = WinRateCallback( judge=self.judge, trainer=trainer, generation_config=self.generation_config ) trainer.add_callback(win_rate_callback) trainer.train() winrate_history = [h for h in trainer.state.log_history if "eval_win_rate" in h] self.assertListEqual(winrate_history, self.expected_winrates) def test_without_ref_model(self): # Same as before, but without the ref_model attribute. It should use the model attribute instead training_args = TrainingArguments( output_dir=self.tmp_dir, eval_strategy="steps", eval_steps=2, # evaluate every 2 steps per_device_train_batch_size=2, # 8 samples in total so 4 batches of 2 per epoch per_device_eval_batch_size=2, report_to="none", ) trainer = Trainer( model=self.model, args=training_args, train_dataset=self.dataset["train"], eval_dataset=self.dataset["test"], processing_class=self.tokenizer, ) win_rate_callback = WinRateCallback( judge=self.judge, trainer=trainer, generation_config=self.generation_config ) trainer.add_callback(win_rate_callback) trainer.train() winrate_history = [h for h in trainer.state.log_history if "eval_win_rate" in h] self.assertListEqual(winrate_history, self.expected_winrates) def test_soft_judge(self): """Test that the soft judge functionality works correctly""" training_args = TrainingArguments( output_dir=self.tmp_dir, eval_strategy="steps", eval_steps=2, # evaluate every 2 steps per_device_train_batch_size=2, # 8 samples in total so 4 batches of 2 per epoch per_device_eval_batch_size=2, report_to="none", ) trainer = TrainerWithRefModel( model=self.model, ref_model=self.ref_model, args=training_args, train_dataset=self.dataset["train"], eval_dataset=self.dataset["test"], processing_class=self.tokenizer, ) win_rate_callback = WinRateCallback( judge=self.judge, trainer=trainer, generation_config=self.generation_config, use_soft_judge=True ) trainer.add_callback(win_rate_callback) trainer.train() # Expected values based on judge returning [0.3, 0.9] for each pair expected_soft_winrates = [ {"eval_avg_win_prob": 0.4, "eval_win_rate": 0.5, "epoch": 0.0, "step": 0}, {"eval_avg_win_prob": 0.4, "eval_win_rate": 0.5, "epoch": 0.5, "step": 2}, {"eval_avg_win_prob": 0.4, "eval_win_rate": 0.5, "epoch": 1.0, "step": 4}, {"eval_avg_win_prob": 0.4, "eval_win_rate": 0.5, "epoch": 1.5, "step": 6}, {"eval_avg_win_prob": 0.4, "eval_win_rate": 0.5, "epoch": 2.0, "step": 8}, {"eval_avg_win_prob": 0.4, "eval_win_rate": 0.5, "epoch": 2.5, "step": 10}, {"eval_avg_win_prob": 0.4, "eval_win_rate": 0.5, "epoch": 3.0, "step": 12}, ] winrate_history = [ {k: h[k] for k in ["eval_avg_win_prob", "eval_win_rate", "epoch", "step"]} for h in trainer.state.log_history if "eval_avg_win_prob" in h ] self.assertListEqual(winrate_history, expected_soft_winrates) @require_peft def test_lora(self): peft_config = LoraConfig( r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM", ) self.model.add_adapter(peft_config) training_args = TrainingArguments( output_dir=self.tmp_dir, eval_strategy="steps", eval_steps=2, # evaluate every 2 steps per_device_train_batch_size=2, # 8 samples in total so 4 batches of 2 per epoch per_device_eval_batch_size=2, report_to="none", ) trainer = Trainer( model=self.model, args=training_args, train_dataset=self.dataset["train"], eval_dataset=self.dataset["test"], processing_class=self.tokenizer, ) win_rate_callback = WinRateCallback( judge=self.judge, trainer=trainer, generation_config=self.generation_config ) trainer.add_callback(win_rate_callback) trainer.train() winrate_history = [h for h in trainer.state.log_history if "eval_win_rate" in h] self.assertListEqual(winrate_history, self.expected_winrates) class LogCompletionsCallbackTester(TrlTestCase): def setUp(self): super().setUp() self.model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5") self.tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5") self.tokenizer.pad_token = self.tokenizer.eos_token dataset = load_dataset("trl-internal-testing/zen", "standard_prompt_only") dataset["train"] = dataset["train"].select(range(8)) def tokenize_function(examples): out = self.tokenizer(examples["prompt"], padding="max_length", max_length=16, truncation=True) out["labels"] = out["input_ids"].copy() return out self.dataset = dataset.map(tokenize_function, batched=True) self.generation_config = GenerationConfig(max_length=32) @require_wandb def test_basic_wandb(self): import wandb training_args = TrainingArguments( output_dir=self.tmp_dir, eval_strategy="steps", eval_steps=2, # evaluate every 2 steps per_device_train_batch_size=2, # 8 samples in total so 4 batches of 2 per epoch per_device_eval_batch_size=2, report_to="wandb", ) trainer = Trainer( model=self.model, args=training_args, train_dataset=self.dataset["train"], eval_dataset=self.dataset["test"], processing_class=self.tokenizer, ) completions_callback = LogCompletionsCallback(trainer, self.generation_config, num_prompts=2) trainer.add_callback(completions_callback) trainer.train() # Get the current run completions_path = wandb.run.summary.completions["path"] json_path = os.path.join(wandb.run.dir, completions_path) with open(json_path) as f: completions = json.load(f) # Check that the columns are correct self.assertIn("step", completions["columns"]) self.assertIn("prompt", completions["columns"]) self.assertIn("completion", completions["columns"]) # Check that the prompt is in the log self.assertIn(self.dataset["test"][0]["prompt"], completions["data"][0]) @require_comet def test_basic_comet(self): import comet_ml training_args = TrainingArguments( output_dir=self.tmp_dir, eval_strategy="steps", eval_steps=2, # evaluate every 2 steps per_device_train_batch_size=2, # 8 samples in total so 4 batches of 2 per epoch per_device_eval_batch_size=2, report_to="comet_ml", ) trainer = Trainer( model=self.model, args=training_args, train_dataset=self.dataset["train"], eval_dataset=self.dataset["test"], processing_class=self.tokenizer, ) completions_callback = LogCompletionsCallback(trainer, self.generation_config, num_prompts=2) trainer.add_callback(completions_callback) trainer.train() # close experiment to make sure all pending data are flushed experiment = comet_ml.get_running_experiment() assert experiment is not None experiment.end() # get experiment assets and check that all required tables was logged steps = len(self.dataset["train"]) + len(self.dataset["test"]) tables_logged = int(steps / 2) + 1 # +1 to include zero step api_experiment = comet_ml.APIExperiment(previous_experiment=experiment.id) tables = api_experiment.get_asset_list("dataframe") assert tables is not None assert len(tables) == tables_logged assert all(table["fileName"] == "completions.csv" for table in tables) @require_mergekit class MergeModelCallbackTester(TrlTestCase): def setUp(self): super().setUp() self.model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5") self.tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5") self.dataset = load_dataset("trl-internal-testing/zen", "standard_preference", split="train") def test_callback(self): training_args = DPOConfig( output_dir=self.tmp_dir, num_train_epochs=1, report_to="none", save_strategy="steps", save_steps=1, ) config = MergeConfig() merge_callback = MergeModelCallback(config) trainer = DPOTrainer( model=self.model, args=training_args, train_dataset=self.dataset, processing_class=self.tokenizer, callbacks=[merge_callback], ) trainer.train() last_checkpoint = get_last_checkpoint(self.tmp_dir) merged_path = os.path.join(last_checkpoint, "merged") self.assertTrue(os.path.isdir(merged_path), "Merged folder does not exist in the last checkpoint.") def test_every_checkpoint(self): training_args = DPOConfig( output_dir=self.tmp_dir, num_train_epochs=1, report_to="none", save_strategy="steps", save_steps=1, ) config = MergeConfig() merge_callback = MergeModelCallback(config, merge_at_every_checkpoint=True) trainer = DPOTrainer( model=self.model, args=training_args, train_dataset=self.dataset, processing_class=self.tokenizer, callbacks=[merge_callback], ) trainer.train() checkpoints = sorted( [os.path.join(self.tmp_dir, cp) for cp in os.listdir(self.tmp_dir) if cp.startswith("checkpoint-")] ) for checkpoint in checkpoints: merged_path = os.path.join(checkpoint, "merged") self.assertTrue(os.path.isdir(merged_path), f"Merged folder does not exist in checkpoint {checkpoint}.") class BEMACallbackTester(TrlTestCase): def setUp(self): super().setUp() self.model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5") self.tokenizer = AutoTokenizer.from_pretrained("trl-internal-testing/tiny-Qwen2ForCausalLM-2.5") self.tokenizer.pad_token = self.tokenizer.eos_token dataset = load_dataset("trl-internal-testing/zen", "standard_language_modeling") def tokenize_function(examples, tokenizer): out = tokenizer(examples["text"], padding="max_length", max_length=17) out["labels"] = out["input_ids"].copy() return out self.dataset = dataset.map( tokenize_function, fn_kwargs={"tokenizer": self.tokenizer}, remove_columns=["text"], batched=True ) def test_model_saved(self): """Test that BEMACallback saves the BEMA model.""" training_args = TrainingArguments(output_dir=self.tmp_dir, report_to="none") bema_callback = BEMACallback(update_freq=2) trainer = Trainer( model=self.model, args=training_args, train_dataset=self.dataset["train"], processing_class=self.tokenizer, callbacks=[bema_callback], ) trainer.train() # Check that the BEMA model was saved and can be loaded bema_path = os.path.join(self.tmp_dir, "bema") self.assertTrue(os.path.isdir(bema_path), "BEMA directory was not created") AutoModelForCausalLM.from_pretrained(bema_path) def test_update_frequency_0(self): """Test that BEMA callback respects the update frequency.""" training_args = TrainingArguments(output_dir=self.tmp_dir, report_to="none") bema_callback = BEMACallback(update_freq=2) with patch.object(bema_callback, "_update_bema_weights") as mock_update: trainer = Trainer( model=self.model, args=training_args, train_dataset=self.dataset["train"], processing_class=self.tokenizer, callbacks=[bema_callback], ) trainer.train() # Total 9 steps (17 samples, batch size 8, 3 epochs). # BEMA starts after step 0 and updates every 2 steps → updates at 2, 4, 5, 8 self.assertEqual(mock_update.call_args_list, [call(2), call(4), call(6), call(8)]) def test_update_frequency_1(self): """Test that BEMA callback respects the update frequency.""" training_args = TrainingArguments(output_dir=self.tmp_dir, report_to="none") bema_callback = BEMACallback(update_freq=3) with patch.object(bema_callback, "_update_bema_weights") as mock_update: trainer = Trainer( model=self.model, args=training_args, train_dataset=self.dataset["train"], processing_class=self.tokenizer, callbacks=[bema_callback], ) trainer.train() # Total 9 steps (17 samples, batch size 8, 3 epochs). # BEMA starts after step 0 and updates every 3 steps → updates at 3, 6, 9 self.assertEqual(mock_update.call_args_list, [call(3), call(6), call(9)]) def test_update_frequency_2(self): """Test that BEMA callback respects the update frequency.""" training_args = TrainingArguments(output_dir=self.tmp_dir, report_to="none") bema_callback = BEMACallback(update_freq=2, update_after=3) with patch.object(bema_callback, "_update_bema_weights") as mock_update: trainer = Trainer( model=self.model, args=training_args, train_dataset=self.dataset["train"], processing_class=self.tokenizer, callbacks=[bema_callback], ) trainer.train() # Total 9 steps (17 samples, batch size 8, 3 epochs). # BEMA starts after step 3 and updates every 2 steps → updates at 5, 7, 9 self.assertEqual(mock_update.call_args_list, [call(5), call(7), call(9)]) def test_no_bema(self): """Test that BEMACallback works without BEMA updates.""" training_args = TrainingArguments(output_dir=self.tmp_dir, report_to="none") bema_callback = BEMACallback(update_freq=2, bias_power=0.0) trainer = Trainer( model=self.model, args=training_args, train_dataset=self.dataset["train"], processing_class=self.tokenizer, callbacks=[bema_callback], ) trainer.train() def test_no_ema(self): """Test that BEMACallback works without EMA updates.""" training_args = TrainingArguments(output_dir=self.tmp_dir, report_to="none") bema_callback = BEMACallback(update_freq=2, ema_power=0.0) trainer = Trainer( model=self.model, args=training_args, train_dataset=self.dataset["train"], processing_class=self.tokenizer, callbacks=[bema_callback], ) trainer.train()
trl/tests/test_callbacks.py/0
{ "file_path": "trl/tests/test_callbacks.py", "repo_id": "trl", "token_count": 9159 }
597
# Copyright 2020-2025 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import gc import unittest import torch from parameterized import parameterized from transformers import AutoModelForCausalLM, AutoModelForSeq2SeqLM, GenerationConfig from trl import AutoModelForCausalLMWithValueHead, AutoModelForSeq2SeqLMWithValueHead, create_reference_model from .testing_utils import TrlTestCase ALL_CAUSAL_LM_MODELS = [ "trl-internal-testing/tiny-BloomForCausalLM", "trl-internal-testing/tiny-CohereForCausalLM", "trl-internal-testing/tiny-DbrxForCausalLM", # "trl-internal-testing/tiny-FalconMambaForCausalLM", # FalconMambaForCausalLM modeling seems to be broken for now "trl-internal-testing/tiny-Gemma2ForCausalLM", "trl-internal-testing/tiny-GemmaForCausalLM", "trl-internal-testing/tiny-GPT2LMHeadModel", "trl-internal-testing/tiny-GPTNeoXForCausalLM", "trl-internal-testing/tiny-LlamaForCausalLM-3.1", "trl-internal-testing/tiny-LlamaForCausalLM-3.2", "trl-internal-testing/tiny-LlamaForCausalLM-3", "trl-internal-testing/tiny-MistralForCausalLM-0.1", "trl-internal-testing/tiny-MistralForCausalLM-0.2", "trl-internal-testing/tiny-OPTForCausalLM", "trl-internal-testing/tiny-Phi3ForCausalLM", "trl-internal-testing/tiny-Qwen2ForCausalLM-2.5", ] ALL_SEQ2SEQ_MODELS = [ "trl-internal-testing/tiny-T5ForConditionalGeneration", "trl-internal-testing/tiny-BartModel", ] class BaseTester: class VHeadModelTester(TrlTestCase): all_model_names = None trl_model_class = None transformers_model_class = None def test_value_head(self): r""" Test if the v-head is added to the model successfully """ for model_name in self.all_model_names: model = self.trl_model_class.from_pretrained(model_name) self.assertTrue(hasattr(model, "v_head")) def test_value_head_shape(self): r""" Test if the v-head has the correct shape """ for model_name in self.all_model_names: model = self.trl_model_class.from_pretrained(model_name) self.assertEqual(model.v_head.summary.weight.shape[0], 1) def test_value_head_init_random(self): r""" Test if the v-head has been randomly initialized. We can check that by making sure the bias is different than zeros by default. """ for model_name in self.all_model_names: model = self.trl_model_class.from_pretrained(model_name) self.assertFalse( torch.allclose(model.v_head.summary.bias, torch.zeros_like(model.v_head.summary.bias)) ) def test_value_head_not_str(self): r""" Test if the v-head is added to the model successfully, by passing a non `PretrainedModel` as an argument to `from_pretrained`. """ for model_name in self.all_model_names: pretrained_model = self.transformers_model_class.from_pretrained(model_name) model = self.trl_model_class.from_pretrained(pretrained_model) self.assertTrue(hasattr(model, "v_head")) def test_from_save_trl(self): """ Test if the model can be saved and loaded from a directory and get the same weights, including the additional modules (e.g. v_head) """ for model_name in self.all_model_names: model = self.trl_model_class.from_pretrained(model_name) model.save_pretrained(self.tmp_dir) model_from_save = self.trl_model_class.from_pretrained(self.tmp_dir) # Check if the weights are the same for key in model_from_save.state_dict(): self.assertTrue(torch.allclose(model_from_save.state_dict()[key], model.state_dict()[key])) def test_from_save_trl_sharded(self): """ Test if the model can be saved and loaded from a directory and get the same weights - sharded case """ for model_name in self.all_model_names: model = self.trl_model_class.from_pretrained(model_name) model.save_pretrained(self.tmp_dir) model_from_save = self.trl_model_class.from_pretrained(self.tmp_dir) # Check if the weights are the same for key in model_from_save.state_dict(): self.assertTrue(torch.allclose(model_from_save.state_dict()[key], model.state_dict()[key])) def test_from_save_transformers_sharded(self): """ Test if the model can be saved and loaded using transformers and get the same weights - sharded case """ for model_name in self.all_model_names: transformers_model = self.trl_model_class.transformers_parent_class.from_pretrained(model_name) trl_model = self.trl_model_class.from_pretrained(model_name) trl_model.save_pretrained(self.tmp_dir, max_shard_size="1MB") transformers_model_from_save = self.trl_model_class.transformers_parent_class.from_pretrained( self.tmp_dir ) # Check if the weights are the same for key in transformers_model.state_dict(): self.assertTrue( torch.allclose( transformers_model_from_save.state_dict()[key], transformers_model.state_dict()[key] ) ) def test_from_save_transformers(self): """ Test if the model can be saved and loaded using transformers and get the same weights. We override the test of the super class to check if the weights are the same. """ for model_name in self.all_model_names: transformers_model = self.trl_model_class.transformers_parent_class.from_pretrained(model_name) trl_model = self.trl_model_class.from_pretrained(model_name) trl_model.save_pretrained(self.tmp_dir) transformers_model_from_save = self.trl_model_class.transformers_parent_class.from_pretrained( self.tmp_dir ) # Check if the weights are the same for key in transformers_model.state_dict(): self.assertTrue( torch.allclose( transformers_model_from_save.state_dict()[key], transformers_model.state_dict()[key] ) ) # Check if the trl model has the same keys as the transformers model # except the v_head for key in trl_model.state_dict(): if "v_head" not in key: self.assertIn(key, transformers_model.state_dict()) # check if the weights are the same self.assertTrue( torch.allclose(trl_model.state_dict()[key], transformers_model.state_dict()[key]) ) # check if they have the same modules self.assertEqual( set(transformers_model_from_save.state_dict().keys()), set(transformers_model.state_dict().keys()), ) class CausalLMValueHeadModelTester(BaseTester.VHeadModelTester, TrlTestCase): """ Testing suite for v-head models. """ all_model_names = ALL_CAUSAL_LM_MODELS trl_model_class = AutoModelForCausalLMWithValueHead transformers_model_class = AutoModelForCausalLM def tearDown(self): # free memory gc.collect() super().tearDown() def test_inference(self): r""" Test if the model can be used for inference and outputs 3 values - logits, loss, and value states """ EXPECTED_OUTPUT_SIZE = 3 for model_name in self.all_model_names: model = self.trl_model_class.from_pretrained(model_name) input_ids = torch.tensor([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]) outputs = model(input_ids) # Check if the outputs are of the right size - here # we always output 3 values - logits, loss, and value states self.assertEqual(len(outputs), EXPECTED_OUTPUT_SIZE) def test_dropout_config(self): r""" Test if we instantiate a model by adding `summary_drop_prob` to the config it will be added to the v_head """ for model_name in self.all_model_names: pretrained_model = self.transformers_model_class.from_pretrained(model_name) pretrained_model.config.summary_dropout_prob = 0.5 model = self.trl_model_class.from_pretrained(pretrained_model) # Check if v head of the model has the same dropout as the config self.assertEqual(model.v_head.dropout.p, pretrained_model.config.summary_dropout_prob) def test_dropout_kwargs(self): r""" Test if we instantiate a model by adding `summary_drop_prob` to the config it will be added to the v_head """ for model_name in self.all_model_names: v_head_kwargs = {"summary_dropout_prob": 0.5} model = self.trl_model_class.from_pretrained(model_name, **v_head_kwargs) # Check if v head of the model has the same dropout as the config self.assertEqual(model.v_head.dropout.p, 0.5) model = self.trl_model_class.from_pretrained(model_name, summary_dropout_prob=0.5) # Check if v head of the model has the same dropout as the config self.assertEqual(model.v_head.dropout.p, 0.5) @parameterized.expand(ALL_CAUSAL_LM_MODELS) def test_generate(self, model_name): r""" Test if `generate` works for every model """ generation_config = GenerationConfig(max_new_tokens=9) model = self.trl_model_class.from_pretrained(model_name) input_ids = torch.tensor([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]) # Just check if the generation works _ = model.generate(input_ids, generation_config=generation_config) def test_transformers_bf16_kwargs(self): r""" Test if the transformers kwargs are correctly passed. Here we check that loading a model in half precision works as expected, i.e. the weights of the `pretrained_model` attribute is loaded in half precision and you can run a dummy forward pass without any issue. """ for model_name in self.all_model_names: trl_model = self.trl_model_class.from_pretrained(model_name, torch_dtype=torch.bfloat16) lm_head_namings = ["lm_head", "embed_out", "output_layer"] self.assertTrue( any(hasattr(trl_model.pretrained_model, lm_head_naming) for lm_head_naming in lm_head_namings), "Can't test the model because it doesn't have any of the expected lm_head namings", ) for lm_head_naming in lm_head_namings: if hasattr(trl_model.pretrained_model, lm_head_naming): self.assertEqual(getattr(trl_model.pretrained_model, lm_head_naming).weight.dtype, torch.bfloat16) dummy_input = torch.LongTensor([[0, 1, 0, 1]]) # check dummy forward pass works in half precision _ = trl_model(dummy_input) @unittest.skip("This test needs to be run manually due to HF token issue.") def test_push_to_hub(self): for model_name in self.all_model_names: model = AutoModelForCausalLMWithValueHead.from_pretrained(model_name) if "sharded" in model_name: model.push_to_hub(model_name + "-ppo", use_auth_token=True, max_shard_size="1MB") else: model.push_to_hub(model_name + "-ppo", use_auth_token=True) model_from_pretrained = AutoModelForCausalLMWithValueHead.from_pretrained(model_name + "-ppo") # check all keys self.assertEqual(model.state_dict().keys(), model_from_pretrained.state_dict().keys()) for name, param in model.state_dict().items(): self.assertTrue( torch.allclose(param, model_from_pretrained.state_dict()[name]), f"Parameter {name} is not the same after push_to_hub and from_pretrained", ) class Seq2SeqValueHeadModelTester(BaseTester.VHeadModelTester, TrlTestCase): """ Testing suite for v-head models. """ all_model_names = ALL_SEQ2SEQ_MODELS trl_model_class = AutoModelForSeq2SeqLMWithValueHead transformers_model_class = AutoModelForSeq2SeqLM def tearDown(self): # free memory gc.collect() super().tearDown() def test_inference(self): r""" Test if the model can be used for inference and outputs 3 values - logits, loss, and value states """ EXPECTED_OUTPUT_SIZE = 3 for model_name in self.all_model_names: model = self.trl_model_class.from_pretrained(model_name) input_ids = torch.tensor([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]) decoder_input_ids = torch.tensor([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]) outputs = model(input_ids, decoder_input_ids=decoder_input_ids) # Check if the outputs are of the right size - here # we always output 3 values - logits, loss, and value states self.assertEqual(len(outputs), EXPECTED_OUTPUT_SIZE) def test_dropout_config(self): r""" Test if we instantiate a model by adding `summary_drop_prob` to the config it will be added to the v_head """ for model_name in self.all_model_names: pretrained_model = self.transformers_model_class.from_pretrained(model_name) pretrained_model.config.summary_dropout_prob = 0.5 model = self.trl_model_class.from_pretrained(pretrained_model) # Check if v head of the model has the same dropout as the config self.assertEqual(model.v_head.dropout.p, pretrained_model.config.summary_dropout_prob) def test_dropout_kwargs(self): r""" Test if we instantiate a model by adding `summary_drop_prob` to the config it will be added to the v_head """ for model_name in self.all_model_names: v_head_kwargs = {"summary_dropout_prob": 0.5} model = self.trl_model_class.from_pretrained(model_name, **v_head_kwargs) # Check if v head of the model has the same dropout as the config self.assertEqual(model.v_head.dropout.p, 0.5) model = self.trl_model_class.from_pretrained(model_name, summary_dropout_prob=0.5) # Check if v head of the model has the same dropout as the config self.assertEqual(model.v_head.dropout.p, 0.5) @parameterized.expand(ALL_SEQ2SEQ_MODELS) def test_generate(self, model_name): r""" Test if `generate` works for every model """ generation_config = GenerationConfig(max_new_tokens=9) model = self.trl_model_class.from_pretrained(model_name) input_ids = torch.tensor([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]) decoder_input_ids = torch.tensor([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]) # Just check if the generation works _ = model.generate(input_ids, decoder_input_ids=decoder_input_ids, generation_config=generation_config) @unittest.skip("This test needs to be run manually due to HF token issue.") def test_push_to_hub(self): for model_name in self.all_model_names: model = self.trl_model_class.from_pretrained(model_name) if "sharded" in model_name: model.push_to_hub(model_name + "-ppo", use_auth_token=True, max_shard_size="1MB") else: model.push_to_hub(model_name + "-ppo", use_auth_token=True) model_from_pretrained = self.trl_model_class.from_pretrained(model_name + "-ppo") # check all keys self.assertEqual(model.state_dict().keys(), model_from_pretrained.state_dict().keys()) for name, param in model.state_dict().items(): self.assertTrue( torch.allclose(param, model_from_pretrained.state_dict()[name]), f"Parameter {name} is not the same after push_to_hub and from_pretrained", ) def test_transformers_bf16_kwargs(self): r""" Test if the transformers kwargs are correctly passed. Here we check that loading a model in half precision works as expected, i.e. the weights of the `pretrained_model` attribute is loaded in half precision and you can run a dummy forward pass without any issue. """ for model_name in self.all_model_names: trl_model = self.trl_model_class.from_pretrained(model_name, torch_dtype=torch.bfloat16) lm_head_namings = self.trl_model_class.lm_head_namings self.assertTrue( any(hasattr(trl_model.pretrained_model, lm_head_naming) for lm_head_naming in lm_head_namings) ) for lm_head_naming in lm_head_namings: if hasattr(trl_model.pretrained_model, lm_head_naming): self.assertTrue(getattr(trl_model.pretrained_model, lm_head_naming).weight.dtype == torch.bfloat16) dummy_input = torch.LongTensor([[0, 1, 0, 1]]) # check dummy forward pass works in half precision _ = trl_model(input_ids=dummy_input, decoder_input_ids=dummy_input) class ReferenceModelTest(TrlTestCase): def setUp(self): super().setUp() self.model = AutoModelForCausalLMWithValueHead.from_pretrained("trl-internal-testing/tiny-GPT2LMHeadModel") self.test_input = torch.tensor([[0, 1, 2, 3]]) self.optimizer = torch.optim.AdamW(self.model.parameters(), lr=1) self.layer_format = "pretrained_model.transformer.h.{layer}.attn.c_attn.weight" def test_independent_reference(self): layer_0 = self.layer_format.format(layer=0) layer_1 = self.layer_format.format(layer=1) ref_model = create_reference_model(self.model) first_layer_before = self.model.get_parameter(layer_0).data.clone() last_layer_before = self.model.get_parameter(layer_1).data.clone() # the model only has 2 layers first_ref_layer_before = ref_model.get_parameter(layer_0).data.clone() last_ref_layer_before = ref_model.get_parameter(layer_1).data.clone() output = self.model(input_ids=self.test_input, labels=self.test_input) output[1].backward() self.optimizer.step() first_layer_after = self.model.get_parameter(layer_0).data.clone() last_layer_after = self.model.get_parameter(layer_1).data.clone() first_ref_layer_after = ref_model.get_parameter(layer_0).data.clone() last_ref_layer_after = ref_model.get_parameter(layer_1).data.clone() # before optimization ref and model are identical self.assertTrue((first_layer_before == first_ref_layer_before).all()) self.assertTrue((last_layer_before == last_ref_layer_before).all()) # ref model stays identical after optimization self.assertTrue((first_ref_layer_before == first_ref_layer_after).all()) self.assertTrue((last_ref_layer_before == last_ref_layer_after).all()) # optimized model changes self.assertFalse((first_layer_before == first_layer_after).all()) self.assertFalse((last_layer_before == last_layer_after).all()) def test_shared_layers(self): layer_0 = self.layer_format.format(layer=0) layer_1 = self.layer_format.format(layer=1) ref_model = create_reference_model(self.model, num_shared_layers=1) first_layer_before = self.model.get_parameter(layer_0).data.clone() second_layer_before = self.model.get_parameter(layer_1).data.clone() first_ref_layer_before = ref_model.get_parameter(layer_0).data.clone() second_ref_layer_before = ref_model.get_parameter(layer_1).data.clone() output = self.model(input_ids=self.test_input, labels=self.test_input) output[1].backward() self.optimizer.step() first_layer_after = self.model.get_parameter(layer_0).data.clone() second_layer_after = self.model.get_parameter(layer_1).data.clone() first_ref_layer_after = ref_model.get_parameter(layer_0).data.clone() second_ref_layer_after = ref_model.get_parameter(layer_1).data.clone() # before optimization ref and model are identical self.assertTrue((first_layer_before == first_ref_layer_before).all()) self.assertTrue((second_layer_before == second_ref_layer_before).all()) # ref model stays identical after optimization self.assertTrue((first_ref_layer_before == first_ref_layer_after).all()) self.assertTrue((second_ref_layer_before == second_ref_layer_after).all()) # first layer of optimized model stays the same self.assertTrue((first_layer_before == first_layer_after).all()) # other layers in optimized model change self.assertFalse((second_layer_before == second_layer_after).all())
trl/tests/test_modeling_value_head.py/0
{ "file_path": "trl/tests/test_modeling_value_head.py", "repo_id": "trl", "token_count": 9757 }
598
# 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 contextlib import functools import time from collections.abc import Generator from transformers import Trainer from transformers.integrations import is_mlflow_available, is_wandb_available if is_wandb_available(): import wandb if is_mlflow_available(): import mlflow @contextlib.contextmanager def profiling_context(trainer: Trainer, name: str) -> Generator[None, None, None]: """ A context manager function for profiling a block of code. Results are logged to Weights & Biases or MLflow depending on the trainer's configuration. Args: trainer (`~transformers.Trainer`): Trainer object. name (`str`): Name of the block to be profiled. Used as a key in the logged dictionary. Example: ```python from transformers import Trainer from trl.extras.profiling import profiling_context class MyTrainer(Trainer): def some_method(self): A = np.random.rand(1000, 1000) B = np.random.rand(1000, 1000) with profiling_context(self, "matrix_multiplication"): # Code to profile: simulate a computationally expensive operation result = A @ B # Matrix multiplication ``` """ start_time = time.perf_counter() yield end_time = time.perf_counter() duration = end_time - start_time profiling_metrics = {f"profiling/Time taken: {trainer.__class__.__name__}.{name}": duration} if "wandb" in trainer.args.report_to and wandb.run is not None and trainer.accelerator.is_main_process: wandb.log(profiling_metrics) if "mlflow" in trainer.args.report_to and mlflow.run is not None and trainer.accelerator.is_main_process: mlflow.log_metrics(profiling_metrics, step=trainer.state.global_step) def profiling_decorator(func: callable) -> callable: """ Decorator to profile a function and log execution time using [`extras.profiling.profiling_context`]. Args: func (`callable`): Function to be profiled. Example: ```python from transformers import Trainer from trl.extras.profiling import profiling_decorator class MyTrainer(Trainer): @profiling_decorator def some_method(self): A = np.random.rand(1000, 1000) B = np.random.rand(1000, 1000) # Code to profile: simulate a computationally expensive operation result = A @ B ``` """ @functools.wraps(func) def wrapper(self, *args, **kwargs): with profiling_context(self, func.__name__): return func(self, *args, **kwargs) return wrapper
trl/trl/extras/profiling.py/0
{ "file_path": "trl/trl/extras/profiling.py", "repo_id": "trl", "token_count": 1184 }
599
# Copyright 2020-2025 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import inspect import os import random import textwrap from collections import defaultdict from contextlib import nullcontext from pathlib import Path from typing import Any, Callable, Literal, Optional, Union import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F from accelerate import PartialState, logging from datasets import Dataset from torch import autocast from torch.utils.data import DataLoader from transformers import ( AutoModelForCausalLM, BaseImageProcessor, DataCollator, FeatureExtractionMixin, PreTrainedModel, PreTrainedTokenizerBase, ProcessorMixin, Trainer, is_comet_available, is_wandb_available, ) from transformers.trainer_callback import TrainerCallback from transformers.trainer_utils import EvalLoopOutput from transformers.utils import is_peft_available, is_torch_fx_proxy from ..data_utils import maybe_apply_chat_template, maybe_extract_prompt from .cpo_config import CPOConfig from .utils import ( DPODataCollatorWithPadding, add_bos_token_if_needed, add_eos_token_if_needed, disable_dropout_in_model, generate_model_card, get_comet_experiment_url, log_table_to_comet_experiment, pad_to_length, peft_module_casting_to_bf16, selective_log_softmax, ) if is_peft_available(): from peft import PeftModel, get_peft_model, prepare_model_for_kbit_training if is_wandb_available(): import wandb logger = logging.get_logger(__name__) class CPOTrainer(Trainer): r""" Initialize CPOTrainer. Args: model (`transformers.PreTrainedModel`): The model to train, preferably an `AutoModelForSequenceClassification`. args (`CPOConfig`): The CPO 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. model_init (`Callable[[], transformers.PreTrainedModel]`): The model initializer to use for training. If None is specified, the default model initializer will be used. callbacks (`list[transformers.TrainerCallback]`): The callbacks to use for training. optimizers (`tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR]`): The optimizer and scheduler to use for training. preprocess_logits_for_metrics (`Callable[[torch.Tensor, torch.Tensor], torch.Tensor]`): The function to use to preprocess the logits before computing the metrics. peft_config (`dict`, defaults to `None`): The PEFT configuration to use for training. If you pass a PEFT configuration, the model will be wrapped in a PEFT model. compute_metrics (`Callable[[EvalPrediction], dict]`, *optional*): The function to use to compute the metrics. Must take a `EvalPrediction` and return a dictionary string to metric values. """ _tag_names = ["trl", "cpo"] def __init__( self, model: Optional[Union[PreTrainedModel, nn.Module, str]] = None, args: Optional[CPOConfig] = None, data_collator: Optional[DataCollator] = None, train_dataset: Optional[Dataset] = None, eval_dataset: Optional[Union[Dataset, dict[str, Dataset]]] = None, processing_class: Optional[ Union[PreTrainedTokenizerBase, BaseImageProcessor, FeatureExtractionMixin, ProcessorMixin] ] = None, model_init: Optional[Callable[[], PreTrainedModel]] = None, callbacks: Optional[list[TrainerCallback]] = None, optimizers: tuple[torch.optim.Optimizer, torch.optim.lr_scheduler.LambdaLR] = (None, None), preprocess_logits_for_metrics: Optional[Callable[[torch.Tensor, torch.Tensor], torch.Tensor]] = None, peft_config: Optional[dict] = None, compute_metrics: Optional[Callable[[EvalLoopOutput], dict]] = None, ): if args.model_init_kwargs is None: model_init_kwargs = {} elif not isinstance(model, str): raise ValueError("You passed model_kwargs to the CPOTrainer. But your model is already instantiated.") else: model_init_kwargs = args.model_init_kwargs torch_dtype = model_init_kwargs.get("torch_dtype") if torch_dtype is not None: # Convert to `torch.dtype` if an str is passed if isinstance(torch_dtype, str) and torch_dtype != "auto": torch_dtype = getattr(torch, torch_dtype) if torch_dtype != "auto" and not isinstance(torch_dtype, torch.dtype): raise ValueError( f"Invalid `torch_dtype` passed to the CPOConfig. Expected a string with either `torch.dtype` or 'auto', but got {torch_dtype}." ) model_init_kwargs["torch_dtype"] = torch_dtype if isinstance(model, str): model = AutoModelForCausalLM.from_pretrained(model, **model_init_kwargs) # Initialize this variable to False. This helps tracking the case when `peft_module_casting_to_bf16` # has been called in order to properly call autocast if needed. self._peft_has_been_casted_to_bf16 = False if not is_peft_available() and peft_config is not None: raise ValueError( "PEFT is not installed and you passed a `peft_config` in the trainer's kwargs, please install it to use the PEFT models" ) elif is_peft_available() and peft_config is not None: # if model is a peft model and we have a peft_config, we merge and unload it first if isinstance(model, PeftModel): model = model.merge_and_unload() if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False): _support_gc_kwargs = hasattr( args, "gradient_checkpointing_kwargs" ) and "gradient_checkpointing_kwargs" in list( inspect.signature(prepare_model_for_kbit_training).parameters ) prepare_model_kwargs = {"use_gradient_checkpointing": args.gradient_checkpointing} if _support_gc_kwargs: prepare_model_kwargs["gradient_checkpointing_kwargs"] = args.gradient_checkpointing_kwargs model = prepare_model_for_kbit_training(model, **prepare_model_kwargs) elif args.gradient_checkpointing: # For backward compatibility with older versions of transformers if hasattr(model, "enable_input_require_grads"): model.enable_input_require_grads() else: def make_inputs_require_grad(module, input, output): output.requires_grad_(True) model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) # get peft model with the given config model = get_peft_model(model, peft_config) if args.bf16 and getattr(model, "is_loaded_in_4bit", False): peft_module_casting_to_bf16(model) # If args.bf16 we need to explicitly call `generate` with torch amp autocast context manager self._peft_has_been_casted_to_bf16 = True # For models that use gradient_checkpointing, we need to attach a hook that enables input # to explicitly have `requires_grad=True`, otherwise training will either silently # fail or completely fail. elif args.gradient_checkpointing: # For backward compatibility with older versions of transformers if hasattr(model, "enable_input_require_grads"): model.enable_input_require_grads() else: def make_inputs_require_grad(module, input, output): output.requires_grad_(True) model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) if args.generate_during_eval and not (is_wandb_available() or is_comet_available()): raise ValueError( "`generate_during_eval=True` requires Weights and Biases or Comet to be installed." " Please install `wandb` or `comet-ml` to resolve." ) if model is not None: self.is_encoder_decoder = model.config.is_encoder_decoder elif args.is_encoder_decoder is None: raise ValueError("When no model is provided, you need to pass the parameter is_encoder_decoder.") else: self.is_encoder_decoder = args.is_encoder_decoder if self.is_encoder_decoder: self.decoder_start_token_id = model.config.decoder_start_token_id self.pad_token_id = model.config.pad_token_id if processing_class is None: raise ValueError("processing_class must be specified to tokenize a CPO dataset.") if args.max_length is None: logger.warning( "`max_length` is not set in the CPOConfig's init" " it will default to `512` by default, but you should do it yourself in the future.", ) max_length = 512 else: max_length = args.max_length if args.max_prompt_length is None: logger.warning( "`max_prompt_length` is not set in the CPOConfig's init" " it will default to `128` by default, but you should do it yourself in the future.", ) max_prompt_length = 128 else: max_prompt_length = args.max_prompt_length if not max_prompt_length < max_length: raise ValueError( f"max_prompt_length ({max_prompt_length}) should be strictly less than max_length ({max_length})." ) if args.max_completion_length is None and self.is_encoder_decoder: logger.warning( "When using an encoder decoder architecture, you should set `max_completion_length` in the CPOConfig's init" " it will default to `128` by default, but you should do it yourself in the future.", ) max_completion_length = 128 else: max_completion_length = args.max_completion_length if data_collator is None: data_collator = DPODataCollatorWithPadding( pad_token_id=processing_class.pad_token_id, label_pad_token_id=args.label_pad_token_id, is_encoder_decoder=self.is_encoder_decoder, ) if args.remove_unused_columns: args.remove_unused_columns = False # warn users logger.warning( "When using DPODataCollatorWithPadding, you should set `remove_unused_columns=False` in your TrainingArguments" " we have set it for you, but you should do it yourself in the future.", ) self.use_dpo_data_collator = True else: self.use_dpo_data_collator = False # Disable dropout in the model if args.disable_dropout: disable_dropout_in_model(model) self.max_length = max_length self.generate_during_eval = args.generate_during_eval self.label_pad_token_id = args.label_pad_token_id self.padding_value = args.padding_value if args.padding_value is not None else processing_class.pad_token_id self.max_prompt_length = max_prompt_length self.truncation_mode = args.truncation_mode self.max_completion_length = max_completion_length self.processing_class = processing_class if args.loss_type in ["hinge", "ipo"] and args.label_smoothing > 0: logger.warning( f"You are using the {args.loss_type} loss type that does not support label smoothing. The " "`label_smoothing` parameter will be ignored. Set `label_smoothing` to `0.0` to remove this warning.", ) if args.loss_type == "kto_pair": raise ValueError("Support for kto_pair has been removed in CPOTrainer. Please use KTOTrainer.") self.beta = args.beta self.label_smoothing = args.label_smoothing self.loss_type = args.loss_type self.cpo_alpha = args.cpo_alpha self.aux_loss_enabled = getattr(model.config, "output_router_logits", False) self.aux_loss_coef = getattr(model.config, "router_aux_loss_coef", 0.0) if self.aux_loss_enabled and self.aux_loss_coef == 0.0: logger.warning( "You set `output_router_logits` to `True` in the model config, but `router_aux_loss_coef` is set to " "`0.0`, meaning the auxiliary loss will not be used. Either set `router_aux_loss_coef` to a value " "greater than `0.0`, or set `output_router_logits` to `False` if you don't want to use the auxiliary " "loss.", ) if args.loss_type == "simpo": self.simpo_gamma = args.simpo_gamma # AlphaPO parameter for reward shaping self.alpha = args.alpha self._stored_metrics = defaultdict(lambda: defaultdict(list)) # 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 CPO, the sampled data does not include the # "input_ids" key. Instead, the available keys are "prompt_input_ids", "chosen_input_ids", and # "rejected_input_ids". As a result, the trainer issues the warning: "Could not estimate the number of tokens # of the input, floating-point operations will not be computed." To suppress this warning, we set the # "estimate_tokens" key in the model's "warnings_issued" dictionary to True. This acts as a flag to indicate # that the warning has already been issued. model.warnings_issued["estimate_tokens"] = True # Compute that only on the main process for faster data processing. # see: https://github.com/huggingface/trl/pull/1255 with PartialState().main_process_first(): # Extract the prompt if needed, and apply the chat template if needed train_dataset = train_dataset.map(maybe_extract_prompt, num_proc=args.dataset_num_proc) train_dataset = train_dataset.map( maybe_apply_chat_template, fn_kwargs={"tokenizer": processing_class}, num_proc=args.dataset_num_proc ) if eval_dataset is not None: eval_dataset = eval_dataset.map(maybe_extract_prompt, num_proc=args.dataset_num_proc) eval_dataset = eval_dataset.map( maybe_apply_chat_template, fn_kwargs={"tokenizer": processing_class}, num_proc=args.dataset_num_proc, ) # tokenize the dataset train_dataset = train_dataset.map(self.tokenize_row, num_proc=args.dataset_num_proc) if eval_dataset is not None: eval_dataset = eval_dataset.map(self.tokenize_row, num_proc=args.dataset_num_proc) super().__init__( model=model, args=args, data_collator=data_collator, train_dataset=train_dataset, eval_dataset=eval_dataset, processing_class=processing_class, model_init=model_init, compute_metrics=compute_metrics, callbacks=callbacks, optimizers=optimizers, preprocess_logits_for_metrics=preprocess_logits_for_metrics, ) # Gradient accumulation requires scaled loss. Normally, loss scaling in the parent class depends on whether the # model accepts loss-related kwargs. Since we compute our own loss, this check is irrelevant. We set # self.model_accepts_loss_kwargs to False to enable scaling. self.model_accepts_loss_kwargs = False # Add tags for models that have been loaded with the correct transformers version if hasattr(self.model, "add_model_tags"): self.model.add_model_tags(self._tag_names) if not hasattr(self, "accelerator"): raise AttributeError( "Your `Trainer` does not have an `accelerator` object. Consider upgrading `transformers`." ) def build_tokenized_answer(self, prompt, answer): """ Llama tokenizer does satisfy `enc(a + b) = enc(a) + enc(b)`. It does ensure `enc(a + b) = enc(a) + enc(a + b)[len(enc(a)):]`. Reference: https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257 """ full_tokenized = self.processing_class(prompt + answer, add_special_tokens=False) prompt_input_ids = self.processing_class(prompt, add_special_tokens=False)["input_ids"] answer_input_ids = full_tokenized["input_ids"][len(prompt_input_ids) :] answer_attention_mask = full_tokenized["attention_mask"][len(prompt_input_ids) :] # Concat tokens to form `enc(a) + enc(a + b)[len(enc(a)):]` full_concat_input_ids = np.concatenate([prompt_input_ids, answer_input_ids]) # Prepare input tokens for token by token comparison full_input_ids = np.array(full_tokenized["input_ids"]) if len(full_input_ids) != len(full_concat_input_ids): raise ValueError("Prompt input ids and answer input ids should have the same length.") # On some tokenizers, like Llama-2 tokenizer, there are occasions where tokens # can be merged together when tokenizing prompt+answer. This could result # on the last token from the prompt being different when tokenized on its own # vs when done as prompt+answer. response_token_ids_start_idx = len(prompt_input_ids) # If tokenized prompt is different than both prompt+answer, then it means the # last token has changed due to merging. if prompt_input_ids != full_tokenized["input_ids"][:response_token_ids_start_idx]: response_token_ids_start_idx -= 1 prompt_input_ids = full_tokenized["input_ids"][:response_token_ids_start_idx] prompt_attention_mask = full_tokenized["attention_mask"][:response_token_ids_start_idx] if len(prompt_input_ids) != len(prompt_attention_mask): raise ValueError("Prompt input ids and attention mask should have the same length.") answer_input_ids = full_tokenized["input_ids"][response_token_ids_start_idx:] answer_attention_mask = full_tokenized["attention_mask"][response_token_ids_start_idx:] return dict( prompt_input_ids=prompt_input_ids, prompt_attention_mask=prompt_attention_mask, input_ids=answer_input_ids, attention_mask=answer_attention_mask, ) def tokenize_row(self, feature, model: Optional[Union[PreTrainedModel, nn.Module]] = None) -> dict: """Tokenize a single row from a CPO specific dataset. At this stage, we don't convert to PyTorch tensors yet; we just handle the truncation in case the prompt + chosen or prompt + rejected responses is/are too long. First we truncate the prompt; if we're still too long, we truncate the chosen/rejected. We also create the labels for the chosen/rejected responses, which are of length equal to the sum of the length of the prompt and the chosen/rejected response, with label_pad_token_id for the prompt tokens. """ batch = {} prompt = feature["prompt"] chosen = feature["chosen"] rejected = feature["rejected"] if not self.is_encoder_decoder: # Check issues below for more details # 1. https://github.com/huggingface/trl/issues/907 # 2. https://github.com/EleutherAI/lm-evaluation-harness/pull/531#issuecomment-1595586257 # 3. https://github.com/LianjiaTech/BELLE/issues/337 if not isinstance(prompt, str): raise ValueError(f"prompt should be an str but got {type(prompt)}") prompt_tokens = self.processing_class(prompt, add_special_tokens=False) prompt_tokens = {f"prompt_{k}": v for k, v in prompt_tokens.items()} if not isinstance(chosen, str): raise ValueError(f"chosen should be an str but got {type(chosen)}") chosen_tokens = self.build_tokenized_answer(prompt, chosen) if not isinstance(rejected, str): raise ValueError(f"rejected should be an str but got {type(rejected)}") rejected_tokens = self.build_tokenized_answer(prompt, rejected) # Last prompt token might get merged by tokenizer and # it should not be included for generation if that happens prompt_len_input_ids = len(prompt_tokens["prompt_input_ids"]) chosen_prompt_len_input_ids = len(chosen_tokens["prompt_input_ids"]) rejected_prompt_len_input_ids = len(rejected_tokens["prompt_input_ids"]) prompt_len_input_ids = min(chosen_prompt_len_input_ids, rejected_prompt_len_input_ids) for k, v in prompt_tokens.items(): prompt_tokens[k] = v[:prompt_len_input_ids] # Make sure prompts only have one different token at most an # and length only differs by 1 at most num_diff_tokens = sum( [a != b for a, b in zip(chosen_tokens["prompt_input_ids"], rejected_tokens["prompt_input_ids"])] ) num_diff_len = abs(chosen_prompt_len_input_ids - rejected_prompt_len_input_ids) if num_diff_tokens > 1 or num_diff_len > 1: raise ValueError( "Chosen and rejected prompt_input_ids might only differ on the " "last token due to tokenizer merge ops." ) # add BOS token to head of prompt. Avoid adding if it's already there prompt_tokens, chosen_tokens, rejected_tokens = add_bos_token_if_needed( self.processing_class.bos_token_id, prompt_len_input_ids, prompt_tokens, chosen_prompt_len_input_ids, chosen_tokens, rejected_prompt_len_input_ids, rejected_tokens, ) # add EOS token to end of answer. Avoid adding if it's already there chosen_tokens, rejected_tokens = add_eos_token_if_needed( self.processing_class.eos_token_id, chosen_tokens, rejected_tokens ) longer_response_length = max(len(chosen_tokens["input_ids"]), len(rejected_tokens["input_ids"])) # if combined sequence is too long, truncate the prompt for answer_tokens in [chosen_tokens, rejected_tokens, prompt_tokens]: if len(answer_tokens["prompt_input_ids"]) + longer_response_length > self.max_length: if self.truncation_mode == "keep_start": for k in ["prompt_input_ids", "prompt_attention_mask"]: answer_tokens[k] = answer_tokens[k][: self.max_prompt_length] elif self.truncation_mode == "keep_end": for k in ["prompt_input_ids", "prompt_attention_mask"]: answer_tokens[k] = answer_tokens[k][-self.max_prompt_length :] else: raise ValueError(f"Unknown truncation mode: {self.truncation_mode}") # if that's still too long, truncate the response for answer_tokens in [chosen_tokens, rejected_tokens]: if len(answer_tokens["prompt_input_ids"]) + longer_response_length > self.max_length: for k in ["input_ids", "attention_mask"]: answer_tokens[k] = answer_tokens[k][: self.max_length - self.max_prompt_length] # Create labels chosen_sequence_tokens = { k: chosen_tokens[f"prompt_{k}"] + chosen_tokens[k] for k in ["input_ids", "attention_mask"] } rejected_sequence_tokens = { k: rejected_tokens[f"prompt_{k}"] + rejected_tokens[k] for k in ["input_ids", "attention_mask"] } chosen_sequence_tokens["labels"] = chosen_sequence_tokens["input_ids"][:] chosen_sequence_tokens["labels"][: len(chosen_tokens["prompt_input_ids"])] = [ self.label_pad_token_id ] * len(chosen_tokens["prompt_input_ids"]) rejected_sequence_tokens["labels"] = rejected_sequence_tokens["input_ids"][:] rejected_sequence_tokens["labels"][: len(rejected_tokens["prompt_input_ids"])] = [ self.label_pad_token_id ] * len(rejected_tokens["prompt_input_ids"]) for k, toks in { "chosen_": chosen_sequence_tokens, "rejected_": rejected_sequence_tokens, "": prompt_tokens, }.items(): for type_key, tokens in toks.items(): if type_key == "token_type_ids": continue batch[f"{k}{type_key}"] = tokens else: chosen_tokens = self.processing_class( chosen, truncation=True, max_length=self.max_completion_length, add_special_tokens=True ) rejected_tokens = self.processing_class( rejected, truncation=True, max_length=self.max_completion_length, add_special_tokens=True ) prompt_tokens = self.processing_class( prompt, truncation=True, max_length=self.max_prompt_length, add_special_tokens=True ) batch["chosen_labels"] = chosen_tokens["input_ids"] batch["rejected_labels"] = rejected_tokens["input_ids"] batch["prompt_input_ids"] = prompt_tokens["input_ids"] batch["prompt_attention_mask"] = prompt_tokens["attention_mask"] if model is not None and hasattr(model, "prepare_decoder_input_ids_from_labels"): batch["rejected_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels( labels=torch.tensor(batch["rejected_labels"]) ) batch["chosen_decoder_input_ids"] = model.prepare_decoder_input_ids_from_labels( labels=torch.tensor(batch["chosen_labels"]) ) return batch @staticmethod def concatenated_inputs( batch: dict[str, Union[list, torch.LongTensor]], is_encoder_decoder: bool = False, label_pad_token_id: int = -100, padding_value: int = 0, device: Optional[torch.device] = None, ) -> dict[str, torch.LongTensor]: """Concatenate the chosen and rejected inputs into a single tensor. Args: batch: A batch of data. Must contain the keys 'chosen_input_ids' and 'rejected_input_ids', which are tensors of shape (batch_size, sequence_length). is_encoder_decoder: Whether the model is an encoder-decoder model. label_pad_token_id: The label pad token id. padding_value: The padding value to use for the concatenated inputs_ids. device: The device for the concatenated inputs. Returns: A dictionary containing the concatenated inputs under the key 'concatenated_input_ids'. """ concatenated_batch = {} if is_encoder_decoder: max_length = max(batch["chosen_labels"].shape[1], batch["rejected_labels"].shape[1]) else: max_length = max(batch["chosen_input_ids"].shape[1], batch["rejected_input_ids"].shape[1]) for k in batch: if k.startswith("chosen") and isinstance(batch[k], torch.Tensor): if "labels" in k or is_encoder_decoder: pad_value = label_pad_token_id elif k.endswith("_input_ids"): pad_value = padding_value elif k.endswith("_attention_mask"): pad_value = 0 concatenated_key = k.replace("chosen", "concatenated") concatenated_batch[concatenated_key] = pad_to_length(batch[k], max_length, pad_value=pad_value) for k in batch: if k.startswith("rejected") and isinstance(batch[k], torch.Tensor): if "labels" in k or is_encoder_decoder: pad_value = label_pad_token_id elif k.endswith("_input_ids"): pad_value = padding_value elif k.endswith("_attention_mask"): pad_value = 0 concatenated_key = k.replace("rejected", "concatenated") concatenated_batch[concatenated_key] = torch.cat( ( concatenated_batch[concatenated_key], pad_to_length(batch[k], max_length, pad_value=pad_value), ), dim=0, ).to(device=device) if is_encoder_decoder: concatenated_batch["concatenated_input_ids"] = batch["prompt_input_ids"].repeat(2, 1).to(device=device) concatenated_batch["concatenated_attention_mask"] = ( batch["prompt_attention_mask"].repeat(2, 1).to(device=device) ) return concatenated_batch def cpo_loss( self, policy_chosen_logps: torch.FloatTensor, policy_rejected_logps: torch.FloatTensor, ) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: """Compute the CPO loss for a batch of policy and reference model log probabilities. Args: policy_chosen_logps: Log probabilities of the policy model for the chosen responses. Shape: (batch_size,) policy_rejected_logps: Log probabilities of the policy model for the rejected responses. Shape: (batch_size,) Returns: A tuple of three tensors: (losses, chosen_rewards, rejected_rewards). The losses tensor contains the CPO loss for each example in the batch. The chosen_rewards and rejected_rewards tensors contain the rewards for the chosen and rejected responses, respectively. """ # Apply AlphaPO reward transformation if alpha != 0 if self.alpha != 0.0: # Compute probabilities chosen_probs = torch.exp(policy_chosen_logps) rejected_probs = torch.exp(policy_rejected_logps) # Apply AlphaPO transformation: r = (1 - p^(-alpha)) / alpha policy_chosen_rewards = (1 - chosen_probs.pow(-self.alpha)) / self.alpha policy_rejected_rewards = (1 - rejected_probs.pow(-self.alpha)) / self.alpha logits = (policy_chosen_rewards - policy_rejected_rewards).to(self.accelerator.device) else: # Standard log probability rewards when alpha = 0 logits = (policy_chosen_logps - policy_rejected_logps).to(self.accelerator.device) # The beta is a temperature parameter for the CPO loss, typically something in the range of 0.1 to 0.5. # We ignore the reference model as beta -> 0. The label_smoothing parameter encodes our uncertainty about the labels and # calculates a conservative CPO loss. if self.loss_type == "simpo": gamma_logratios = self.simpo_gamma / self.beta logits = logits - gamma_logratios # This reduces to Equation 3 from the CPO paper when label_smoothing -> 0. losses = ( -F.logsigmoid(self.beta * logits) * (1 - self.label_smoothing) - F.logsigmoid(-self.beta * logits) * self.label_smoothing ) elif self.loss_type == "sigmoid": # This reduces to Equation 3 from the CPO paper when label_smoothing -> 0. losses = ( -F.logsigmoid(self.beta * logits) * (1 - self.label_smoothing) - F.logsigmoid(-self.beta * logits) * self.label_smoothing ) elif self.loss_type == "hinge": losses = torch.relu(1 - self.beta * logits) elif self.loss_type == "ipo": # eqn (17) of the paper where beta is the regularization parameter for the IPO loss, denoted by tau in the paper. losses = (logits - 1 / (2 * self.beta)) ** 2 else: raise ValueError( f"Unknown loss type: {self.loss_type}. Should be one of ['sigmoid', 'hinge', 'ipo', 'simpo']" ) # Calculate rewards for logging if self.alpha != 0.0: # When using AlphaPO transformation, use the transformed rewards chosen_rewards = self.beta * policy_chosen_rewards.to(self.accelerator.device).detach() rejected_rewards = self.beta * policy_rejected_rewards.to(self.accelerator.device).detach() else: # Standard log probability rewards chosen_rewards = self.beta * (policy_chosen_logps.to(self.accelerator.device)).detach() rejected_rewards = self.beta * (policy_rejected_logps.to(self.accelerator.device)).detach() return losses, chosen_rewards, rejected_rewards @staticmethod def get_batch_logps( logits: torch.FloatTensor, labels: torch.LongTensor, average_log_prob: bool = False, label_pad_token_id: int = -100, is_encoder_decoder: bool = False, ) -> torch.FloatTensor: """Compute the log probabilities of the given labels under the given logits. Args: logits: Logits of the model (unnormalized). Shape: (batch_size, sequence_length, vocab_size) labels: Labels for which to compute the log probabilities. Label tokens with a value of label_pad_token_id are ignored. Shape: (batch_size, sequence_length) average_log_prob: If True, return the average log probability per (non-masked) token. Otherwise, return the sum of the log probabilities of the (non-masked) tokens. label_pad_token_id: The label pad token id. is_encoder_decoder: Whether the model is an encoder-decoder model. Returns: A tensor of shape (batch_size,) containing the average/sum log probabilities of the given labels under the given logits. """ if logits.shape[:-1] != labels.shape: raise ValueError("Logits (batch and sequence length dim) and labels must have the same shape.") if not is_encoder_decoder: labels = labels[:, 1:].clone() logits = logits[:, :-1, :] loss_mask = labels != label_pad_token_id # dummy token; we'll ignore the losses on these tokens later labels[labels == label_pad_token_id] = 0 per_token_logps = selective_log_softmax(logits, labels) if average_log_prob: return (per_token_logps * loss_mask).sum(-1) / loss_mask.sum(-1) else: return (per_token_logps * loss_mask).sum(-1) def concatenated_forward( self, model: nn.Module, batch: dict[str, Union[list, torch.LongTensor]] ) -> tuple[torch.FloatTensor, torch.FloatTensor, torch.FloatTensor, torch.FloatTensor]: """Run the given model on the given batch of inputs, concatenating the chosen and rejected inputs together. We do this to avoid doing two forward passes, because it's faster for FSDP. """ concatenated_batch = self.concatenated_inputs( batch, is_encoder_decoder=self.is_encoder_decoder, label_pad_token_id=self.label_pad_token_id, padding_value=self.padding_value, device=self.accelerator.device, ) len_chosen = batch["chosen_labels"].shape[0] model_kwargs = ( { "decoder_input_ids": self._shift_right(concatenated_batch["concatenated_labels"]), } if self.is_encoder_decoder else {} ) if self.aux_loss_enabled: model_kwargs["output_router_logits"] = True outputs = model( concatenated_batch["concatenated_input_ids"], attention_mask=concatenated_batch["concatenated_attention_mask"], use_cache=False, **model_kwargs, ) all_logits = outputs.logits def cross_entropy_loss(logits, labels): if not self.is_encoder_decoder: # Shift so that tokens < n predict n logits = logits[..., :-1, :].contiguous() labels = labels[..., 1:].contiguous() # Flatten the tokens loss_fct = nn.CrossEntropyLoss() logits = logits.view(-1, logits.shape[-1]) labels = labels.view(-1) # Enable model parallelism labels = labels.to(logits.device) loss = loss_fct(logits, labels) return loss labels = concatenated_batch["concatenated_labels"].clone() if self.cpo_alpha == 0: nll_loss = torch.tensor(0.0).to(self.accelerator.device) else: nll_loss = cross_entropy_loss(all_logits[:len_chosen], labels[:len_chosen]) all_logps = self.get_batch_logps( all_logits, concatenated_batch["concatenated_labels"], average_log_prob=self.loss_type in ["ipo", "simpo"], is_encoder_decoder=self.is_encoder_decoder, label_pad_token_id=self.label_pad_token_id, ) chosen_logps = all_logps[:len_chosen] rejected_logps = all_logps[len_chosen:] chosen_logits = all_logits[:len_chosen] rejected_logits = all_logits[len_chosen:] if self.aux_loss_enabled: return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, nll_loss, outputs.aux_loss) return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, nll_loss) def get_batch_loss_metrics( self, model, batch: dict[str, Union[list, torch.LongTensor]], train_eval: Literal["train", "eval"] = "train", ): """Compute the CPO loss and other metrics for the given batch of inputs for train or test.""" metrics = {} forward_output = self.concatenated_forward(model, batch) ( policy_chosen_logps, policy_rejected_logps, policy_chosen_logits, policy_rejected_logits, policy_nll_loss, ) = forward_output[:5] if self.aux_loss_enabled: aux_loss = forward_output[5] losses, chosen_rewards, rejected_rewards = self.cpo_loss( policy_chosen_logps, policy_rejected_logps, ) loss = losses.mean() + self.cpo_alpha * policy_nll_loss reward_accuracies = (chosen_rewards > rejected_rewards).float() prefix = "eval_" if train_eval == "eval" else "" metrics[f"{prefix}rewards/chosen"] = self.accelerator.gather_for_metrics(chosen_rewards).mean().item() metrics[f"{prefix}rewards/rejected"] = self.accelerator.gather_for_metrics(rejected_rewards).mean().item() metrics[f"{prefix}rewards/accuracies"] = self.accelerator.gather_for_metrics(reward_accuracies).mean().item() metrics[f"{prefix}rewards/margins"] = ( self.accelerator.gather_for_metrics(chosen_rewards - rejected_rewards).mean().item() ) metrics[f"{prefix}logps/rejected"] = ( self.accelerator.gather_for_metrics(policy_rejected_logps).detach().mean().item() ) metrics[f"{prefix}logps/chosen"] = ( self.accelerator.gather_for_metrics(policy_chosen_logps).detach().mean().item() ) metrics[f"{prefix}logits/rejected"] = ( self.accelerator.gather_for_metrics(policy_rejected_logits.detach().mean()).mean().item() ) metrics[f"{prefix}logits/chosen"] = ( self.accelerator.gather_for_metrics(policy_chosen_logits.detach().mean()).mean().item() ) metrics[f"{prefix}nll_loss"] = self.accelerator.gather_for_metrics(policy_nll_loss).detach().mean().item() if self.aux_loss_enabled: loss += self.aux_loss_coef * aux_loss return loss, metrics def compute_loss( self, model: Union[PreTrainedModel, nn.Module], inputs: dict[str, Union[torch.Tensor, Any]], return_outputs=False, num_items_in_batch=None, ) -> Union[torch.Tensor, tuple[torch.Tensor, dict[str, torch.Tensor]]]: compute_loss_context_manager = ( autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext() ) with compute_loss_context_manager: loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="train") # force log the metrics self.store_metrics(metrics, train_eval="train") if return_outputs: return (loss, metrics) return loss def generate_from_model(self, model, batch: dict[str, torch.LongTensor]) -> str: """Generate samples from the model and reference model for the given batch of inputs.""" # If one uses `generate_during_eval` with peft + bf16, we need to explicitly call generate with # the torch amp context manager as some hidden states are silently casted to full precision. generate_context_manager = ( autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext() ) with generate_context_manager: policy_output = model.generate( input_ids=batch["prompt_input_ids"], attention_mask=batch["prompt_attention_mask"], max_length=self.max_length, do_sample=True, pad_token_id=self.processing_class.pad_token_id, ) policy_output = pad_to_length(policy_output, self.max_length, self.processing_class.pad_token_id) policy_output_decoded = self.processing_class.batch_decode(policy_output, skip_special_tokens=True) return policy_output_decoded def prediction_step( self, model: Union[PreTrainedModel, nn.Module], inputs: dict[str, Union[torch.Tensor, Any]], prediction_loss_only: bool, ignore_keys: Optional[list[str]] = None, ): if ignore_keys is None: if hasattr(model, "config"): ignore_keys = getattr(model.config, "keys_to_ignore_at_inference", []) else: ignore_keys = [] prediction_context_manager = ( autocast(self.accelerator.device.type) if self._peft_has_been_casted_to_bf16 else nullcontext() ) with torch.no_grad(), prediction_context_manager: loss, metrics = self.get_batch_loss_metrics(model, inputs, train_eval="eval") # force log the metrics self.store_metrics(metrics, train_eval="eval") if prediction_loss_only: return (loss.detach(), None, None) # logits for the chosen and rejected samples from model logits_dict = { "eval_logits/chosen": metrics["eval_logits/chosen"], "eval_logits/rejected": metrics["eval_logits/rejected"], } logits = [v for k, v in logits_dict.items() if k not in ignore_keys] logits = torch.tensor(logits, device=self.accelerator.device) labels = torch.zeros(logits.shape[0], device=self.accelerator.device) return (loss.detach(), logits, labels) def store_metrics(self, metrics: dict[str, float], train_eval: Literal["train", "eval"] = "train") -> None: for key, value in metrics.items(): self._stored_metrics[train_eval][key].append(value) def evaluation_loop( self, dataloader: DataLoader, description: str, prediction_loss_only: Optional[bool] = None, ignore_keys: Optional[list[str]] = None, metric_key_prefix: str = "eval", ) -> EvalLoopOutput: """ Overriding built-in evaluation loop to store metrics for each batch. Prediction/evaluation loop, shared by `Trainer.evaluate()` and `Trainer.predict()`. Works both with or without labels. """ # Sample and save to game log if requested (for one batch to save time) if self.generate_during_eval: # Generate random indices within the range of the total number of samples num_samples = len(dataloader.dataset) random_indices = random.sample(range(num_samples), k=self.args.eval_batch_size) # Use dataloader.dataset.select to get the random batch without iterating over the DataLoader random_batch_dataset = dataloader.dataset.select(random_indices) random_batch = self.data_collator(random_batch_dataset) random_batch = self._prepare_inputs(random_batch) policy_output_decoded = self.generate_from_model(self.model, random_batch) table = pd.DataFrame( columns=["Prompt", "Policy"], data=[ [prompt, pol[len(prompt) :]] for prompt, pol in zip(random_batch["prompt"], policy_output_decoded) ], ) if "wandb" in self.args.report_to: wandb.log({"game_log": wandb.Table(data=table)}) if "comet_ml" in self.args.report_to: log_table_to_comet_experiment( name="game_log.csv", table=table, ) # Base evaluation initial_output = super().evaluation_loop( dataloader, description, prediction_loss_only, ignore_keys, metric_key_prefix ) return initial_output def log(self, logs: dict[str, float], start_time: Optional[float] = None) -> None: """ Log `logs` on the various objects watching training, including stored metrics. Args: logs (`dict[str, float]`): The values to log. start_time (`float` or `None`, *optional*, defaults to `None`): Start time of the training. """ # logs either has 'loss' or 'eval_loss' train_eval = "train" if "loss" in logs else "eval" # Add averaged stored metrics to logs for key, metrics in self._stored_metrics[train_eval].items(): logs[key] = torch.tensor(metrics).mean().item() del self._stored_metrics[train_eval] return super().log(logs, start_time) def _shift_right(self, input_ids): if self.decoder_start_token_id is None: raise ValueError( "model.config.decoder_start_token_id has to be defined. It is usually set to the pad_token_id." ) # shift inputs to the right if is_torch_fx_proxy(input_ids): # Item assignment is not supported natively for proxies. shifted_input_ids = torch.full(input_ids.shape[:-1] + (1,), self.decoder_start_token_id) shifted_input_ids = torch.cat([shifted_input_ids, input_ids[..., :-1]], dim=-1) else: shifted_input_ids = input_ids.new_zeros(input_ids.shape) shifted_input_ids[..., 1:] = input_ids[..., :-1].clone() shifted_input_ids[..., 0] = self.decoder_start_token_id if self.pad_token_id is None: raise ValueError("model.config.pad_token_id has to be defined.") # replace possible -100 values in labels by `pad_token_id` shifted_input_ids.masked_fill_(shifted_input_ids == -100, self.pad_token_id) return shifted_input_ids # 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{xu2024contrastive, title = {{Contrastive Preference Optimization: Pushing the Boundaries of LLM Performance in Machine Translation}}, author = {Haoran Xu and Amr Sharaf and Yunmo Chen and Weiting Tan and Lingfeng Shen and Benjamin Van Durme and Kenton Murray and Young Jin Kim}, year = 2024, booktitle = {Forty-first International Conference on Machine Learning, {ICML} 2024, Vienna, Austria, July 21-27, 2024}, publisher = {OpenReview.net}, url = {https://openreview.net/forum?id=51iwkioZpn} }""") 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="CPO", trainer_citation=citation, paper_title="Contrastive Preference Optimization: Pushing the Boundaries of LLM Performance in Machine Translation", paper_id="2401.08417", ) model_card.save(os.path.join(self.args.output_dir, "README.md"))
trl/trl/trainer/cpo_trainer.py/0
{ "file_path": "trl/trl/trainer/cpo_trainer.py", "repo_id": "trl", "token_count": 23609 }
600
# 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 typing import Any, Callable, Optional, Union import jinja2 import torch import torch.nn as nn import torch.nn.functional as F from datasets import Dataset, IterableDataset from transformers import ( BaseImageProcessor, FeatureExtractionMixin, PreTrainedModel, PreTrainedTokenizerBase, ProcessorMixin, TrainerCallback, is_wandb_available, ) from transformers.trainer_utils import EvalPrediction from transformers.training_args import OptimizerNames from transformers.utils import is_apex_available, is_peft_available from ..data_utils import is_conversational, maybe_apply_chat_template from ..models.modeling_base import GeometricMixtureWrapper from ..models.utils import unwrap_model_for_generation from .judges import BasePairwiseJudge from .nash_md_config import NashMDConfig from .online_dpo_trainer import OnlineDPOTrainer from .utils import ( SIMPLE_CHAT_TEMPLATE, empty_cache, generate_model_card, get_comet_experiment_url, get_reward, selective_log_softmax, truncate_right, ) if is_apex_available(): from apex import amp if is_wandb_available(): import wandb if is_peft_available(): from peft import PeftModel class NashMDTrainer(OnlineDPOTrainer): r""" Initialize NashMDTrainer as a subclass of [`OnlineDPOConfig`]. Args: model (`transformers.PreTrainedModel`): The model to train, preferably an `AutoModelForCausalLM`. ref_model (`PreTrainedModelWrapper`): Hugging Face transformer model with a casual language modelling head. Used for implicit reward computation and loss. If no reference model is provided, the trainer will create a reference model with the same architecture as the model to be optimized. reward_model (`transformers.PreTrainedModel`): The reward model to score completions with, preferably an `AutoModelForSequenceClassification`. judge (`BasePairwiseJudge`): The judge to use for pairwise comparison of model completions. args (`NashMDConfig`): The NashMD 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", "nash-md"] def __init__( self, model: Union[PreTrainedModel, nn.Module] = None, ref_model: Union[PreTrainedModel, nn.Module] = None, reward_model: Union[PreTrainedModel, nn.Module, None] = None, judge: Optional[BasePairwiseJudge] = None, args: Optional[NashMDConfig] = None, data_collator: Optional[Callable] = None, train_dataset: Optional[Union[Dataset, IterableDataset]] = None, eval_dataset: Optional[Union[Dataset, dict[str, Dataset]]] = None, processing_class: Optional[ Union[PreTrainedTokenizerBase, BaseImageProcessor, FeatureExtractionMixin, ProcessorMixin] ] = 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: super().__init__( model=model, ref_model=ref_model, reward_model=reward_model, judge=judge, args=args, data_collator=data_collator, train_dataset=train_dataset, eval_dataset=eval_dataset, processing_class=processing_class, reward_processing_class=processing_class, # for now, NashMDTrainer can't use any reward model peft_config=peft_config, compute_metrics=compute_metrics, callbacks=callbacks, optimizers=optimizers, preprocess_logits_for_metrics=preprocess_logits_for_metrics, ) self._mixture_coef = self.args.mixture_coef # Overwrite the stats dictionary to include NashMD specific statistics self.stats = { # Remove "non_score_reward", "rlhf_reward", "scores_margin" # Add "mixture_coef" "loss/kl": [], "objective/entropy": [], "loss/score": [], "rewards/probabilities": [], "rewards/accuracies": [], "rewards/margins": [], "logps/chosen": [], "logps/rejected": [], "val/model_contain_eos_token": [], "val/ref_contain_eos_token": [], "beta": [], "mixture_coef": [], } if self.reward_model is not None: self.stats["rewards/chosen"] = [] self.stats["rewards/rejected"] = [] @property def mixture_coef(self): if isinstance(self._mixture_coef, list): epoch = self.state.epoch return self._mixture_coef[epoch] if epoch < len(self._mixture_coef) else self._mixture_coef[-1] else: return self._mixture_coef def _generate_completions(self, model, prompts): # Generate completions from the policy model. with unwrap_model_for_generation(model, self.accelerator) as unwrapped_policy_for_gen_ctx: model_output = unwrapped_policy_for_gen_ctx.generate( input_ids=prompts["input_ids"], attention_mask=prompts["attention_mask"], generation_config=self.generation_config, ) # Get the DDP/FSDP unwrapped version of the main model. # This will be the policy model for GeometricMixtureWrapper (PEFT adapters active if PEFT is used). policy_model_for_gmw = self.accelerator.unwrap_model(model) # Determine the correct reference model for GeometricMixtureWrapper. # This also needs to be DDP/FSDP unwrapped. ref_model_for_gmw: torch.nn.Module if self.ref_model is None: # No explicit ref_model is provided. # Use the base of the main `model` if it's a PEFT model. # policy_model_for_gmw is already DDP-unwrapped. if is_peft_available() and isinstance(policy_model_for_gmw, PeftModel): ref_model_for_gmw = policy_model_for_gmw.get_base_model() else: # Not a PEFT model (or PEFT not available), or already a base model. # Use the DDP-unwrapped policy model itself as the reference. ref_model_for_gmw = policy_model_for_gmw else: # An explicit ref_model is provided. Unwrap it for DDP/FSDP. ref_model_for_gmw = self.accelerator.unwrap_model(self.ref_model) # Both models given to GeometricMixtureWrapper (policy_model_for_gmw and ref_model_for_gmw) are DDP-unwrapped. with torch.no_grad(): # Ensure no_grad context for mixture model generation mixture_model = GeometricMixtureWrapper( model=policy_model_for_gmw, ref_model=ref_model_for_gmw, generation_config=self.generation_config, mixture_coef=self.mixture_coef, device=self.accelerator.device, ) mixture_output = mixture_model.generate( input_ids=prompts["input_ids"], attention_mask=prompts["attention_mask"], generation_config=self.generation_config, ) return model_output, mixture_output def _process_completions(self, model_output, mixture_output, prompts): context_length = prompts["input_ids"].shape[1] # Process model completions model_completion_ids = model_output[:, context_length:] model_completion_ids, model_completion_mask = truncate_right( model_completion_ids, self.processing_class.eos_token_id, self.processing_class.pad_token_id ) model_data = { "input_ids": torch.cat((prompts["input_ids"], model_completion_ids), dim=1), "attention_mask": torch.cat((prompts["attention_mask"], model_completion_mask), dim=1), "raw": prompts["raw"], } # Process reference model completions mixture_completion_ids = mixture_output[:, context_length:] mixture_completion_ids, mixture_completion_mask = truncate_right( mixture_completion_ids, self.processing_class.eos_token_id, self.processing_class.pad_token_id ) mixture_data = { "input_ids": torch.cat((prompts["input_ids"], mixture_completion_ids), dim=1), "attention_mask": torch.cat((prompts["attention_mask"], mixture_completion_mask), dim=1), "raw": prompts["raw"], } return model_data, mixture_data def _compute_rewards(self, model_data, mixture_data, context_length): with torch.no_grad(): _, model_scores, _ = get_reward( self.reward_model, model_data["input_ids"], self.processing_class.pad_token_id, context_length ) _, mixture_scores, _ = get_reward( self.reward_model, mixture_data["input_ids"], self.processing_class.pad_token_id, context_length ) # Apply EOS penalty if needed if self.args.missing_eos_penalty is not None: model_contain_eos = torch.any(model_data["input_ids"] == self.processing_class.eos_token_id, dim=-1) mixture_contain_eos = torch.any(mixture_data["input_ids"] == self.processing_class.eos_token_id, dim=-1) model_scores[~model_contain_eos] -= self.args.missing_eos_penalty mixture_scores[~mixture_contain_eos] -= self.args.missing_eos_penalty return model_scores, mixture_scores def _compute_judge(self, model_data, mixture_data, context_length): prompts = model_data["raw"] model_data_completions = self.processing_class.batch_decode( model_data["input_ids"][:, context_length:], skip_special_tokens=True ) model_data_completions = [completion.strip() for completion in model_data_completions] mixture_data_completions = self.processing_class.batch_decode( mixture_data["input_ids"][:, context_length:], skip_special_tokens=True ) mixture_data_completions = [completion.strip() for completion in mixture_data_completions] if is_conversational({"prompt": prompts[0]}): model_data_completions = [ [{"role": "assistant", "content": completion}] for completion in model_data_completions ] environment = jinja2.Environment() template = environment.from_string(SIMPLE_CHAT_TEMPLATE) prompts = [template.render(messages=message) for message in prompts] model_data_completions = [template.render(messages=completion) for completion in model_data_completions] mixture_data_completions = [ [{"role": "assistant", "content": completion}] for completion in mixture_data_completions ] mixture_data_completions = [ template.render(messages=completion) for completion in mixture_data_completions ] probability = self.judge.judge( prompts, list(zip(model_data_completions, mixture_data_completions)), return_scores=True, ) return torch.tensor(probability, device=model_data["input_ids"].device) def _compute_logprobs(self, model, model_data, context_length): def compute_logprobs_for_data(m, data): output = m(data["input_ids"], attention_mask=data["attention_mask"]) logits = output.logits[:, context_length - 1 : -1] token_logprobs = selective_log_softmax(logits, data["input_ids"][:, context_length:]) return token_logprobs # Compute logprobs for model completions under the model model_logprobs_model_data = compute_logprobs_for_data(model, model_data) # Compute logprobs of model completions under the reference model with torch.no_grad(): if self.ref_model is None: with model.disable_adapter(): ref_logprobs_model_data = compute_logprobs_for_data(model, model_data) else: ref_logprobs_model_data = compute_logprobs_for_data(self.ref_model, model_data) # Mask padding tokens model_padding_mask = model_data["attention_mask"][:, context_length:] == 0 model_logprobs_model_data = model_logprobs_model_data.masked_fill(model_padding_mask, 0.0) ref_logprobs_model_data = ref_logprobs_model_data.masked_fill(model_padding_mask, 0.0) return (model_logprobs_model_data, ref_logprobs_model_data) def _compute_losses( self, model_logprobs_model_data, ref_logprobs_model_data, probability, ): # reinforce score where 0.5 is a control variate score = (probability - 0.5) * model_logprobs_model_data.sum(1) # kl divergence via reinforce with torch.no_grad(): log_ratio = model_logprobs_model_data - ref_logprobs_model_data kl_div_log = log_ratio.sum(1) kl_div_loss = (log_ratio * model_logprobs_model_data).sum(1) # final loss loss = self.beta * kl_div_loss - score return loss.mean(), score, kl_div_log def _log_statistics( self, model_data, mixture_data, model_logprobs_model_data, ref_logprobs_model_data, probability, score, kl_div, context_length, model_scores=None, mixture_scores=None, ): # Helper function to gather and compute mean def gather_mean(tensor): return self.accelerator.gather_for_metrics(tensor).mean().item() # Log score self.stats["loss/score"].append(gather_mean(score)) # Log KL divergence self.stats["loss/kl"].append(gather_mean(kl_div)) # Log logprobs model_logprobs_model_data_sum = model_logprobs_model_data.sum(1) ref_logprobs_model_data_sum = ref_logprobs_model_data.sum(1) self.stats["logps/chosen"].append(gather_mean(model_logprobs_model_data_sum)) self.stats["logps/rejected"].append(gather_mean(ref_logprobs_model_data_sum)) # Log rewards if self.reward_model is not None: self.stats["rewards/chosen"].append(gather_mean(model_scores)) self.stats["rewards/rejected"].append(gather_mean(mixture_scores)) # Log probabilities self.stats["rewards/probabilities"].append(gather_mean(probability)) # Calculate entropy for model data entropy_model_data = -model_logprobs_model_data.sum(1) self.stats["objective/entropy"].append(gather_mean(entropy_model_data)) # Calculate margins margin = model_logprobs_model_data_sum - ref_logprobs_model_data_sum self.stats["rewards/margins"].append(gather_mean(margin)) # Calculate accuracy accuracy = (margin > 0).float() self.stats["rewards/accuracies"].append(gather_mean(accuracy)) # Log EOS token statistics model_eos = (model_data["input_ids"][:, context_length:] == self.processing_class.eos_token_id).any(dim=1) mixture_eos = (mixture_data["input_ids"][:, context_length:] == self.processing_class.eos_token_id).any(dim=1) self.stats["val/model_contain_eos_token"].append(gather_mean(model_eos.float())) self.stats["val/ref_contain_eos_token"].append(gather_mean(mixture_eos.float())) # Log beta and mixture coef self.stats["beta"].append(self.beta) self.stats["mixture_coef"].append(self.mixture_coef) 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() # Apply chat template and tokenize the input batch_size = len(next(iter(inputs.values()))) prompts = inputs["prompt"] inputs = [{k: v[i] for k, v in inputs.items()} for i in range(batch_size)] inputs = [maybe_apply_chat_template(x, self.processing_class) for x in inputs] inputs = [self.tokenize_row(x, self.model.config.is_encoder_decoder, self.processing_class) for x in inputs] inputs = self.data_collator(inputs) # need the prompt_ only inputs = self._prepare_inputs(inputs) context_length = inputs["prompt_input_ids"].shape[1] prompts = { "input_ids": inputs["prompt_input_ids"], "attention_mask": inputs["prompt_attention_mask"], "raw": prompts, } del inputs # Sample completions from both the model and the reference model model_output, mixture_output = self._generate_completions(model, prompts) # Process model completions model_data, mixture_data = self._process_completions(model_output, mixture_output, prompts) # Compute rewards if self.reward_model is not None: model_scores, mixture_scores = self._compute_rewards(model_data, mixture_data, context_length) # probability of the model data vs the mixture data probability = F.sigmoid(model_scores - mixture_scores) else: model_scores, mixture_scores = None, None probability = self._compute_judge(model_data, mixture_data, context_length) # Compute logprobs model_logprobs_model_data, ref_logprobs_model_data = self._compute_logprobs(model, model_data, context_length) # Compute loss loss, score, kl_div = self._compute_losses(model_logprobs_model_data, ref_logprobs_model_data, probability) # Log everything self._log_statistics( model_data, mixture_data, model_logprobs_model_data.detach(), ref_logprobs_model_data, probability, score.detach(), kl_div.detach(), context_length, model_scores, mixture_scores, ) 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 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{munos2024nash, title = {{Nash Learning from Human Feedback}}, author = {R{\'{e}}mi Munos and Michal Valko and Daniele Calandriello and Mohammad Gheshlaghi Azar and Mark Rowland and Zhaohan Daniel Guo and Yunhao Tang and Matthieu Geist and Thomas Mesnard and C{\\^{o}}me Fiegel and Andrea Michi and Marco Selvi and Sertan Girgin and Nikola Momchev and Olivier Bachem and Daniel J. Mankowitz and Doina Precup and Bilal Piot}, year = 2024, booktitle = {Forty-first International Conference on Machine Learning, {ICML} 2024, Vienna, Austria, July 21-27, 2024}, publisher = {OpenReview.net}, url = {https://openreview.net/forum?id=Y5AmNYiyCQ} }""") 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="Nash-MD", trainer_citation=citation, paper_title="Nash Learning from Human Feedback", paper_id="2312.00886", ) model_card.save(os.path.join(self.args.output_dir, "README.md"))
trl/trl/trainer/nash_md_trainer.py/0
{ "file_path": "trl/trl/trainer/nash_md_trainer.py", "repo_id": "trl", "token_count": 10493 }
601
# 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 trl.trainer.online_dpo_config import OnlineDPOConfig @dataclass class XPOConfig(OnlineDPOConfig): r""" Configuration class for the [`XPOTrainer`]. Subclass of [`OnlineDPOConfig`] we can use all its arguments and add the following: Parameters: alpha (`float` or `list[float]`, *optional*, defaults to `1e-5`): Weight of the XPO loss term. If a list of floats is provided then the alpha is selected for each new epoch and the last alpha is used for the rest of the epochs. """ alpha: list[float] = field( default_factory=lambda: [1e-5], metadata={ "help": "Weight of the XPO loss term. If a list of floats is provided then the alpha is selected for each " "new epoch and the last alpha is used for the rest of the epochs." }, ) def __post_init__(self): super().__post_init__() if hasattr(self.alpha, "__len__") and len(self.alpha) == 1: self.alpha = self.alpha[0]
trl/trl/trainer/xpo_config.py/0
{ "file_path": "trl/trl/trainer/xpo_config.py", "repo_id": "trl", "token_count": 569 }
602
import os import sys import re from huggingface_hub import InferenceClient # Get the directory containing the current script script_dir = os.path.dirname(os.path.abspath(__file__)) default_inp_dir = os.path.join(script_dir, '..', 'units/en') default_model = "deepseek-ai/DeepSeek-R1" default_client = InferenceClient( provider="together", # api_key is read from the environment ) def auto_translate( output_lang: str, prompt: callable, inp_dir: str = default_inp_dir, model: str = default_model, client: InferenceClient = default_client ): get_output_path = lambda x: x.replace('/en', f'/{output_lang}') escape_special_tokens = lambda x: x.replace('<think>', '<%%think%%>').replace('</think>', '<%%/think%%>') unescape_special_tokens = lambda x: x.replace('<%%think%%>', '<think>').replace('<%%/think%%>', '</think>') # Get the list of all files in the directory, recursively inp_files: list[str] = [] print('Collecting files...') for root, dirs, files in os.walk(inp_dir): for file in files: if file.endswith('.mdx') or file == "_toctree.yml": fname = os.path.join(root, file) print(' +', fname) inp_files.append(fname) def write_out_file(fpath: str, content: str): base_path = os.path.dirname(fpath) os.makedirs(base_path, exist_ok=True) with open(fpath, 'w', encoding='utf-8') as f: f.write(content) # Read the content of the file and process for i, inp_file in enumerate(inp_files): out_file = get_output_path(inp_file) if os.path.exists(out_file): print(f'[{i+1}/{len(inp_files)}] Skipping file: {inp_file}') continue with open(inp_file, 'r', encoding='utf-8') as f: content: str = f.read() content = escape_special_tokens(content) if content.strip() == "": print(f'[{i+1}/{len(inp_files)}] Skipping empty file: {inp_file}') write_out_file(out_file, "") continue print(f'[{i+1}/{len(inp_files)}] Processing file: {inp_file}') stream = client.chat.completions.create( model=model, temperature=0.0, messages=[ {"role": "user", "content": prompt(content)}, ], stream=True, ) final_text = "" for chunk in stream: print(chunk.choices[0].delta.content, end="") sys.stdout.flush() final_text += chunk.choices[0].delta.content # Optionally filter <think>...</think> reasoning process final_text = final_text.split('</think>').pop().strip() # Write the output to the file final_text = unescape_special_tokens(final_text) write_out_file(out_file, final_text) print() print(f' -> Translated to: {out_file}') print("--" * 20) #break
agents-course/scripts/translation.py/0
{ "file_path": "agents-course/scripts/translation.py", "repo_id": "agents-course", "token_count": 1471 }
0
# Launching Your Pokémon Battle Agent It's now time to battle! ⚡️ ## **Battle the Stream Agent!** If you don't feel like building your own agent, and you're just curious about the battle potential of agents in pokémon. We are hosting an automated livestream on [twitch](https://www.twitch.tv/jofthomas) <iframe src="https://jofthomas-twitch-streaming.hf.space" frameborder="0" width="1200" height="600" ></iframe> To battle the agent in stream you can: Instructions: 1. Go to the **Pokémon Showdown Space**: [Link Here](https://huggingface.co/spaces/Jofthomas/Pokemon_showdown) 2. **Choose Your Name** (Top-right corner). 3. Find the **Current Agent's Username**. Check: * The **Stream Display**: [Link Here](https://www.twitch.tv/jofthomas) 4. **Search** for that username on the Showdown Space and **Send a Battle Invitation**. *Heads Up:* Only one agent is online at once! Make sure you've got the right name. ## Pokémon Battle Agent Challenger If you've created your own Pokémon Battle Agent from the last section, you're probably wondering: **how can I test it against others?** Let's find out! We've built a dedicated [Hugging Face Space](https://huggingface.co/spaces/PShowdown/pokemon_agents) for this purpose: <iframe src="https://pshowdown-pokemon-agents.hf.space" frameborder="0" width="1200" height="600" ></iframe> This Space is connected to our own **Pokémon Showdown server**, where your Agent can take on others in epic AI-powered battles. ### How to Launch Your Agent Follow these steps to bring your Agent to life in the arena: 1. **Duplicate the Space** Click the three dots in the top-right menu of the Space and select “Duplicate this Space”. 2. **Add Your Agent Code to `agent.py`** Open the file and paste your Agent implementation. You can follow this [example](https://huggingface.co/spaces/PShowdown/pokemon_agents/blob/main/agents.py) or check out the [project structure](https://huggingface.co/spaces/PShowdown/pokemon_agents/tree/main) for guidance. 3. **Register Your Agent in `app.py`** Add your Agent’s name and logic to the dropdown menu. Refer to [this snippet](https://huggingface.co/spaces/PShowdown/pokemon_agents/blob/main/app.py) for inspiration. 4. **Select Your Agent** Once added, your Agent will show up in the “Select Agent” dropdown menu. Pick it from the list! ✅ 5. **Enter Your Pokémon Showdown Username** Make sure the username matches the one shown in the iframe’s **"Choose name"** input. You can also connect with your official account. 6. **Click “Send Battle Invitation”** Your Agent will send an invite to the selected opponent. It should appear on-screen! 7. **Accept the Battle & Enjoy the Fight!** Let the battle begin! May the smartest Agent win Ready to see your creation in action? Let the AI showdown commence! 🥊
agents-course/units/en/bonus-unit3/launching_agent_battle.mdx/0
{ "file_path": "agents-course/units/en/bonus-unit3/launching_agent_battle.mdx", "repo_id": "agents-course", "token_count": 867 }
1
# Quick Self-Check (ungraded) [[quiz2]] What?! Another Quiz? We know, we know, ... 😅 But this short, ungraded quiz is here to **help you reinforce key concepts you've just learned**. This quiz covers Large Language Models (LLMs), message systems, and tools; essential components for understanding and building AI agents. ### Q1: Which of the following best describes an AI tool? <Question choices={[ { text: "A process that only generates text responses", explain: "", }, { text: "An executable process or external API that allows agents to perform specific tasks and interact with external environments", explain: "Tools are executable functions that agents can use to perform specific tasks and interact with external environments.", correct: true }, { text: "A feature that stores agent conversations", explain: "", } ]} /> --- ### Q2: How do AI agents use tools as a form of "acting" in an environment? <Question choices={[ { text: "By passively waiting for user instructions", explain: "", }, { text: "By only using pre-programmed responses", explain: "", }, { text: "By asking the LLM to generate tool invocation code when appropriate and running tools on behalf of the model", explain: "Agents can invoke tools and use reasoning to plan and re-plan based on the information gained.", correct: true } ]} /> --- ### Q3: What is a Large Language Model (LLM)? <Question choices={[ { text: "A simple chatbot designed to respond with pre-defined answers", explain: "", }, { text: "A deep learning model trained on large amounts of text to understand and generate human-like language", explain: "", correct: true }, { text: "A rule-based AI that follows strict predefined commands", explain: "", } ]} /> --- ### Q4: Which of the following best describes the role of special tokens in LLMs? <Question choices={[ { text: "They are additional words stored in the model's vocabulary to enhance text generation quality", explain: "", }, { text: "They serve specific functions like marking the end of a sequence (EOS) or separating different message roles in chat models", explain: "", correct: true }, { text: "They are randomly inserted tokens used to improve response variability", explain: "", } ]} /> --- ### Q5: How do AI chat models process user messages internally? <Question choices={[ { text: "They directly interpret messages as structured commands with no transformations", explain: "", }, { text: "They convert user messages into a formatted prompt by concatenating system, user, and assistant messages", explain: "", correct: true }, { text: "They generate responses randomly based on previous conversations", explain: "", } ]} /> --- Got it? Great! Now let's **dive into the complete Agent flow and start building your first AI Agent!**
agents-course/units/en/unit1/quiz2.mdx/0
{ "file_path": "agents-course/units/en/unit1/quiz2.mdx", "repo_id": "agents-course", "token_count": 754 }
2
# What are components in LlamaIndex? Remember Alfred, our helpful butler agent from Unit 1? To assist us effectively, Alfred needs to understand our requests and **prepare, find and use relevant information to help complete tasks.** This is where LlamaIndex's components come in. While LlamaIndex has many components, **we'll focus specifically on the `QueryEngine` component.** Why? Because it can be used as a Retrieval-Augmented Generation (RAG) tool for an agent. So, what is RAG? LLMs are trained on enormous bodies of data to learn general knowledge. However, they may not be trained on relevant and up-to-date data. RAG solves this problem by finding and retrieving relevant information from your data and giving that to the LLM. ![RAG](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/llama-index/rag.png) Now, think about how Alfred works: 1. You ask Alfred to help plan a dinner party 2. Alfred needs to check your calendar, dietary preferences, and past successful menus 3. The `QueryEngine` helps Alfred find this information and use it to plan the dinner party This makes the `QueryEngine` **a key component for building agentic RAG workflows** in LlamaIndex. Just as Alfred needs to search through your household information to be helpful, any agent needs a way to find and understand relevant data. The `QueryEngine` provides exactly this capability. Now, let's dive a bit deeper into the components and see how you can **combine components to create a RAG pipeline.** ## Creating a RAG pipeline using components <Tip> You can follow the code in <a href="https://huggingface.co/agents-course/notebooks/blob/main/unit2/llama-index/components.ipynb" target="_blank">this notebook</a> that you can run using Google Colab. </Tip> There are five key stages within RAG, which in turn will be a part of most larger applications you build. These are: 1. **Loading**: this refers to getting your data from where it lives -- whether it's text files, PDFs, another website, a database, or an API -- into your workflow. LlamaHub provides hundreds of integrations to choose from. 2. **Indexing**: this means creating a data structure that allows for querying the data. For LLMs, this nearly always means creating vector embeddings. Which are numerical representations of the meaning of the data. Indexing can also refer to numerous other metadata strategies to make it easy to accurately find contextually relevant data based on properties. 3. **Storing**: once your data is indexed you will want to store your index, as well as other metadata, to avoid having to re-index it. 4. **Querying**: for any given indexing strategy there are many ways you can utilize LLMs and LlamaIndex data structures to query, including sub-queries, multi-step queries and hybrid strategies. 5. **Evaluation**: a critical step in any flow is checking how effective it is relative to other strategies, or when you make changes. Evaluation provides objective measures of how accurate, faithful and fast your responses to queries are. Next, let's see how we can reproduce these stages using components. ### Loading and embedding documents As mentioned before, LlamaIndex can work on top of your own data, however, **before accessing data, we need to load it.** There are three main ways to load data into LlamaIndex: 1. `SimpleDirectoryReader`: A built-in loader for various file types from a local directory. 2. `LlamaParse`: LlamaParse, LlamaIndex's official tool for PDF parsing, available as a managed API. 3. `LlamaHub`: A registry of hundreds of data-loading libraries to ingest data from any source. <Tip>Get familiar with <a href="https://docs.llamaindex.ai/en/stable/module_guides/loading/connector/">LlamaHub</a> loaders and <a href="https://github.com/run-llama/llama_cloud_services/blob/main/parse.md">LlamaParse</a> parser for more complex data sources.</Tip> **The simplest way to load data is with `SimpleDirectoryReader`.** This versatile component can load various file types from a folder and convert them into `Document` objects that LlamaIndex can work with. Let's see how we can use `SimpleDirectoryReader` to load data from a folder. ```python from llama_index.core import SimpleDirectoryReader reader = SimpleDirectoryReader(input_dir="path/to/directory") documents = reader.load_data() ``` After loading our documents, we need to break them into smaller pieces called `Node` objects. A `Node` is just a chunk of text from the original document that's easier for the AI to work with, while it still has references to the original `Document` object. The `IngestionPipeline` helps us create these nodes through two key transformations. 1. `SentenceSplitter` breaks down documents into manageable chunks by splitting them at natural sentence boundaries. 2. `HuggingFaceEmbedding` converts each chunk into numerical embeddings - vector representations that capture the semantic meaning in a way AI can process efficiently. This process helps us organise our documents in a way that's more useful for searching and analysis. ```python from llama_index.core import Document from llama_index.embeddings.huggingface import HuggingFaceEmbedding from llama_index.core.node_parser import SentenceSplitter from llama_index.core.ingestion import IngestionPipeline # create the pipeline with transformations pipeline = IngestionPipeline( transformations=[ SentenceSplitter(chunk_overlap=0), HuggingFaceEmbedding(model_name="BAAI/bge-small-en-v1.5"), ] ) nodes = await pipeline.arun(documents=[Document.example()]) ``` ### Storing and indexing documents After creating our `Node` objects we need to index them to make them searchable, but before we can do that, we need a place to store our data. Since we are using an ingestion pipeline, we can directly attach a vector store to the pipeline to populate it. In this case, we will use `Chroma` to store our documents. <details> <summary>Install ChromaDB</summary> As introduced in the <a href="./llama-hub">section on the LlamaHub</a>, we can install the ChromaDB vector store with the following command: ```bash pip install llama-index-vector-stores-chroma ``` </details> ```python import chromadb from llama_index.vector_stores.chroma import ChromaVectorStore db = chromadb.PersistentClient(path="./alfred_chroma_db") chroma_collection = db.get_or_create_collection("alfred") vector_store = ChromaVectorStore(chroma_collection=chroma_collection) pipeline = IngestionPipeline( transformations=[ SentenceSplitter(chunk_size=25, chunk_overlap=0), HuggingFaceEmbedding(model_name="BAAI/bge-small-en-v1.5"), ], vector_store=vector_store, ) ``` <Tip>An overview of the different vector stores can be found in the <a href="https://docs.llamaindex.ai/en/stable/module_guides/storing/vector_stores/">LlamaIndex documentation</a>.</Tip> This is where vector embeddings come in - by embedding both the query and nodes in the same vector space, we can find relevant matches. The `VectorStoreIndex` handles this for us, using the same embedding model we used during ingestion to ensure consistency. Let's see how to create this index from our vector store and embeddings: ```python from llama_index.core import VectorStoreIndex from llama_index.embeddings.huggingface import HuggingFaceEmbedding embed_model = HuggingFaceEmbedding(model_name="BAAI/bge-small-en-v1.5") index = VectorStoreIndex.from_vector_store(vector_store, embed_model=embed_model) ``` All information is automatically persisted within the `ChromaVectorStore` object and the passed directory path. Great! Now that we can save and load our index easily, let's explore how to query it in different ways. ### Querying a VectorStoreIndex with prompts and LLMs Before we can query our index, we need to convert it to a query interface. The most common conversion options are: - `as_retriever`: For basic document retrieval, returning a list of `NodeWithScore` objects with similarity scores - `as_query_engine`: For single question-answer interactions, returning a written response - `as_chat_engine`: For conversational interactions that maintain memory across multiple messages, returning a written response using chat history and indexed context We'll focus on the query engine since it is more common for agent-like interactions. We also pass in an LLM to the query engine to use for the response. ```python from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI llm = HuggingFaceInferenceAPI(model_name="Qwen/Qwen2.5-Coder-32B-Instruct") query_engine = index.as_query_engine( llm=llm, response_mode="tree_summarize", ) query_engine.query("What is the meaning of life?") # The meaning of life is 42 ``` ### Response Processing Under the hood, the query engine doesn't only use the LLM to answer the question but also uses a `ResponseSynthesizer` as a strategy to process the response. Once again, this is fully customisable but there are three main strategies that work well out of the box: - `refine`: create and refine an answer by sequentially going through each retrieved text chunk. This makes a separate LLM call per Node/retrieved chunk. - `compact` (default): similar to refining but concatenating the chunks beforehand, resulting in fewer LLM calls. - `tree_summarize`: create a detailed answer by going through each retrieved text chunk and creating a tree structure of the answer. <Tip>Take fine-grained control of your query workflows with the <a href="https://docs.llamaindex.ai/en/stable/module_guides/deploying/query_engine/usage_pattern/#low-level-composition-api">low-level composition API</a>. This API lets you customize and fine-tune every step of the query process to match your exact needs, which also pairs great with <a href="https://docs.llamaindex.ai/en/stable/module_guides/workflow/">Workflows</a> </Tip> The language model won't always perform in predictable ways, so we can't be sure that the answer we get is always correct. We can deal with this by **evaluating the quality of the answer**. ### Evaluation and observability LlamaIndex provides **built-in evaluation tools to assess response quality.** These evaluators leverage LLMs to analyze responses across different dimensions. Let's look at the three main evaluators available: - `FaithfulnessEvaluator`: Evaluates the faithfulness of the answer by checking if the answer is supported by the context. - `AnswerRelevancyEvaluator`: Evaluate the relevance of the answer by checking if the answer is relevant to the question. - `CorrectnessEvaluator`: Evaluate the correctness of the answer by checking if the answer is correct. <Tip>Want to learn more about agent observability and evaluation? Continue your journey with the <a href="https://huggingface.co/learn/agents-course/bonus-unit2/introduction">Bonus Unit 2</a>.</Tip> ```python from llama_index.core.evaluation import FaithfulnessEvaluator query_engine = # from the previous section llm = # from the previous section # query index evaluator = FaithfulnessEvaluator(llm=llm) response = query_engine.query( "What battles took place in New York City in the American Revolution?" ) eval_result = evaluator.evaluate_response(response=response) eval_result.passing ``` Even without direct evaluation, we can **gain insights into how our system is performing through observability.** This is especially useful when we are building more complex workflows and want to understand how each component is performing. <details> <summary>Install LlamaTrace</summary> As introduced in the <a href="./llama-hub">section on the LlamaHub</a>, we can install the LlamaTrace callback from Arize Phoenix with the following command: ```bash pip install -U llama-index-callbacks-arize-phoenix ``` Additionally, we need to set the `PHOENIX_API_KEY` environment variable to our LlamaTrace API key. We can get this by: - Creating an account at [LlamaTrace](https://llamatrace.com/login) - Generating an API key in your account settings - Using the API key in the code below to enable tracing </details> ```python import llama_index import os PHOENIX_API_KEY = "<PHOENIX_API_KEY>" os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = f"api_key={PHOENIX_API_KEY}" llama_index.core.set_global_handler( "arize_phoenix", endpoint="https://llamatrace.com/v1/traces" ) ``` <Tip>Want to learn more about components and how to use them? Continue your journey with the <a href="https://docs.llamaindex.ai/en/stable/module_guides/">Components Guides</a> or the <a href="https://docs.llamaindex.ai/en/stable/understanding/rag/">Guide on RAG</a>.</Tip> We have seen how to use components to create a `QueryEngine`. Now, let's see how we can **use the `QueryEngine` as a tool for an agent!**
agents-course/units/en/unit2/llama-index/components.mdx/0
{ "file_path": "agents-course/units/en/unit2/llama-index/components.mdx", "repo_id": "agents-course", "token_count": 3527 }
3
<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/unit2/smolagents/tool_calling_agents.ipynb"}, ]} askForHelpUrl="http://hf.co/join/discord" /> # Writing actions as code snippets or JSON blobs <Tip> You can follow the code in <a href="https://huggingface.co/agents-course/notebooks/blob/main/unit2/smolagents/tool_calling_agents.ipynb" target="_blank">this notebook</a> that you can run using Google Colab. </Tip> Tool Calling Agents are the second type of agent available in `smolagents`. Unlike Code Agents that use Python snippets, these agents **use the built-in tool-calling capabilities of LLM providers** to generate tool calls as **JSON structures**. This is the standard approach used by OpenAI, Anthropic, and many other providers. Let's look at an example. When Alfred wants to search for catering services and party ideas, a `CodeAgent` would generate and run Python code like this: ```python for query in [ "Best catering services in Gotham City", "Party theme ideas for superheroes" ]: print(web_search(f"Search for: {query}")) ``` A `ToolCallingAgent` would instead create a JSON structure: ```python [ {"name": "web_search", "arguments": "Best catering services in Gotham City"}, {"name": "web_search", "arguments": "Party theme ideas for superheroes"} ] ``` This JSON blob is then used to execute the tool calls. While `smolagents` primarily focuses on `CodeAgents` since [they perform better overall](https://huggingface.co/papers/2402.01030), `ToolCallingAgents` can be effective for simple systems that don't require variable handling or complex tool calls. ![Code vs JSON Actions](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/code_vs_json_actions.png) ## How Do Tool Calling Agents Work? Tool Calling Agents follow the same multi-step workflow as Code Agents (see the [previous section](./code_agents) for details). The key difference is in **how they structure their actions**: instead of executable code, they **generate JSON objects that specify tool names and arguments**. The system then **parses these instructions** to execute the appropriate tools. ## Example: Running a Tool Calling Agent Let's revisit the previous example where Alfred started party preparations, but this time we'll use a `ToolCallingAgent` to highlight the difference. We'll build an agent that can search the web using DuckDuckGo, just like in our Code Agent example. The only difference is the agent type - the framework handles everything else: ```python from smolagents import ToolCallingAgent, DuckDuckGoSearchTool, InferenceClientModel agent = ToolCallingAgent(tools=[DuckDuckGoSearchTool()], model=InferenceClientModel()) agent.run("Search for the best music recommendations for a party at the Wayne's mansion.") ``` When you examine the agent's trace, instead of seeing `Executing parsed code:`, you'll see something like: ```text ╭─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │ Calling tool: 'web_search' with arguments: {'query': "best music recommendations for a party at Wayne's │ │ mansion"} │ ╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ ``` The agent generates a structured tool call that the system processes to produce the output, rather than directly executing code like a `CodeAgent`. Now that we understand both agent types, we can choose the right one for our needs. Let's continue exploring `smolagents` to make Alfred's party a success! 🎉 ## Resources - [ToolCallingAgent documentation](https://huggingface.co/docs/smolagents/v1.8.1/en/reference/agents#smolagents.ToolCallingAgent) - Official documentation for ToolCallingAgent
agents-course/units/en/unit2/smolagents/tool_calling_agents.mdx/0
{ "file_path": "agents-course/units/en/unit2/smolagents/tool_calling_agents.mdx", "repo_id": "agents-course", "token_count": 1170 }
4
# What is GAIA? [GAIA](https://huggingface.co/papers/2311.12983) is a **benchmark designed to evaluate AI assistants on real-world tasks** that require a combination of core capabilities—such as reasoning, multimodal understanding, web browsing, and proficient tool use. It was introduced in the paper _"[GAIA: A Benchmark for General AI Assistants](https://huggingface.co/papers/2311.12983)"_. The benchmark features **466 carefully curated questions** that are **conceptually simple for humans**, yet **remarkably challenging for current AI systems**. To illustrate the gap: - **Humans**: ~92% success rate - **GPT-4 with plugins**: ~15% - **Deep Research (OpenAI)**: 67.36% on the validation set GAIA highlights the current limitations of AI models and provides a rigorous benchmark to evaluate progress toward truly general-purpose AI assistants. ## 🌱 GAIA’s Core Principles GAIA is carefully designed around the following pillars: - 🔍 **Real-world difficulty**: Tasks require multi-step reasoning, multimodal understanding, and tool interaction. - 🧾 **Human interpretability**: Despite their difficulty for AI, tasks remain conceptually simple and easy to follow for humans. - 🛡️ **Non-gameability**: Correct answers demand full task execution, making brute-forcing ineffective. - 🧰 **Simplicity of evaluation**: Answers are concise, factual, and unambiguous—ideal for benchmarking. ## Difficulty Levels GAIA tasks are organized into **three levels of increasing complexity**, each testing specific skills: - **Level 1**: Requires less than 5 steps and minimal tool usage. - **Level 2**: Involves more complex reasoning and coordination between multiple tools and 5-10 steps. - **Level 3**: Demands long-term planning and advanced integration of various tools. ![GAIA levels](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit4/gaia_levels.png) ## Example of a Hard GAIA Question > Which of the fruits shown in the 2008 painting "Embroidery from Uzbekistan" were served as part of the October 1949 breakfast menu for the ocean liner that was later used as a floating prop for the film "The Last Voyage"? Give the items as a comma-separated list, ordering them in clockwise order based on their arrangement in the painting starting from the 12 o'clock position. Use the plural form of each fruit. As you can see, this question challenges AI systems in several ways: - Requires a **structured response format** - Involves **multimodal reasoning** (e.g., analyzing images) - Demands **multi-hop retrieval** of interdependent facts: - Identifying the fruits in the painting - Discovering which ocean liner was used in *The Last Voyage* - Looking up the breakfast menu from October 1949 for that ship - Needs **correct sequencing** and high-level planning to solve in the right order This kind of task highlights where standalone LLMs often fall short, making GAIA an ideal benchmark for **agent-based systems** that can reason, retrieve, and execute over multiple steps and modalities. ![GAIA capabilities plot](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit4/gaia_capabilities.png) ## Live Evaluation To encourage continuous benchmarking, **GAIA provides a public leaderboard hosted on Hugging Face**, where you can test your models against **300 testing questions**. 👉 Check out the leaderboard [here](https://huggingface.co/spaces/gaia-benchmark/leaderboard) <iframe src="https://gaia-benchmark-leaderboard.hf.space" frameborder="0" width="850" height="450" ></iframe> Want to dive deeper into GAIA? - 📄 [Read the full paper](https://huggingface.co/papers/2311.12983) - 📄 [Deep Research release post by OpenAI](https://openai.com/index/introducing-deep-research/) - 📄 [Open-source DeepResearch – Freeing our search agents](https://huggingface.co/blog/open-deep-research)
agents-course/units/en/unit4/what-is-gaia.mdx/0
{ "file_path": "agents-course/units/en/unit4/what-is-gaia.mdx", "repo_id": "agents-course", "token_count": 1041 }
5
# Live 1: Como funciona el curso y preguntas y respuestas En esta primera sesión en vivo del Curso de Agentes, explicamos **como funciona el curso** (alcance, unidades, desafios y más) y respondimos tus preguntas. <iframe width="560" height="315" src="https://www.youtube.com/embed/iLVyYDbdSmM?si=TCX5Ai3uZuKLXq45" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe> Para saber cuando se publica la siguiente sesión, consulta nuestro **Servidor de Discord**. Tambien te enviaremos un correo electrónico. Si no puedes participar, no te preocupes, **todas las sesión en vivo están grabadas**.
agents-course/units/es/communication/live1.mdx/0
{ "file_path": "agents-course/units/es/communication/live1.mdx", "repo_id": "agents-course", "token_count": 272 }
6
# ¿Qué son las Herramientas? <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/whiteboard-check-2.jpg" alt="Planificación de la Unidad 1"/> Un aspecto crucial de los Agentes de IA es su capacidad para realizar **acciones**. Como vimos, esto sucede a través del uso de **Herramientas**. En esta sección, aprenderemos qué son las Herramientas, cómo diseñarlas de manera efectiva y cómo integrarlas en tu Agente a través del Mensaje del Sistema. Al proporcionar a tu Agente las Herramientas adecuadas —y describir claramente cómo funcionan esas Herramientas— puedes aumentar dramáticamente lo que tu IA puede lograr. ¡Vamos a profundizar! ## ¿Qué son las Herramientas de IA? Una **Herramienta es una función proporcionada al LLM**. Esta función debe cumplir un **objetivo claro**. Aquí hay algunas herramientas comúnmente utilizadas en agentes de IA: | Herramienta | Descripción | |----------------|---------------------------------------------------------------| | Búsqueda Web | Permite al agente obtener información actualizada de internet. | | Generación de Imágenes | Crea imágenes basadas en descripciones textuales. | | Recuperación | Recupera información de una fuente externa. | | Interfaz de API | Interactúa con una API externa (GitHub, YouTube, Spotify, etc.). | ¡Esos son solo ejemplos, ya que de hecho puedes crear una herramienta para cualquier caso de uso! Una buena herramienta debería ser algo que **complemente el poder de un LLM**. Por ejemplo, si necesitas realizar operaciones aritméticas, proporcionar una **herramienta de calculadora** a tu LLM proporcionará mejores resultados que confiar en las capacidades nativas del modelo. Además, **los LLMs predicen la finalización de un prompt basándose en sus datos de entrenamiento**, lo que significa que su conocimiento interno solo incluye eventos anteriores a su entrenamiento. Por lo tanto, si tu agente necesita datos actualizados, debes proporcionarlos a través de alguna herramienta. Por ejemplo, si le preguntas directamente a un LLM (sin una herramienta de búsqueda) sobre el clima de hoy, el LLM potencialmente alucinará un clima aleatorio. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/weather.jpg" alt="Clima"/> - Una Herramienta debe contener: - Una **descripción textual de lo que hace la función**. - Un *Callable* (algo para realizar una acción). - *Argumentos* con tipos. - (Opcional) Salidas con tipos. ## ¿Cómo funcionan las herramientas? Los LLMs, como vimos, solo pueden recibir entradas de texto y generar salidas de texto. No tienen forma de llamar a herramientas por sí mismos. Lo que queremos decir cuando hablamos de _proporcionar herramientas a un Agente_, es que **enseñamos** al LLM sobre la existencia de herramientas, y pedimos al modelo que genere texto que invocará herramientas cuando las necesite. Por ejemplo, si proporcionamos una herramienta para verificar el clima en una ubicación desde Internet, y luego preguntamos al LLM sobre el clima en París, el LLM reconocerá esa pregunta como una oportunidad relevante para usar la herramienta "clima" que le enseñamos. El LLM generará _texto_, en forma de código, para invocar esa herramienta. Es responsabilidad del **Agente** analizar la salida del LLM, reconocer que se requiere una llamada a una herramienta e invocar la herramienta en nombre del LLM. La salida de la herramienta luego se enviará de vuelta al LLM, que compondrá su respuesta final para el usuario. La salida de una llamada a una herramienta es otro tipo de mensaje en la conversación. Los pasos de llamada a herramientas típicamente no se muestran al usuario: el Agente recupera la conversación, llama a la(s) herramienta(s), obtiene las salidas, las agrega como un nuevo mensaje de conversación y envía la conversación actualizada al LLM nuevamente. Desde el punto de vista del usuario, es como si el LLM hubiera usado la herramienta, pero de hecho fue nuestro código de aplicación (el **Agente**) quien lo hizo. Hablaremos mucho más sobre este proceso en sesiones futuras. ## ¿Cómo proporcionamos herramientas a un LLM? La respuesta completa puede parecer abrumadora, pero esencialmente usamos el prompt del sistema para proporcionar descripciones textuales de las herramientas disponibles al modelo: <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/Agent_system_prompt.png" alt="Prompt del sistema para herramientas"/> Para que esto funcione, tenemos que ser muy precisos y exactos sobre: 1. **Lo que hace la herramienta** 2. **Qué entradas exactas espera** Esta es la razón por la que las descripciones de herramientas generalmente se proporcionan utilizando estructuras expresivas pero precisas, como lenguajes de computadora o JSON. No es _necesario_ hacerlo así, cualquier formato preciso y coherente funcionaría. Si esto parece demasiado teórico, vamos a entenderlo a través de un ejemplo concreto. Implementaremos una herramienta **calculadora** simplificada que solo multiplicará dos enteros. Esta podría ser nuestra implementación en Python: ```python def calculadora(a: int, b: int) -> int: """Multiplica dos enteros.""" return a * b ``` Así que nuestra herramienta se llama `calculadora`, **multiplica dos enteros**, y requiere las siguientes entradas: - **`a`** (*int*): Un entero. - **`b`** (*int*): Un entero. La salida de la herramienta es otro número entero que podemos describir así: - (*int*): El producto de `a` y `b`. Todos estos detalles son importantes. Vamos a juntarlos en una cadena de texto que describe nuestra herramienta para que el LLM la entienda. ```text Nombre de Herramienta: calculadora, Descripción: Multiplica dos enteros., Argumentos: a: int, b: int, Salidas: int ``` > **Recordatorio:** Esta descripción textual es *lo que queremos que el LLM sepa sobre la herramienta*. Cuando pasamos la cadena anterior como parte de la entrada al LLM, el modelo la reconocerá como una herramienta, y sabrá qué necesita pasar como entradas y qué esperar de la salida. Si queremos proporcionar herramientas adicionales, debemos ser consistentes y siempre usar el mismo formato. Este proceso puede ser frágil, y podríamos pasar por alto accidentalmente algunos detalles. ¿Hay una mejor manera? ### Auto-formateo de secciones de Herramientas Nuestra herramienta fue escrita en Python, y la implementación ya proporciona todo lo que necesitamos: - Un nombre descriptivo de lo que hace: `calculadora` - Una descripción más larga, proporcionada por el comentario docstring de la función: `Multiplica dos enteros.` - Las entradas y su tipo: la función claramente espera dos `int`s. - El tipo de la salida. Hay una razón por la que la gente usa lenguajes de programación: son expresivos, concisos y precisos. Podríamos proporcionar el código fuente de Python como la _especificación_ de la herramienta para el LLM, pero la forma en que se implementa la herramienta no importa. Todo lo que importa es su nombre, lo que hace, las entradas que espera y la salida que proporciona. Aprovecharemos las características de introspección de Python para aprovechar el código fuente y construir una descripción de herramienta automáticamente para nosotros. Todo lo que necesitamos es que la implementación de la herramienta use sugerencias de tipo, docstrings y nombres de función sensatos. Escribiremos algo de código para extraer las partes relevantes del código fuente. Después de terminar, solo necesitaremos usar un decorador de Python para indicar que la función `calculadora` es una herramienta: ```python @tool def calculadora(a: int, b: int) -> int: """Multiplica dos enteros.""" return a * b print(calculadora.to_string()) ``` Nota el decorador `@tool` antes de la definición de la función. Con la implementación que veremos a continuación, podremos recuperar el siguiente texto automáticamente del código fuente a través de la función `to_string()` proporcionada por el decorador: ```text Nombre de Herramienta: calculadora, Descripción: Multiplica dos enteros., Argumentos: a: int, b: int, Salidas: int ``` Como puedes ver, ¡es lo mismo que escribimos manualmente antes! ### Implementación genérica de Herramienta Creamos una clase genérica `Tool` que podemos reutilizar siempre que necesitemos usar una herramienta. > **Descargo de responsabilidad:** Esta implementación de ejemplo es ficticia pero se parece mucho a implementaciones reales en la mayoría de las bibliotecas. ```python class Tool: """ Una clase que representa un fragmento de código reutilizable (Herramienta). Atributos: name (str): Nombre de la herramienta. description (str): Una descripción textual de lo que hace la herramienta. func (callable): La función que esta herramienta envuelve. arguments (list): Una lista de argumentos. outputs (str or list): El tipo(s) de retorno de la función envuelta. """ 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: """ Devuelve una representación en cadena de la herramienta, incluyendo su nombre, descripción, argumentos y salidas. """ args_str = ", ".join([ f"{arg_name}: {arg_type}" for arg_name, arg_type in self.arguments ]) return ( f"Nombre de Herramienta: {self.name}," f" Descripción: {self.description}," f" Argumentos: {args_str}," f" Salidas: {self.outputs}" ) def __call__(self, *args, **kwargs): """ Invoca la función subyacente (callable) con los argumentos proporcionados. """ return self.func(*args, **kwargs) ``` Puede parecer complicado, pero si lo recorremos lentamente podemos ver lo que hace. Definimos una clase **`Tool`** que incluye: - **`name`** (*str*): El nombre de la herramienta. - **`description`** (*str*): Una breve descripción de lo que hace la herramienta. - **`function`** (*callable*): La función que ejecuta la herramienta. - **`arguments`** (*list*): Los parámetros de entrada esperados. - **`outputs`** (*str* o *list*): Las salidas esperadas de la herramienta. - **`__call__()`**: Llama a la función cuando se invoca la instancia de la herramienta. - **`to_string()`**: Convierte los atributos de la herramienta en una representación textual. Podríamos crear una Herramienta con esta clase usando código como el siguiente: ```python calculadora_tool = Tool( "calculadora", # nombre "Multiplica dos enteros.", # descripción calculadora, # función a llamar [("a", "int"), ("b", "int")], # entradas (nombres y tipos) "int", # salida ) ``` ¡Pero también podemos usar el módulo `inspect` de Python para recuperar toda la información por nosotros! Esto es lo que hace el decorador `@tool`. > Si estás interesado, puedes revelar la siguiente sección para ver la implementación del decorador. <details> <summary> código del decorador</summary> ```python def tool(func): """ Un decorador que crea una instancia de Tool a partir de la función dada. """ # Obtener la firma de la función signature = inspect.signature(func) # Extraer pares (param_name, param_annotation) para entradas 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)) # Determinar la anotación de retorno return_annotation = signature.return_annotation if return_annotation is inspect._empty: outputs = "Sin anotación de retorno" else: outputs = ( return_annotation.__name__ if hasattr(return_annotation, '__name__') else str(return_annotation) ) # Usar el docstring de la función como descripción (por defecto si es None) description = func.__doc__ or "No se proporcionó descripción." # El nombre de la función se convierte en el nombre de la Herramienta name = func.__name__ # Devolver una nueva instancia de Tool return Tool( name=name, description=description, func=func, arguments=arguments, outputs=outputs ) ``` </details> Solo para reiterar, con este decorador en su lugar podemos implementar nuestra herramienta así: ```python @tool def calculadora(a: int, b: int) -> int: """Multiplica dos enteros.""" return a * b print(calculadora.to_string()) ``` Y podemos usar el método `to_string` de la `Tool` para recuperar automáticamente un texto adecuado para ser utilizado como descripción de herramienta para un LLM: ```text Nombre de Herramienta: calculadora, Descripción: Multiplica dos enteros., Argumentos: a: int, b: int, Salidas: int ``` La descripción se **inyecta** en el prompt del sistema. Tomando el ejemplo con el que comenzamos esta sección, así es como se vería después de reemplazar el `tools_description`: <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/Agent_system_prompt_tools.png" alt="Prompt del sistema para herramientas"/> En la sección [Acciones](actions.mdx), aprenderemos más sobre cómo un Agente puede **Llamar** a esta herramienta que acabamos de crear. --- Las herramientas juegan un papel crucial en la mejora de las capacidades de los agentes de IA. Para resumir, aprendimos: - *Qué son las Herramientas*: Funciones que dan a los LLMs capacidades adicionales, como realizar cálculos o acceder a datos externos. - *Cómo Definir una Herramienta*: Proporcionando una descripción textual clara, entradas, salidas y una función invocable. - *Por qué las Herramientas son Esenciales*: Permiten a los Agentes superar las limitaciones del entrenamiento estático del modelo, manejar tareas en tiempo real y realizar acciones especializadas. Ahora, podemos pasar al [Flujo de Trabajo del Agente](agent-steps-and-structure.mdx) donde verás cómo un Agente observa, piensa y actúa. Esto **reúne todo lo que hemos cubierto hasta ahora** y prepara el escenario para crear tu propio Agente de IA completamente funcional. Pero primero, ¡es hora de otro cuestionario corto!
agents-course/units/es/unit1/tools.mdx/0
{ "file_path": "agents-course/units/es/unit1/tools.mdx", "repo_id": "agents-course", "token_count": 5845 }
7
<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/vision_agents.ipynb"}, ]} /> # Agentes de Visión con smolagents <Tip warning={true}> Los ejemplos en esta sección requieren acceso a un modelo VLM potente. Los probamos usando la API de GPT-4o. Sin embargo, <a href="./why_use_smolagents">Por qué usar smolagents</a> discute soluciones alternativas soportadas por smolagents y Hugging Face. Si deseas explorar otras opciones, asegúrate de revisar esa sección. </Tip> Dotar a los agentes con capacidades visuales es crucial para resolver tareas que van más allá del procesamiento de texto. Muchos desafíos del mundo real, como la navegación web o la comprensión de documentos, requieren analizar contenido visual complejo. Afortunadamente, `smolagents` proporciona soporte integrado para modelos de visión-lenguaje (VLMs), permitiendo a los agentes procesar e interpretar imágenes de manera efectiva. En este ejemplo, imagina que Alfred, el mayordomo de la Mansión Wayne, tiene la tarea de verificar las identidades de los invitados que asisten a la fiesta. Como puedes imaginar, Alfred puede no estar familiarizado con todos los que llegan. Para ayudarlo, podemos usar un agente que verifique su identidad buscando información visual sobre su apariencia usando un VLM. Esto permitirá a Alfred tomar decisiones informadas sobre quién puede entrar. ¡Vamos a construir este ejemplo! ## Proporcionando Imágenes al Inicio de la Ejecución del Agente <Tip> Puedes seguir el código en <a href="https://huggingface.co/agents-course/notebooks/blob/main/unit2/smolagents/vision_agents.ipynb" target="_blank">este notebook</a> que puedes ejecutar usando Google Colab. </Tip> En este enfoque, las imágenes se pasan al agente al inicio y se almacenan como `task_images` junto con el prompt de la tarea. El agente luego procesa estas imágenes durante su ejecución. Considera el caso donde Alfred quiere verificar las identidades de los superhéroes que asisten a la fiesta. Ya tiene un conjunto de datos de imágenes de fiestas anteriores con los nombres de los invitados. Dada la imagen de un nuevo visitante, el agente puede compararla con el conjunto de datos existente y tomar una decisión sobre dejarlos entrar. En este caso, un invitado está tratando de entrar, y Alfred sospecha que este visitante podría ser El Joker haciéndose pasar por Wonder Woman. Alfred necesita verificar su identidad para evitar que entren personas no deseadas. Vamos a construir el ejemplo. Primero, se cargan las imágenes. En este caso, usamos imágenes de Wikipedia para mantener el ejemplo mínimo, ¡pero imagina el posible caso de uso! ```python from PIL import Image import requests from io import BytesIO image_urls = [ "https://upload.wikimedia.org/wikipedia/commons/e/e8/The_Joker_at_Wax_Museum_Plus.jpg", # Imagen del Joker "https://upload.wikimedia.org/wikipedia/en/9/98/Joker_%28DC_Comics_character%29.jpg" # Imagen del Joker ] images = [] for url in image_urls: response = requests.get(url) image = Image.open(BytesIO(response.content)).convert("RGB") images.append(image) ``` Ahora que tenemos las imágenes, el agente nos dirá si un invitado es realmente un superhéroe (Wonder Woman) o un villano (El Joker). ```python from smolagents import CodeAgent, OpenAIServerModel model = OpenAIServerModel(model_id="gpt-4o") # Instanciar el agente agent = CodeAgent( tools=[], model=model, max_steps=20, verbosity_level=2 ) response = agent.run( """ Describe el disfraz y maquillaje que está usando el personaje de cómic en estas fotos y devuelve la descripción. Dime si el invitado es El Joker o Wonder Woman. """, images=images ) ``` En el caso de mi ejecución, la salida es la siguiente, aunque podría variar en tu caso, como ya hemos discutido: ```python { 'Disfraz y Maquillaje - Primera Imagen': ( 'Abrigo púrpura y una corbata o pañuelo de seda púrpura sobre una camisa amarillo mostaza.', 'Pintura facial blanca con rasgos exagerados, cejas oscuras, maquillaje azul en los ojos, labios rojos formando una amplia sonrisa.' ), 'Disfraz y Maquillaje - Segunda Imagen': ( 'Traje oscuro con una flor en la solapa, sosteniendo una carta de juego.', 'Piel pálida, cabello verde, labios muy rojos con una sonrisa exagerada.' ), 'Identidad del Personaje': 'Este personaje se asemeja a representaciones conocidas de El Joker de los medios de cómics.' } ``` En este caso, la salida revela que la persona se está haciendo pasar por alguien más, ¡así que podemos evitar que El Joker entre a la fiesta! ## Proporcionando Imágenes con Recuperación Dinámica <Tip> Puedes seguir el código en <a href="https://huggingface.co/agents-course/notebooks/blob/main/unit2/smolagents/vision_web_browser.py" target="_blank">este archivo Python</a> </Tip> El enfoque anterior es valioso y tiene muchos casos de uso potenciales. Sin embargo, en situaciones donde el invitado no está en la base de datos, necesitamos explorar otras formas de identificarlos. Una posible solución es recuperar dinámicamente imágenes e información de fuentes externas, como navegar por la web para obtener detalles. En este enfoque, las imágenes se agregan dinámicamente a la memoria del agente durante la ejecución. Como sabemos, los agentes en `smolagents` están basados en la clase `MultiStepAgent`, que es una abstracción del framework ReAct. Esta clase opera en un ciclo estructurado donde varias variables y conocimientos se registran en diferentes etapas: 1. **SystemPromptStep:** Almacena el prompt del sistema. 2. **TaskStep:** Registra la consulta del usuario y cualquier entrada proporcionada. 3. **ActionStep:** Captura registros de las acciones del agente y los resultados. Este enfoque estructurado permite a los agentes incorporar información visual de manera dinámica y responder de forma adaptativa a tareas en evolución. A continuación se muestra el diagrama que ya hemos visto, ilustrando el proceso de flujo de trabajo dinámico y cómo diferentes pasos se integran dentro del ciclo de vida del agente. Al navegar, el agente puede tomar capturas de pantalla y guardarlas como `observation_images` en el `ActionStep`. ![Recuperación dinámica de imágenes](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/smolagents-can-see/diagram_adding_vlms_smolagents.png) Ahora que entendemos la necesidad, vamos a construir nuestro ejemplo completo. En este caso, Alfred quiere control total sobre el proceso de verificación de invitados, por lo que buscar detalles se convierte en una solución viable. Para completar este ejemplo, necesitamos un nuevo conjunto de herramientas para el agente. Además, usaremos Selenium y Helium, que son herramientas de automatización de navegador. Esto nos permitirá construir un agente que explore la web, buscando detalles sobre un posible invitado y recuperando información de verificación. Vamos a instalar las herramientas necesarias: ```bash pip install "smolagents[all]" helium selenium python-dotenv ``` Necesitaremos un conjunto de herramientas de agente específicamente diseñadas para navegar, como `search_item_ctrl_f`, `go_back`, y `close_popups`. Estas herramientas permiten al agente actuar como una persona navegando por la web. ```python @tool def search_item_ctrl_f(text: str, nth_result: int = 1) -> str: """ Busca texto en la página actual a través de Ctrl + F y salta a la n-ésima ocurrencia. Args: text: El texto a buscar nth_result: A qué ocurrencia saltar (por defecto: 1) """ elements = driver.find_elements(By.XPATH, f"//*[contains(text(), '{text}')]") if nth_result > len(elements): raise Exception(f"Coincidencia n°{nth_result} no encontrada (solo se encontraron {len(elements)} coincidencias)") result = f"Se encontraron {len(elements)} coincidencias para '{text}'." elem = elements[nth_result - 1] driver.execute_script("arguments[0].scrollIntoView(true);", elem) result += f"Enfocado en el elemento {nth_result} de {len(elements)}" return result @tool def go_back() -> None: """Regresa a la página anterior.""" driver.back() @tool def close_popups() -> str: """ Cierra cualquier modal o pop-up visible en la página. ¡Usa esto para descartar ventanas emergentes! Esto no funciona en banners de consentimiento de cookies. """ webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform() ``` También necesitamos funcionalidad para guardar capturas de pantalla, ya que esta será una parte esencial de lo que nuestro agente VLM usa para completar la tarea. Esta funcionalidad captura la pantalla y la guarda en `step_log.observations_images = [image.copy()]`, permitiendo al agente almacenar y procesar las imágenes dinámicamente mientras navega. ```python def save_screenshot(step_log: ActionStep, agent: CodeAgent) -> None: sleep(1.0) # Permitir que ocurran animaciones JavaScript antes de tomar la captura de pantalla driver = helium.get_driver() current_step = step_log.step_number if driver is not None: for step_logs in agent.logs: # Eliminar capturas de pantalla anteriores de los registros para un procesamiento eficiente if isinstance(step_log, ActionStep) and step_log.step_number <= current_step - 2: step_logs.observations_images = None png_bytes = driver.get_screenshot_as_png() image = Image.open(BytesIO(png_bytes)) print(f"Se capturó una captura de pantalla del navegador: {image.size} píxeles") step_log.observations_images = [image.copy()] # Crear una copia para asegurar que persista, ¡importante! # Actualizar observaciones con la URL actual url_info = f"URL actual: {driver.current_url}" step_log.observations = url_info if step_logs.observations is None else step_log.observations + "\n" + url_info return ``` Esta función se pasa al agente como `step_callback`, ya que se activa al final de cada paso durante la ejecución del agente. Esto permite al agente capturar y almacenar dinámicamente capturas de pantalla a lo largo de su proceso. Ahora, podemos generar nuestro agente de visión para navegar por la web, proporcionándole las herramientas que creamos, junto con el `DuckDuckGoSearchTool` para explorar la web. Esta herramienta ayudará al agente a recuperar la información necesaria para verificar las identidades de los invitados basándose en señales visuales. ```python from smolagents import CodeAgent, OpenAIServerModel, DuckDuckGoSearchTool model = OpenAIServerModel(model_id="gpt-4o") agent = CodeAgent( tools=[DuckDuckGoSearchTool(), go_back, close_popups, search_item_ctrl_f], model=model, additional_authorized_imports=["helium"], step_callbacks=[save_screenshot], max_steps=20, verbosity_level=2, ) ``` Con eso, Alfred está listo para verificar las identidades de los invitados y tomar decisiones informadas sobre si dejarlos entrar a la fiesta: ```python agent.run(""" Soy Alfred, el mayordomo de la Mansión Wayne, responsable de verificar la identidad de los invitados en la fiesta. Una superheroína ha llegado a la entrada afirmando ser Wonder Woman, pero necesito confirmar si ella es quien dice ser. Por favor, busca imágenes de Wonder Woman y genera una descripción visual detallada basada en esas imágenes. Además, navega a Wikipedia para recopilar detalles clave sobre su apariencia. Con esta información, puedo determinar si concederle acceso al evento. """ + helium_instructions) ``` Puedes ver que incluimos `helium_instructions` como parte de la tarea. Este prompt especial está destinado a controlar la navegación del agente, asegurando que siga los pasos correctos mientras navega por la web. Veamos cómo funciona esto en el video a continuación: <video controls> <source src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/smolagents/VisionBrowserAgent.mp4" type="video/mp4"> </video> Esta es la salida final: ```python Respuesta final: Wonder Woman normalmente se representa vistiendo un corsé rojo y dorado, shorts o falda azul con estrellas blancas, una tiara dorada, brazaletes plateados y un Lazo de la Verdad dorado. Es la Princesa Diana de Themyscira, conocida como Diana Prince en el mundo de los hombres. ``` ¡Con todo eso, hemos creado exitosamente nuestro verificador de identidad para la fiesta! Alfred ahora tiene las herramientas necesarias para asegurar que solo los invitados correctos pasen por la puerta. ¡Todo está listo para pasarlo bien en la Mansión Wayne! ## Lecturas Adicionales - [Acabamos de dar vista a smolagents](https://huggingface.co/blog/smolagents-can-see) - Blog que describe la funcionalidad del agente de visión. - [Automatización de Navegador Web con Agentes 🤖🌐](https://huggingface.co/docs/smolagents/examples/web_browser) - Ejemplo de navegación web usando un agente de visión. - [Ejemplo de Agente de Visión para Navegador Web](https://github.com/huggingface/smolagents/blob/main/src/smolagents/vision_web_browser.py) - Ejemplo de navegación web usando un agente de visión.
agents-course/units/es/unit2/smolagents/vision_agents.mdx/0
{ "file_path": "agents-course/units/es/unit2/smolagents/vision_agents.mdx", "repo_id": "agents-course", "token_count": 4929 }
8
- title: Unité 0. Bienvenue dans le cours sections: - local: unit0/introduction title: Bienvenue dans le cours 🤗 - local: unit0/onboarding title: Embarquement - local: unit0/discord101 title: (Optionnel) Introduction à Discord - title: Live 1. Comment fonctionne le cours et Q&R sections: - local: communication/live1 title: Live 1. Comment fonctionne le cours et Q&R - title: Unité 1. Introduction aux Agents sections: - local: unit1/introduction title: Introduction aux agents - local: unit1/what-are-agents title: Qu'est-ce qu'un agent ? - local: unit1/quiz1 title: Quiz rapide 1 - local: unit1/what-are-llms title: Qu'est-ce qu'un LLM ? - local: unit1/messages-and-special-tokens title: Messages et tokens spéciaux - local: unit1/tools title: Que sont les outils ? - local: unit1/quiz2 title: Quiz rapide 2 - local: unit1/agent-steps-and-structure title: Comprendre les agents à travers le cycle Réflexion-Action-Observation - local: unit1/thoughts title: Réflexions, raisonnement interne et l'approche Re-Act - local: unit1/actions title: Actions, permettre à l'agent d'interagir avec son environnement - local: unit1/observations title: Observer, intégrer le retour d'information pour réfléchir et s'adapter - local: unit1/dummy-agent-library title: Bibliothèque d'agents factices - local: unit1/tutorial title: Créons notre premier agent avec smolagents - local: unit1/final-quiz title: Quiz final de l'Unité 1 - local: unit1/conclusion title: Conclusion - title: Unité 2. Frameworks pour les agents sections: - local: unit2/introduction title: Frameworks pour les agents - title: Unité 2.1 Le framework smolagents sections: - local: unit2/smolagents/introduction title: Introduction à smolagents - local: unit2/smolagents/why_use_smolagents title: Pourquoi utiliser smolagents ? - local: unit2/smolagents/quiz1 title: Quiz rapide 1 - local: unit2/smolagents/code_agents title: Construire des agents qui utilisent du code - local: unit2/smolagents/tool_calling_agents title: Écrire des actions sous forme d'extraits de code ou de blobs JSON - local: unit2/smolagents/tools title: Outils - local: unit2/smolagents/retrieval_agents title: Construction de systèmes de RAG agentiques - local: unit2/smolagents/quiz2 title: Quiz rapide 2 - local: unit2/smolagents/multi_agent_systems title: Systèmes multi-agents - local: unit2/smolagents/vision_agents title: Agents visuel avec smolagents - local: unit2/smolagents/final_quiz title: Quiz final - local: unit2/smolagents/conclusion title: Conclusion - title: Unité 2.2 Le framework LlamaIndex sections: - local: unit2/llama-index/introduction title: Introduction à LlamaIndex - local: unit2/llama-index/llama-hub title: Introduction au LlamaHub - local: unit2/llama-index/components title: Que sont les components dans LlamaIndex ? - local: unit2/llama-index/tools title: Utiliser des outils dans LlamaIndex - local: unit2/llama-index/quiz1 title: Quiz rapide 1 - local: unit2/llama-index/agents title: Utiliser des agents dans LlamaIndex - local: unit2/llama-index/workflows title: Créer des workflows agentiques dans LlamaIndex - local: unit2/llama-index/quiz2 title: Quiz rapide 2 - local: unit2/llama-index/conclusion title: Conclusion - title: Unité 2.3 Le framework LangGraph sections: - local: unit2/langgraph/introduction title: Introduction à LangGraph - local: unit2/langgraph/when_to_use_langgraph title: Qu'est-ce que LangGraph ? - local: unit2/langgraph/building_blocks title: Les blocs de construction de LangGraph - local: unit2/langgraph/first_graph title: Construire votre premier LangGraph - local: unit2/langgraph/document_analysis_agent title: Graphe d'analyse de documents - local: unit2/langgraph/quiz1 title: Quiz rapide 1 - local: unit2/langgraph/conclusion title: Conclusion - title: Unité 3. Cas d'usage pour le RAG agentique sections: - local: unit3/agentic-rag/introduction title: Introduction au cas d'usage de RAG agentique - local: unit3/agentic-rag/agentic-rag title: RAG agentique - local: unit3/agentic-rag/invitees title: Création d'un RAG pour converser avec les invités - local: unit3/agentic-rag/tools title: Création et intégration d'outils pour votre agent - local: unit3/agentic-rag/agent title: Création de l'agent pour le gala - local: unit3/agentic-rag/conclusion title: Conclusion - title: Unité 4. Projet final - Créer, tester et certifier votre agent sections: - local: unit4/introduction title: Introduction à l'unité finale - local: unit4/what-is-gaia title: Qu'est-ce que GAIA ? - local: unit4/hands-on title: Le projet pratique final - local: unit4/get-your-certificate title: Obtenez votre certificat - local: unit4/conclusion title: Conclusion du cours - local: unit4/additional-readings title: Et maintenant ? Quels sujets devrais-je apprendre ? - title: Unité bonus 1. Affiner un LLM pour l'appel de fonctions sections: - local: bonus-unit1/introduction title: Introduction - local: bonus-unit1/what-is-function-calling title: Qu'est-ce que l'appel de fonctions ? - local: bonus-unit1/fine-tuning title: Finetunons un modèle pour pouvoir faire de l'appel de fonctions - local: bonus-unit1/conclusion title: Conclusion - title: Unité bonus 2. Observabilité et évaluation des agents sections: - local: bonus-unit2/introduction title: Introduction - local: bonus-unit2/what-is-agent-observability-and-evaluation title: Qu'est-ce que l'observabilité et l'évaluation des agents ? - local: bonus-unit2/monitoring-and-evaluating-agents-notebook title: Observer et évaluer des agents - local: bonus-unit2/quiz title: Quiz - title: Unité bonus 3. Agents dans les jeux avec Pokémon sections: - local: bonus-unit3/introduction title: Introduction - local: bonus-unit3/state-of-art title: L'état de l'art de l'utilisation des LLM dans les jeux - local: bonus-unit3/from-llm-to-agents title: Des LLM aux agents - local: bonus-unit3/building_your_pokemon_agent title: Construire un agent de combat Pokémon - local: bonus-unit3/launching_agent_battle title: Lancer l'agent de combat Pokémon - local: bonus-unit3/conclusion title: Conclusion
agents-course/units/fr/_toctree.yml/0
{ "file_path": "agents-course/units/fr/_toctree.yml", "repo_id": "agents-course", "token_count": 2359 }
9
# (Optionnel) Introduction à Discord [[discord-101]] <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit0/discord-etiquette.jpg" alt="L'étiquette sur Discord" width="100%"/> Ce guide est conçu pour vous aider à débuter sur Discord, une plateforme de chat gratuite très prisée dans les communautés de *gaming* et de *machine learning*. Rejoignez le serveur Discord de la communauté Hugging Face, qui compte **plus de 100 000 membres**, en cliquant <a href="https://discord.gg/UrrTSsSyjb" target="_blank">ici</a>. C'est un excellent endroit pour se connecter avec d'autres passionnés ! ## Le cours sur les agents sur le Discord d'Hugging Face Commencer sur Discord peut sembler un peu intimidant, alors voici un guide rapide pour vous orienter. Le serveur d'HF réunit une communauté dynamique aux intérêts variés, offrant des opportunités d'apprentissage à travers des discussions sur des papiers scientifiques, des événements et bien plus encore. Après [vous être inscrit](http://hf.co/join/discord), présentez-vous dans le canal `#introduce-yourself`. Nous avons créé 4 canaux pour le cours sur les Agents : - `agents-course-announcements` : pour les **dernières informations sur le cours**. - `🎓-agents-course-general` : pour les **discussions générales et bavardages**. - `agents-course-questions` : pour **poser des questions et aider vos camarades**. - `agents-course-showcase` : pour **présenter vos meilleurs agents**. De plus, vous pouvez consulter : - `smolagents` : pour les **discussions et l'assistance concernant la bibliothèque**. ## Conseils pour utiliser Discord efficacement ### Comment rejoindre un serveur Si vous n'êtes pas très familier avec Discord, vous pouvez consulter ce <a href="https://support.discord.com/hc/en-us/articles/360034842871-How-do-I-join-a-Server#h_01FSJF9GT2QJMS2PRAW36WNBS8" target="_blank">guide</a> expliquant comment rejoindre un serveur. Voici un résumé rapide des étapes : 1. Cliquez sur le <a href="https://discord.gg/UrrTSsSyjb" target="_blank">lien d'invitation</a>. 2. Connectez-vous avec votre compte Discord ou créez-en un si vous n'en avez pas. 3. Vérifiez que vous n'êtes pas un bot/agent IA ! 4. Configurez votre pseudo et votre avatar. 5. Cliquez sur « Rejoindre le serveur ». ### Comment utiliser Discord efficacement Voici quelques conseils pour tirer le meilleur parti de Discord : - **Les canaux vocaux** sont disponibles, bien que le chat textuel soit le plus utilisé. - Vous pouvez formater votre texte en utilisant le **style markdown**, ce qui est particulièrement utile pour écrire du code. Notez toutefois que le markdown n'est pas aussi efficace pour les liens. - Pensez à ouvrir des fils de discussion pour les **conversations longues** afin de garder vos échanges bien organisés. Nous espérons que ce guide vous sera utile ! Si vous avez des questions, n'hésitez pas à nous les poser sur Discord 🤗.
agents-course/units/fr/unit0/discord101.mdx/0
{ "file_path": "agents-course/units/fr/unit0/discord101.mdx", "repo_id": "agents-course", "token_count": 1016 }
10
# Créons notre premier agent avec smolagents Dans la section précédente, nous avons appris comment créer des agents à partir de zéro en utilisant du code Python, et nous avons **vu à quel point ce processus peut être fastidieux**. Heureusement, de nombreuses bibliothèques d'agents simplifient ce travail en **se chargeant de la majeure partie du travail lourd pour vous**. Dans ce tutoriel, **vous allez créer votre tout premier agent** capable d'exécuter des actions telles que la génération d'images, la recherche sur le web, la vérification de fuseaux horaires et bien plus encore ! Vous publierez également votre agent **sur un *Space* Hugging Face afin de le partager avec vos amis et collègues**. C'est parti ! ## Qu'est-ce que smolagents ? <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/smolagents.png" alt="smolagents"/> Pour créer cet agent, nous allons utiliser `smolagents`, une bibliothèque qui **fournit un cadre facilitant le développement d'agents**. Cette bibliothèque légère est conçue pour être simple, tout en masquant une grande partie de la complexité liée à la construction d'un agent, permettant ainsi de vous concentrer sur la conception du comportement de l'agent. Nous approfondirons smolagents dans la prochaine unité. En attendant, vous pouvez également consulter cet <a href="https://huggingface.co/blog/smolagents" target="_blank">article de blog</a> ou le <a href="https://github.com/huggingface/smolagents" target="_blank">dépôt GitHub</a> de la bibliothèque. Brièvement, `smolagents` est une bibliothèque se concentrant sur les **agents générant du code** (via la classe `CodeAgent`), un type d'agent qui exécute des **"actions"** via des blocs de code, puis **"observe"** les résultats en exécutant le code. Voici un exemple de ce que nous allons construire ! Nous avons équipé notre agent d'un **outil de génération d'images** et lui avons demandé de générer une image d'un chat. L'agent dans `smolagents` aura les **mêmes comportements que celui personnalisé que nous avons construit précédemment** : il va **réfléchir, agir et observer cycliquement** jusqu'à parvenir à une réponse finale : <iframe width="560" height="315" src="https://www.youtube.com/embed/PQDKcWiuln4?si=ysSTDZoi8y55FVvA" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe> Excitant, n'est-ce pas ? ## Construisons notre agent ! Pour commencer, dupliquez ce *Space* : <a href="https://huggingface.co/spaces/agents-course/First_agent_template" target="_blank">https://huggingface.co/spaces/agents-course/First_agent_template</a> > Merci à <a href="https://huggingface.co/m-ric" target="_blank">Aymeric</a> pour ce patron ! 🙌 Dupliquer signifie **créer une copie locale sur votre propre profil** : <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/duplicate-space.gif" alt="Duplicate"/> Après la duplication, vous devrez ajouter votre *token* d'API Hugging Face pour que votre agent puisse accéder à l'API du modèle : 1. Tout d'abord, obtenez votre *token* Hugging Face sur [https://hf.co/settings/tokens](https://hf.co/settings/tokens) avec la permission d'inférer, si vous n'en avez pas déjà un. 2. Allez dans votre *Space* dupliqué et cliquez sur l'onglet **Settings**. 3. Descendez jusqu'à la section **Variables and Secrets** et cliquez sur **New Secret**. 4. Créez un secret avec le nom `HF_TOKEN` et collez votre token comme valeur. 5. Cliquez sur **Save** pour stocker votre *token* en toute sécurité. Tout au long de cette leçon, le seul fichier (actuellement incomplet) que vous aurez à modifier est le **"app.py"**. Vous pouvez consulter l'[original ici](https://huggingface.co/spaces/agents-course/First_agent_template/blob/main/app.py). Pour trouver le vôtre, allez dans votre copie du *Space*, cliquez sur l'onglet `Files` puis sur `app.py` dans la liste des répertoires. Analysons le code ensemble : - Le fichier commence par quelques importations de bibliothèques simples mais nécessaires ```python from smolagents import CodeAgent, DuckDuckGoSearchTool, FinalAnswerTool, InferenceClientModel, load_tool, tool import datetime import requests import pytz import yaml ``` Comme indiqué précédemment, nous utiliserons directement la classe **CodeAgent** de **smolagents**. ### Les outils Entrons maintenant dans le vif du sujet avec les outils ! Si vous souhaitez un rappel sur les outils, n'hésitez pas à consulter la section [Outils](tools) du cours. ```python @tool def my_custom_tool(arg1: str, arg2: int) -> str: # il est important de spécifier le type de retour # Conservez ce format pour la description de l'outil et des arguments, mais n'hésitez pas à modifier l'outil """Un outil qui ne fait encore rien Arguments: arg1: le premier argument arg2: le deuxième argument """ return "Quelle magie allez-vous créer ?" @tool def get_current_time_in_timezone(timezone: str) -> str: """Un outil qui récupère l'heure locale actuelle dans un fuseau horaire spécifié. Arguments: timezone: Une chaîne représentant un fuseau horaire valide (par exemple, 'America/New_York'). """ try: # Créer l'objet fuseau horaire tz = pytz.timezone(timezone) # Obtenir l'heure actuelle dans ce fuseau horaire local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") return f"L'heure locale actuelle dans {timezone} est : {local_time}" except Exception as e: return f"Erreur lors de la récupération de l'heure pour le fuseau horaire '{timezone}' : {str(e)}" ``` Les outils sont ce que nous vous encourageons à construire dans cette section ! Nous vous donnons deux exemples : 1. Un **outil factice non fonctionnel** que vous pouvez modifier pour créer quelque chose d'utile. 2. Un **outil réellement fonctionnel** qui récupère l'heure actuelle quelque part dans le monde. Pour définir votre outil, il est important de : 1. Fournir des types d'entrée et de sortie pour votre fonction, comme dans `get_current_time_in_timezone(timezone: str) -> str:` 2. Fournir une **docstring bien formatée**. `smolagents` s'attend à ce que tous les arguments aient une **description textuelle dans la docstring**. ### L'agent Il utilise [`Qwen/Qwen2.5-Coder-32B-Instruct`](https://huggingface.co/Qwen/Qwen2.5-Coder-32B-Instruct) comme moteur LLM. C'est un modèle très performant auquel nous accéderons via l'API *serverless*. ```python final_answer = FinalAnswerTool() model = InferenceClientModel( max_tokens=2096, temperature=0.5, model_id='Qwen/Qwen2.5-Coder-32B-Instruct', custom_role_conversions=None, ) with open("prompts.yaml", 'r') as stream: prompt_templates = yaml.safe_load(stream) # Nous créons notre CodeAgent agent = CodeAgent( model=model, tools=[final_answer], # ajoutez vos outils ici (ne supprimez pas final_answer) max_steps=6, verbosity_level=1, grammar=None, planning_interval=None, name=None, description=None, prompt_templates=prompt_templates ) GradioUI(agent).launch() ``` Cet agent utilise toujours l'`InferenceClient` que nous avons vu dans une section précédente derrière la classe **InferenceClientModel** ! Nous fournirons des exemples plus détaillés lors de la présentation du *framework* dans l'Unité 2. Pour l'instant, vous devez vous concentrer sur **l'ajout de nouveaux outils à la liste des outils** en utilisant le paramètre `tools` de votre agent. Par exemple, vous pourriez utiliser `DuckDuckGoSearchTool` qui a été importé dans la première ligne du code, ou vous pouvez examiner `image_generation_tool` qui est chargé depuis le Hub plus tard dans le code. **Ajouter des outils donnera de nouvelles capacités à votre agent**, alors soyez créatif ! ### Le *prompt système* Le *prompt* système de l'agent est stocké dans un fichier `prompts.yaml` séparé. Ce fichier contient des instructions prédéfinies qui guident le comportement de l'agent. Le stockage des *prompts* dans un fichier YAML permet une personnalisation et une réutilisation aisées pour différents agents ou cas d'utilisation. Vous pouvez consulter la [structure des fichiers du *Space*](https://huggingface.co/spaces/agents-course/First_agent_template/tree/main) pour voir où se trouve le fichier `prompts.yaml` et comment il est organisé dans le projet. Le fichier complet **"app.py"** : ```python from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel, load_tool, tool import datetime import requests import pytz import yaml from tools.final_answer import FinalAnswerTool from Gradio_UI import GradioUI # Voici un exemple d'un outil qui ne fait encore rien. Épatez-nous avec votre créativité ! @tool def my_custom_tool(arg1: str, arg2: int) -> str: # il est important de spécifier le type de retour # Conservez ce format pour la description de l'outil et des arguments, mais n'hésitez pas à modifier l'outil """Un outil qui ne fait encore rien Arguments: arg1: le premier argument arg2: le deuxième argument """ return "Quelle magie allez-vous créer ?" @tool def get_current_time_in_timezone(timezone: str) -> str: """Un outil qui récupère l'heure locale actuelle dans un fuseau horaire spécifié. Arguments: timezone: Une chaîne représentant un fuseau horaire valide (par exemple, 'America/New_York'). """ try: # Créer l'objet fuseau horaire tz = pytz.timezone(timezone) # Obtenir l'heure actuelle dans ce fuseau horaire local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") return f"L'heure locale actuelle dans {timezone} est : {local_time}" except Exception as e: return f"Erreur lors de la récupération de l'heure pour le fuseau horaire '{timezone}' : {str(e)}" final_answer = FinalAnswerTool() model = InferenceClientModel( max_tokens=2096, temperature=0.5, model_id='Qwen/Qwen2.5-Coder-32B-Instruct', custom_role_conversions=None, ) # Importer l'outil depuis le Hub image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True) with open("prompts.yaml", 'r') as stream: prompt_templates = yaml.safe_load(stream) agent = CodeAgent( model=model, tools=[final_answer], # ajoutez vos outils ici (ne supprimez pas final_answer) max_steps=6, verbosity_level=1, grammar=None, planning_interval=None, name=None, description=None, prompt_templates=prompt_templates # Transmettre le prompt du système à CodeAgent ) GradioUI(agent).launch() ``` Votre **objectif** est de vous familiariser avec le *Space* et l'agent. Actuellement, l'agent dans le patron **n'utilise aucun outil, alors essayez de lui fournir certains des outils préfabriqués ou même de créer de nouveaux outils vous-même !** Nous attendons avec impatience vos incroyables agents dans le canal Discord **#agents-course-showcase**! --- Félicitations, vous avez construit votre premier Agent ! N'hésitez pas à le partager avec vos amis et collègues. Comme c'est votre première tentative, il est tout à fait normal qu'il soit un peu bogué ou lent. Dans les unités futures, nous apprendrons à construire de meilleurs agents. La meilleure façon d'apprendre est d'essayer, alors n'hésitez pas à le mettre à jour, à ajouter plus d'outils, à essayer avec un autre modèle, etc. Dans la prochaine section, vous allez remplir le quiz final et obtenir votre certificat !
agents-course/units/fr/unit1/tutorial.mdx/0
{ "file_path": "agents-course/units/fr/unit1/tutorial.mdx", "repo_id": "agents-course", "token_count": 4376 }
11
# Introduction au *LlamaHub* ***LlamaHub* est un registre de centaines d'intégrations, d'*agents* et d'*outils* que vous pouvez utiliser dans LlamaIndex.** ![LlamaHub](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/llama-index/llama-hub.png) Nous utiliserons diverses intégrations dans ce cours, alors examinons d'abord le *LlamaHub* et comment il peut nous aider. Voyons comment trouver et installer les dépendances pour les *components* dont nous avons besoin. ## Installation Les instructions d'installation de LlamaIndex sont disponibles comme un **aperçu bien structuré sur [*LlamaHub*](https://llamahub.ai/)**. Cela peut être un peu démoralisant au début, mais la plupart des **commandes d'installation suivent généralement un format facile à retenir** : ```bash pip install llama-index-{component-type}-{framework-name} ``` Essayons d'installer les dépendances pour un *component* *LLM* et *embedding* en utilisant l'[intégration de l'API d'inférence *Hugging Face*](https://llamahub.ai/l/llms/llama-index-llms-huggingface-api?from=llms). ```bash pip install llama-index-llms-huggingface-api llama-index-embeddings-huggingface ``` ## Utilisation Une fois installé, nous pouvons voir les motifs d'utilisation. Vous remarquerez que les chemins d'importation suivent la commande d'installation ! Ci-dessous, nous pouvons voir un exemple d'utilisation de **l'API d'inférence Hugging Face pour un *component* LLM**. ```python from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI import os from dotenv import load_dotenv # Charger le fichier .env load_dotenv() # Récupérer HF_TOKEN à partir des variables d'environnement hf_token = os.getenv("HF_TOKEN") llm = HuggingFaceInferenceAPI( model_name="Qwen/Qwen2.5-Coder-32B-Instruct", temperature=0.7, max_tokens=100, token=hf_token, ) response = llm.complete("Hello, how are you?") print(response) # Je suis bon, comment puis-je vous aider aujourd'hui ? ``` Parfait, nous savons maintenant comment trouver, installer et utiliser les intégrations pour les *components* dont nous avons besoin. **Approfondissons les *components*** et voyons comment nous pouvons les utiliser pour construire nos propres agents.
agents-course/units/fr/unit2/llama-index/llama-hub.mdx/0
{ "file_path": "agents-course/units/fr/unit2/llama-index/llama-hub.mdx", "repo_id": "agents-course", "token_count": 834 }
12
![smolagents banner](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/smolagents/license_to_call.png) # Pourquoi utiliser smolagents Dans ce module, nous explorerons les avantages et les inconvénients de l'utilisation de [smolagents](https://huggingface.co/docs/smolagents/en/index), vous aidant à prendre une décision éclairée pour savoir si c'est le bon *framework* pour vos besoins. ## Qu'est-ce que `smolagents` ? `smolagents` est un *framework* simple mais puissant pour construire des agents. Il fournit aux LLM la capacité d'agir (_agency_) pour interagir avec le monde réel, comme effectuer des recherches ou générer des images. Comme nous l'avons appris dans l'Unité 1, les agents sont des programmes qui utilisent des LLM pour générer des **raisonnements** basés sur des **observations** afin d'effectuer des **actions**. Explorons comment cela est implémenté dans *smolagents*. ### Principaux avantages de `smolagents` - **Simplicité :** Complexité de code et abstractions minimales, pour rendre le *framework* facile à comprendre, adopter et étendre - **Support LLM flexible :** Fonctionne avec n'importe quel LLM grâce à l'intégration avec les outils Hugging Face et les API externes - **Approche orientée code :** Support de première classe pour les *agents à code* qui écrivent leurs actions directement en code, éliminant le besoin d'analyse syntaxique et simplifiant l'appel d'outils - **Intégration au Hub d'Hugging Face :** Intégration transparente avec le Hub, permettant l'utilisation de *Spaces* Gradio comme outils ### Quand utiliser smolagents ? Avec ces avantages en tête, quand devrions-nous utiliser *smolagents* plutôt que d'autres *frameworks* ? *smolagents* est idéal quand : - Vous avez besoin d'une **solution légère et minimale.** - Vous voulez **expérimenter rapidement** sans configurations complexes. - Votre **logique d'application est simple.** ### Actions via code vs. via JSON Contrairement à d'autres *frameworks* où les agents écrivent des actions en JSON, `smolagents` **se concentre sur les appels d'outils en code**, simplifiant le processus d'exécution. C'est parce qu'il n'y a pas besoin d'analyser le JSON pour construire du code qui appelle les outils : la sortie peut être exécutée directement. Le diagramme suivant illustre cette différence : ![Code vs. JSON actions](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/code_vs_json_actions.png) Pour revoir la différence entre les actions via code vs. via JSON, vous pouvez revisiter [la section Actions dans l'Unité 1](https://huggingface.co/learn/agents-course/unit1/actions#actions-enabling-the-agent-to-engage-with-its-environment). ### Types d'agents dans `smolagents` Les agents dans `smolagents` fonctionnent comme des **agents multi-étapes**. Chaque [`MultiStepAgent`](https://huggingface.co/docs/smolagents/main/en/reference/agents#smolagents.MultiStepAgent) effectue : - Un raisonnement - Un appel et une exécution d'outil En plus d'utiliser **[CodeAgent](https://huggingface.co/docs/smolagents/main/en/reference/agents#smolagents.CodeAgent)** comme type principal d'agent, *smolagents* supporte également **[ToolCallingAgent](https://huggingface.co/docs/smolagents/main/en/reference/agents#smolagents.ToolCallingAgent)**, qui écrit des appels d'outils en JSON. Nous explorerons chaque type d'agent plus en détail dans les sections suivantes. <Tip> Dans smolagents, les outils sont définis en utilisant le décorateur <code>@tool</code> enveloppant une fonction Python ou la classe <code>Tool</code>. </Tip> ### Intégration de modèles dans `smolagents` `smolagents` supporte une intégration flexible des LLM, vous permettant d'utiliser n'importe quel modèle appelable qui répond à [certains critères](https://huggingface.co/docs/smolagents/main/en/reference/models). Le *framework* fournit plusieurs classes prédéfinies pour simplifier les connexions aux modèles : - **[TransformersModel](https://huggingface.co/docs/smolagents/main/en/reference/models#smolagents.TransformersModel) :** Implémente un pipeline `transformers` local pour une intégration transparente. - **[InferenceClientModel](https://huggingface.co/docs/smolagents/main/en/reference/models#smolagents.InferenceClientModel) :** Supporte les appels d'[inférence serverless](https://huggingface.co/docs/huggingface_hub/main/en/guides/inference) via [l'infrastructure d'Hugging Face](https://huggingface.co/docs/api-inference/index), ou via un nombre croissant de [fournisseurs d'inférence tiers](https://huggingface.co/docs/huggingface_hub/main/en/guides/inference#supported-providers-and-tasks). - **[LiteLLMModel](https://huggingface.co/docs/smolagents/main/en/reference/models#smolagents.LiteLLMModel) :** Tire parti de [LiteLLM](https://www.litellm.ai/) pour des interactions légères avec les modèles. - **[OpenAIServerModel](https://huggingface.co/docs/smolagents/main/en/reference/models#smolagents.OpenAIServerModel) :** Se connecte à tout service offrant une interface API OpenAI. - **[AzureOpenAIServerModel](https://huggingface.co/docs/smolagents/main/en/reference/models#smolagents.AzureOpenAIServerModel) :** Supporte l'intégration avec tout déploiement Azure OpenAI. Cette flexibilité garantit que les développeurs peuvent choisir le modèle et le service les plus adaptés à leurs cas d'usage spécifiques, et permet une expérimentation facile. Maintenant que nous avons compris pourquoi et quand utiliser *smolagents*, plongeons plus profondément dans cette puissante bibliothèque ! ## Ressources - [Blog smolagents](https://huggingface.co/blog/smolagents) - Introduction à smolagents et aux interactions par code
agents-course/units/fr/unit2/smolagents/why_use_smolagents.mdx/0
{ "file_path": "agents-course/units/fr/unit2/smolagents/why_use_smolagents.mdx", "repo_id": "agents-course", "token_count": 1940 }
13
# AI 에이전트 코스에 오신걸 환영합니다 🤗 [[introduction]] <figure> <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit0/thumbnail.jpg" alt="AI Agents Course thumbnail" width="100%"/> <figcaption>이미지 배경은 <a href="https://scenario.com/">Scenario.com 을 활용하여 제작되었습니다.</a> </figcaption> </figure> 오늘날 AI에서 가장 흥미로운 주제인 **에이전트(Agents)**에 오신 것을 환영합니다! 이 무료 코스에서는 **초급부터 전문가 수준**까지, AI 에이전트를 이해하고 활용하며 직접 구축하는 방법을 배울 수 있습니다. 첫 번째 유닛에서는 다음과 같은 내용을 다룹니다: - **강의 커리큘럼** 살펴보기 - **수강 방식 선택** (자기주도 학습 또는 인증 과정) - **인증 과정 및 마감일 정보** - 코스 운영팀 소개 - **Hugging Face** 계정 만들기. - **Discord 서버** 가입하고 다른 학습자 및 강사들과 소통하기 지금 바로 시작해 보세요! ## 이 코스에서 무엇을 배울 수 있나요? [[expect]] 해당 코스에서는 다음과 같은 내용을 학습합니다: - 📖 AI 에이전트의 **이론, 설계, 실전 활용**에 대해 공부합니다. - 🧑‍💻 [smolagents](https://huggingface.co/docs/smolagents/en/index), [LangChain](https://www.langchain.com/), and [LlamaIndex](https://www.llamaindex.ai/) 등의 **AI 에이전트 라이브러리** 활용법을 배웁니다. - 💾 Hugging Face Hub에 **자신이 만든 에이전트**를 공유하고, 커뮤니티에서 제작한 에이전트를 탐색합니다. - 🏆 **다른 학습자의 에이전트와 비교 평가**하는 챌린지에 참여합니다. - 🎓 과제를 완료하면 **수료 인증서**를 받을 수 있습니다. 그 외에도 다양한 내용을 다룹니다! 이 코스를 마치면 **AI 에이전트의 동작 원리를 이해하고, 최신 라이브러리와 도구를 활용하여 직접 구현하는 방법**을 익히게 됩니다. 👉 <a href="https://bit.ly/hf-learn-agents">지금 바로 코스에 등록하세요!</a> (HuggingFace는 개인정보 보호를 존중합니다. 이메일 주소는 **각 단원 공개시 링크, 챌린지 및 업데이트 정보**를 제공하는 용도로만 사용됩니다.) ## 이 코스는 어떻게 진행되나요? [[course-look-like]] 이 코스는 다음과 같이 구성됩니다: - *기본 개념 학습*: 에이전트 개념을 **이론적**으로 배우는 단계입니다. - *실습*: **기존 AI 에이전트 라이브러리**를 활용해 특정 환경에서 에이전트를 훈련하는 방법을 배웁니다. 실습은 사전 구성된 환경을 제공하는 **Hugging Face Spaces**에서 진행됩니다. - *실전 적용 과제*: 배운 개념을 활용해 현실 문제를 해결하는 과제입니다. - *챌린지*: 여러분이 개발한 에이전트를 다른 에이전트와 경쟁시켜 볼 수 있습니다. 또한, 에이전트 성능을 비교할 수 있는 [리더보드](https://huggingface.co/spaces/huggingface-projects/AI-Agents-Leaderboard) 도 곧 제공될 예정입니다. **에이전트 코스는 여러분의 피드백과 기여를 통해 발전되는 프로젝트입니다 !** [GitHub에서 이슈나 PR을 제출하거나](https://github.com/huggingface/agents-course), Discord 에서 토론에 참여해주세요! 코스를 완료한 후에는 [👉 이 폼](https://docs.google.com/forms/d/e/1FAIpQLSe9VaONn0eglax0uTwi29rIn4tM7H2sYmmybmG5jJNlE5v0xA/viewform?usp=dialog) 을 통해 피드백을 보낼 수 있습니다. ## 코스 개요 [[syllabus]] **전체적인 코스 커리큘럼**입니다. 각 단원 세부 주제 목록들은 해당 단원 공개 시 함께 제공됩니다. | 단원 | 주제 | 설명 | | :---- | :---- | :---- | | 0 | 온보딩 | 강의에서 사용할 도구 및 플랫폼을 설정합니다. | | 1 | 에이전트 기본 개념 | 도구, 사고 과정, 행동, 관찰 및 해당 형식에 대해 설명합니다. 또한 LLM, 메세지, 특수 토큰, 채팅 템플릿에 대해 설명하고, python 함수를 도구로 사용하는 간단한 사례를 소개합니다. | | 1.5 | Bonus : 함수 호출을 위한 LLM 미세 조정 | LoRa 를 사용하여 노트북 내에서 함수 호출을 수행하는 모델을 미세 조정합니다. | | 2 | 프레임워크 | 기본 개념이 인기 라이브러리 smolagents, LangGraph, LLamaIndex 에서 어떻게 구현되는지 살펴봅니다. | | 3 | 실전 적용 사례 | 실제 활용 사례를 구현해봅니다. (경험이 있는 에이전트 개발자분들의 PR 환영 🤗) | | 4 | 최종 과제 | 특정 벤치마크를 위한 에이전트를 구현하고, 학생 리더보드에서 성능을 평가합니다. 🚀 | *보너스 단원도 제공되니 기대해 주세요!* ## 선수 지식 [[what-are-the-prerequisites]] 이 코스를 완주하기 위해 다음과 같은 기본 지식이 필요합니다: - Python 기본지식 - LLM 기본 개념 (1단원에서 LLM 복습 섹션을 제공합니다.) ## 필요 도구 [[tools]] 코스를 수강하기 위해 단 2가지만 필요합니다: - *인터넷이 연결된 컴퓨터* - *Hugging Face 계정*: 모델 및 에이전트를 푸쉬/업로드하고 Spaces를 생성하는 데 필요합니다. 계정이 없으시다면, **[이곳](https://hf.co/join)** 에서 무료로 생성 할 수 있습니다. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit0/tools.jpg" alt="Course tools needed" width="100%"/> ## 인증 과정 [[certification-process]] <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit0/three-paths.jpg" alt="Two paths" width="100%"/> 이 코스는 *자유 수강 모드*로 진행할 수도 있고, 활동을 수행하여 *두 가지 인증서 중 하나*를 받을 수도 있습니다. 자유 수강 모드에서는 원하는 경우 과제와 챌린지에 참여할 수 있으며, **별도로 인증을 신청할 필요가 없습니다.** 인증 과정은 **무료**입니다: - *기본 개념 인증서*: 1단원을 완료해야합니다. *최신 에이전트 트렌드를 배우고자 하는 학생들을 위한 과정* - *완료 인증서*: 1단원, 실전 활용 사례 과제 중 하나, 최종 과제를 완료해야합니다. 인증 과정에는 마감기한이 있으며, 모든 과제는**2025년 5월 1일 이전에** 완료해야 합니다. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit0/deadline.jpg" alt="Deadline" width="100%"/> ## 권장 학습 속도 [[recommended-pace]] 코스 각 단원은 **1주일 이내**에 완료할 수 있도록 설계되었으며, **주당 약 3-4시간**의 학습 시간이 필요합니다. 인증 과정 마감 기한이 있기 때문에, 권장 학습 속도를 제공해드립니다! <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit0/recommended-pace.jpg" alt="Recommended Pace" width="100%"/> ## 코스 최대한 활용하는 방법 [[advice]] 코스를 최대한 활용할 수 있는 방법을 제안해 드립니다: 1. <a href="https://discord.gg/UrrTSsSyjb"> Discord에서 스터디 그룹에 참여하세요.</a>: 그룹으로 학습하는 것이 효과적입니다. 지금 바로 Discord 서버에 가입하고 Hugging Face 계정을 인증하세요! 2. **퀴즈와 과제를 수행하세요**: 가장 좋은 학습 방법은 실습과 자기 평가입니다. 3. **일정을 정하고 꾸준히 학습하세요**: 아래 권장 학습 속도를 참고하시거나, 자신만의 일정을 만들어 보세요.. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit0/advice.jpg" alt="Course advice" width="100%"/> ## 우리는 누구인가 [[who-are-we]] 저자 소개: ### Joffrey Thomas [[joffrey-thomas]] Joffrey는 Hugging Face의 머신러닝 엔지니어로, AI 에이전트를 구현하고 실제 환경에 배포한 경험이 있습니다. Joffrey는 이 코스의 메인 강사입니다. - [Joffrey Hugging Face에서 팔로우 하기](https://huggingface.co/Jofthomas) - [Joffrey X에서 팔로우 하기](https://x.com/Jthmas404) - [Joffrey Linkedin에서 팔로우 하기](https://www.linkedin.com/in/joffrey-thomas/) ### Ben Burtenshaw [[ben-burtenshaw]] Ben은 Hugging Face의 머신러닝 엔지니어로, 다양한 플랫폼에서 강의 경험이 있습니다. Ben의 목표는 이 코스를 모든 사람이 접근할 수 있도록 만드는 것 입니다. - [Ben Hugging Face에서 팔로우 하기](https://huggingface.co/burtenshaw) - [Ben X에서 팔로우 하기](https://x.com/ben_burtenshaw) - [Ben Linkedin에서 팔로우 하기](https://www.linkedin.com/in/ben-burtenshaw/) ### Thomas Simonini [[thomas-simonini]] Thomas는 Hugging Face의 머신러닝 엔지니어로, HuggingFace의 <a href="https://huggingface.co/learn/deep-rl-course/unit0/introduction">Deep RL</a>코스와 <a href="https://huggingface.co/learn/ml-games-course/en/unit0/introduction">ML for games</a> 코스를 진행했습니다. Thomas는 에이전트의 큰 팬으로, 커뮤니티가 무엇을 만들지 기대하고 있습니다! - [Thomas Hugging Face에서 팔로우 하기 ](https://huggingface.co/ThomasSimonini) - [Thomas X에서 팔로우 하기](https://x.com/ThomasSimonini) - [Thomas Linkedin에서 팔로우 하기](https://www.linkedin.com/in/simoninithomas/) ## 감사의 말씀 [[acknowledgments]] 이 코스에 중요한 기여를 해주신 다음 분들께 감사의 말씀을 전합니다: - **[Pedro Cuenca](https://huggingface.co/pcuenq)** – 자료 검토 지도와 전문적인 도움 - **[Aymeric Roucher](https://huggingface.co/m-ric)** – 디코딩 및 최종 에이전트 데모 스페이스와 smolagents 파트 도움 - **[Joshua Lochner](https://huggingface.co/Xenova)** – 토큰화 데모 스페이스 - **[Quentin Gallouédec](https://huggingface.co/qgallouedec)** – 코스 내용에 대한 도움 - **[David Berenstein](https://huggingface.co/davidberenstein1957)** – 코스 내용 및 조정 도움 ## 버그 발견& 강의 개선점 제안! [[contribute]] 기여는 **환영**입니다 🤗 - 만약 *노트북에서 버그🐛*를 발견하셨다면, <a href="https://github.com/huggingface/agents-course/issues">이슈</a>를 열고 **문제를 설명해주세요**. - 만약 *코스를 개선하고 싶다면*, <a href="https://github.com/huggingface/agents-course/pulls"> 풀 리쿼스트</a>를 열어주세요. - *전체 섹션 또는 새로운 단원*을 추가하고 싶다면, 가장 좋은 방법은<a href="https://github.com/huggingface/agents-course/issues">이슈</a>를 열고 **추가하고 싶은 내용을 설명해주세요! 이후 저희가 내용 작성을 시작하실 수 있도록 안내해드리겠습니다.** ## 그 외에도 질문이 있으시다면? [[questions]] <a href="https://discord.gg/UrrTSsSyjb">discord 서버의 #ai-agents-discussions.</a>채널에 질문을 남겨주세요. 코스 학습에 앞서 필요한 모든 정보를 습득하셨으니, 출발 준비를 해봅시다!⛵ <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit0/time-to-onboard.jpg" alt="Time to Onboard" width="100%"/>
agents-course/units/ko/unit0/introduction.mdx/0
{ "file_path": "agents-course/units/ko/unit0/introduction.mdx", "repo_id": "agents-course", "token_count": 8065 }
14
# 에이전트란? [[what-is-an-agent]] <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/whiteboard-no-check.jpg" alt="Unit 1 planning"/> 이 섹션이 끝날 때 쯤이면, 여러분들은 에이전트의 개념과 AI에서의 응용 사례들을 이해하실 수 있을 것입니다. 에이전트가 무엇인지, 한 예시를 들어 설명하겠습니다. ## 큰 그림 : 에이전트 알프레드 (Alfred) [[the-big-picture-alfred-the-agent]] **에이전트** 알프레드를 만나보세요! <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/this-is-alfred.jpg" alt="This is Alfred"/> 알프레드는 **명령을 받습니다.** : "알프레드, 커피 한잔 부탁해요." <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/coffee-please.jpg" alt="I would like a coffee"/> 알프레드는 **자연어를 이해**하므로, 우리의 요청을 빠르게 파악합니다. 주문을 수행하기 전에, Alfred는 **추론과 계획**을 통해 필요한 단계와 도구를 파악합니다: 1. 주방에 간다. 2. 커피머신을 사용한다. 3. 커피를 내린다. 4. 커피를 가져온다. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/reason-and-plan.jpg" alt="Reason and plan"/> 알프레드는 계획을 세운 후, **행동**을 해야 합니다. 알프레드는 세운 계획을 실행하기 위해, 알고 있는 **도구 목록에서 도구**를 사용할 수 있습니다. 이 경우, 커피를 만들기 위해 커피 머신을 사용합니다. 알프레드는는 커피 머신을 작동시켜 커피를 내립니다. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/make-coffee.jpg" alt="Make coffee"/> 마지막으로, Alfred는 신선하게 내린 커피를 우리에게 가져옵니다. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/bring-coffee.jpg" alt="Bring coffee"/> 이것이 바로 에이전트입니다: **추론, 계획, 환경과 상호작용하는 AI 모델** 우리는 이것을 에이전트라고 부르는데, 왜냐하면 _주체성_을 가지고 있기 때문입니다. 즉, 환경과 상호작용할 수 있는 능력을 가지고 있습니다. <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/process.jpg" alt="Agent process"/> ## 좀 더 이론적인 부분을 살펴봅시다 [[lets-go-more-formal]] 전체 그림을 이해한 후, 이제 더 정확한 정의를 내려봅시다: > 에이전트는 사용자가 정의한 목표를 달성하기 위해 환경과 상호작용하는 AI 모델을 이용하는 시스템입니다. 이 시스템은 추론, 계획, 실행을 결합하여 (종종 외부 도구를 통해)작업을 완료합니다. 에이전트는 두 가지 주요 부분으로 나눌 수 있습니다: 1. **두뇌 (AI 모델)** 이곳에서 모든 사고가 일어납니다. AI 모델은 **추론과 계획**을 처리합니다. **상황에 맞게 어떤 행동**을 취할지 결정을 내립니다. 2. **몸 (기능과 도구)** 이 부분은 에이전트가 수행할 수 있는 **모든 작업**을 나타냅니다. **가능한 행동의 범위**는 에이전트가 **어떤 도구**를 가지고 있는지에 달려 있습니다. 예를 들어, 인간은 날개가 없기 때문에 "날기" 행동을 할 수 없지만, "걷기", "달리기", "점프하기", "잡기"와 같은 **행동**은 수행할 수 있습니다. ## 에이전트에는 어떤 AI 모델을 사용하나요? [[what-type-of-ai-models-do-we-use-for-agents]] 에이전트에서 가장 일반적인 AI 모델은 **LLM (Large Language Model)**입니다. 이는 **텍스트**를 입력으로 받아 **텍스트**를 출력하는 모델입니다. 잘 알려진 예로는 **OpenAI의 GPT4, Meta의 LLaMA, Google의 Gemini** 등이 있습니다. 이러한 모델들은 방대한 텍스트 데이터로 학습되어 잘 일반화됩니다. LLM에 대해서는 [다음 섹션](what-are-llms)에서 더 배울 수 있습니다. <Tip> 에이전트의 핵심 모델로 텍스트 외 다른 입력을 받는 모델을 사용할 수도 있습니다. 예를 들어, 이미지를 입력으로 이해할 수 있는 **비전 언어 모델 (VLM)**이 있습니다. 이번 섹션에서는 LLM에 집중하도록 하고, 이후 다른 모델들에 대해서도 다룰 것입니다. </Tip> ## 이 환경에서 AI는 어떤 행동을 취하나요? [[how-does-an-ai-take-action-on-its-environment]] LLMs는 뛰어난 모델이지만, **텍스트**만 생성할 수 있습니다. 그런데, 사용자가 HuggingChat이나 ChatGPT같은 유명 채팅 애플리케이션에서 이미지 생성을 요청하면, 요청대로 이미지를 생성해 줍니다! 이것이 어떻게 가능 할까요? 그 이유는 HuggingChat, ChatGPT의 개발자들이 **도구(Tools) 기능**을 추가했기 때문입니다. 이 도구를 사용하면 LLM이 이미지를 생성할 수 있습니다. <figure> <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/eiffel_brocolis.jpg" alt="Eiffel Brocolis"/> <figcaption>The model used an Image Generation Tool to generate this image. </figcaption> </figure> 도구에 대해서는 [도구](tools) 섹션에서 더 깊게 배우도록 하겠습니다. ## 에이전트는 어떤 작업을 수행할 수 있나요? [[what-type-of-tasks-can-an-agent-do]] 에이전트는 **도구**를 통해 **행동**을 완수하도록 어떠한 작업도 수행 가능합니다. 예를 들어, 나만의 개인 비서 역할을 하는 에이전트(Siri같은)를 내 컴퓨터에 심고, "오늘 회의를 연기해달라고 매니저에게 이메일을 보내줘"라고 요청하면, 이메일을 보내는 코드도 제공할 수 있습니다. 이렇게 하면 이메일을 보낼 때마다 에이전트가 사용할 수 있는 새로운 도구가 됩니다. 이를 Python으로 작성하게 되면: ```python def send_message_to(recipient, message): """수신자에게 이메일을 보내는 데 유용한 함수""" ... ``` LLM은 이 도구를 실행할 코드를 생성하여 요청된 작업을 완수할 수 있습니다. ```python send_message_to("Manager", "오늘 미팅을 연기할 수 있을 까요?") ``` **도구 설계**는 에이전트의 성능에 큰 영향을 미칩니다. 일부 작업은 매우 구체적인 도구를 필요로 할 수 있으며, 다른 작업은 "웹 검색"과 같은 일반적인 도구로 해결할 수 있습니다. > **행동(Action)**과 **도구(Tools)**는 다릅니다. 예를 들어, 하나의 행동에서 여러가지 도구를 사용할 수 있습니다. 에이전트가 환경과 상호작용할 수 있게 한다는 것은 **기업과 개인들이 실제로 사용할** 수 있도록 하는 것을 의미합니다. ### 예시 1: 개인 가상 비서 [[example-1-personal-virtual-assistants]] Siri, Alexa, Google Assistant와 같은 가상 비서는 사용자를 대신해서 디지털 환경에서 에이전트로서 작동합니다. 이들은 사용자 쿼리를 처리하고, 문맥을 분석하며, 데이터베이스에서 정보를 검색하고, 응답을 제공하거나 작업을 시작합니다 (예: 알림 설정, 메시지 전송, 스마트 디바이스 제어 등). ### 예시 2: 고객 서비스 챗봇 [[example-2-customer-service-chatbots]] 많은 기업들이 고객과 자연어로 소통 가능한 챗봇을 에이전트로 배포하고 있습니다. 이 에이전트들은 질문에 답하거나, 문제 해결 단계를 안내하거나, 내부 데이터베이스에서 이슈를 열거나, 심지어 거래도 할 수 있습니다. 그들의 목표는 사용자 만족도를 높이거나, 대기 시간을 줄이거나, 판매 전환율을 높이는 것 등입니다. 고객과 직접 상호작용하고, 대화를 통해 학습하며, 시간이 지남에 따라 응답을 조정하는데, 이러한 에이전트들은 에이전트의 핵심 원칙을 보여줍니다. ### 예시 3: 게임 속 AI NPC 캐릭터 [[example-3-ai-non-playable-character-in-a-video-game]] LLM 기반의 AI 에이전트는 비 플레이어 캐릭터(NPC)를 더 역동적이고 예측 불가능하게 만들 수 있습니다. 정해진 행동 패턴을 따르기보다는, **문맥에 맞게 답변하고, 플레이어와의 상호작용에 반응하며**, 더 세련된 대화를 생성합니다. 이 유연성은 플레이어의 행동에 따라 발전하는 생동감 있는 캐릭터를 만들어냅니다. --- 요약하자면, 에이전트는 **AI 모델 (주로 LLM)**을 핵심 추론 엔진으로 사용하여: - **자연어 이해** : 인간의 지시를 의미 있게 해석하고 반응합니다. - **추론하고 계획**: 정보를 분석하고, 결정을 내리며, 문제를 해결하기 위한 전략을 세웁니다. - **환경과 상호작용**: 정보를 수집하고, 행동을 취하며, 그 결과를 관찰합니다. 이제 여러분은 에이전트에 대해 확실히 배웠으니, 짧은 퀴즈로 배운 내용을 점검한 후, “에이전트의 두뇌”인 [LLM](what-are-llms)에 대해 더 알아보도록 합시다!
agents-course/units/ko/unit1/what-are-agents.mdx/0
{ "file_path": "agents-course/units/ko/unit1/what-are-agents.mdx", "repo_id": "agents-course", "token_count": 7018 }
15
# Библиотека Фиктивного Агента <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit1/whiteboard-unit1sub3DONE.jpg" alt="Раздел 1 планирование"/> Этот курс не зависит от фреймворка, потому что мы хотим **сфокусироваться на концепции AI агентов и не увязнуть в специфике конкретного фреймворка**. Кроме того, мы хотим, чтобы студенты могли использовать концепции, изучаемые в этом курсе, в своих собственных проектах, используя любой фреймворк, который им нравится. Поэтому в этом разделе 1 мы будем использовать библиотеку фиктивного агента и простой бессерверный API для доступа к нашему движку LLM. Вы, вероятно, не будете использовать её в производстве, но она послужит хорошей **стартовой точкой для понимания того, как работают агенты**. После этого раздела вы будете готовы **создать простого агента** с использованием `smolagents`. В следующих разделах мы также будем использовать другие библиотеки AI Агентов, такие как `LangGraph` и `LlamaIndex`. Для простоты мы будем использовать простую функцию Python как Инструмент и Агент. Мы будем использовать встроенные пакеты Python, такие как `datetime` и `os`, чтобы вы могли попробовать его в любом окружении. Вы можете отслеживать процесс [в этом блокноте](https://huggingface.co/agents-course/notebooks/blob/main/unit1/dummy_agent_library.ipynb) и **запустите код самостоятельно**. ## Бессерверный API В экосистеме Hugging Face есть удобная функция Бессерверный API (Serverless API), которая позволяет легко выполнять инференс для многих моделей. При этом не требуется установки или развертывания. ```python import os from huggingface_hub import InferenceClient ## Вам нужен токен с сайта https://hf.co/settings/tokens, убедитесь, что в качестве типа токена выбран 'read'. Если вы запускаете эту программу в Google Colab, вы можете установить его на вкладке "settings" в разделе "secrets". Обязательно назовите его "HF_TOKEN" os.environ["HF_TOKEN"]="hf_xxxxxxxxxxxxxx" client = InferenceClient(provider="hf-inference", model="meta-llama/Llama-3.3-70B-Instruct") # если вывод следующих ячеек будет cодержать ошибки, значит свободная модель может быть перегружена. Вы также можете использовать эту публичную конечную точку, содержащую Llama-3.2-3B-Instruct # client = InferenceClient("https://jc26mwg228mkj8dw.us-east-1.aws.endpoints.huggingface.cloud") ``` ```python output = client.text_generation( "The capital of France is", max_new_tokens=100, ) print(output) ``` вывод: ``` Париж. Столица Франции - Париж. Столица Франции - Париж. Столица Франции - Париж. Столица Франции - Париж. Столица Франции - Париж. Столица Франции - Париж. Столица Франции - Париж. Столица Франции - Париж. Столица Франции - Париж. Столица Франции - Париж. Столица Франции - Париж. Столица Франции - Париж. Столица Франции - Париж. Столица Франции - Париж. ``` Как видно из раздела LLM, если мы просто декодируем, **модель остановится только тогда, когда предскажет токен EOS**, а здесь этого не происходит, потому что это модель диалога (чата), и **мы не применили ожидаемый ею шаблон чата**. Если теперь добавить специальные токены, относящиеся к используемой нами <a href="https://huggingface.co/meta-llama/Llama-3.2-3B-Instruct">Llama-3.2-3B-Instruct модели</a>, поведение меняется, и теперь она выводит ожидаемый нами токен EOS. ```python prompt="""<|begin_of_text|><|start_header_id|>user<|end_header_id|> The capital of France is<|eot_id|><|start_header_id|>assistant<|end_header_id|>""" output = client.text_generation( prompt, max_new_tokens=100, ) print(output) ``` вывод: ``` Столица Франции - Париж. ``` Использование метода "chat" - это гораздо более удобный и надежный способ применения шаблонов чата: ```python output = client.chat.completions.create( messages=[ {"role": "user", "content": "Столица Франции - это"}, ], stream=False, max_tokens=1024, ) print(output.choices[0].message.content) ``` вывод: ``` Paris. ``` Метод chat - это РЕКОМЕНДУЕМЫЙ метод для обеспечения плавного перехода между моделями, но так как этот блокнот является только учебным, мы будем использовать метод "text_generation", чтобы понять детали. ## Фиктивный Агент В предыдущих разделах мы увидели, что суть библиотеки агента заключается в добавлении информации в системную подсказку. Эта системная подсказка немного сложнее, чем та, которую мы видели ранее, но она уже содержит: 1. **Информацию об инструментах**. 2. **Инструкции по циклу** (Мысль → Действие → Наблюдение) ``` Ответить на следующие вопросы как можно лучше. У тебя есть доступ к следующим инструментам: get_weather: Получение текущей погоды в заданном месте Способ использования инструментов заключается в указании json blob. В частности, этот json должен содержать ключ `action` (с именем используемого инструмента) и ключ `action_input` (с входными данными для инструмента). Единственные значения, которые должны быть в поле "action", это: get_weather: Получение текущей погоды в заданном месте, args: {"location": {"type": "string"}} пример использования: {{ "action": "get_weather", "action_input": {"location": "New York"} }} ВСЕГДА используй следующий формат: Вопрос: входной вопрос, на который необходимо ответить. Мысль: ты всегда должен думать о том, какое действие предпринять. Только одно действие за раз в этом формате: Действие: $JSON_BLOB (внутри markdown ячейки) Наблюдение: результат действия. Это наблюдение уникально, полно и является источником истины. ... (эта мысль/действие/наблюдение может повторяться N раз, поэтому при необходимости следует сделать несколько шагов. Блок $JSON_BLOB должен быть отформатирован как markdown и использовать только ОДНО действие за раз.) Ты всегда должен заканчивать свой вывод в следующем формате: Мысль: Теперь я знаю окончательный ответ. Окончательный ответ: окончательный ответ на исходный входной вопрос Теперь начинай! Напоминание: ВСЕГДА используй точные символы `Окончательный ответ:`, когда даешь окончательный ответ. ``` Поскольку мы используем метод «text_generation», нам нужно применить подсказку вручную: ``` prompt=f"""<|begin_of_text|><|start_header_id|>system<|end_header_id|> {SYSTEM_PROMPT} <|eot_id|><|start_header_id|>user<|end_header_id|> Какая погода в Лондоне? <|eot_id|><|start_header_id|>assistant<|end_header_id|> """ ``` Мы также можем сделать это следующим образом, что и происходит внутри метода `chat`: ``` messages=[ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": "Какая погода в Лондоне?"}, ] from transformers import AutoTokenizer tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-3.2-3B-Instruct") tokenizer.apply_chat_template(messages, tokenize=False,add_generation_prompt=True) ``` Теперь подсказка выглядит так: ``` <|begin_of_text|><|start_header_id|>system<|end_header_id|> Ответить на следующие вопросы как можно лучше. У тебя есть доступ к следующим инструментам: get_weather: Получение текущей погоды в заданном месте Способ использования инструментов заключается в указании json blob. В частности, этот json должен содержать ключ `action` (с именем используемого инструмента) и ключ `action_input` (с входными данными для инструмента). Единственные значения, которые должны быть в поле "action", это: get_weather: Получение текущей погоды в заданном месте, args: {"location": {"type": "string"}} пример использования: {{ "action": "get_weather", "action_input": {"location": "New York"} }} ВСЕГДА используй следующий формат: Вопрос: входной вопрос, на который необходимо ответить. Мысль: ты всегда должен думать о том, какое действие предпринять. Только одно действие за раз в этом формате: Действие: $JSON_BLOB (внутри markdown ячейки) Наблюдение: результат действия. Это наблюдение уникально, полно и является источником истины. ... (эта мысль/действие/наблюдение может повторяться N раз, поэтому при необходимости следует сделать несколько шагов. Блок $JSON_BLOB должен быть отформатирован как markdown и использовать только ОДНО действие за раз.) Ты всегда должен заканчивать свой вывод в следующем формате: Мысль: Теперь я знаю окончательный ответ. Окончательный ответ: окончательный ответ на исходный входной вопрос Теперь начинай! Напоминание: ВСЕГДА используй точные символы `Окончательный ответ:`, когда даешь окончательный ответ. <|eot_id|><|start_header_id|>user<|end_header_id|> Какая погода в Лондоне? <|eot_id|><|start_header_id|>assistant<|end_header_id|> ``` Давайте декодируем! ```python output = client.text_generation( prompt, max_new_tokens=200, ) print(output) ``` вывод: ```` Действие: ``` { "action": "get_weather", "action_input": {"location": "London"} } ``` Мысль: Я проверю, какая погода в Лондоне. Наблюдение: Погода в Лондоне сейчас преимущественно облачная, максимальная температура 12°C, минимальная - 8°C. ```` Видите ли вы проблему? >Ответ был галлюцинирован моделью. Нам нужно остановиться, чтобы действительно выполнить функцию! Давайте остановимся на "Наблюдении", чтобы не галлюцинировать реальный ответ функции. ```python output = client.text_generation( prompt, max_new_tokens=200, stop=["Observation:"] # Давайте остановимся до того, как будет вызвана какая-либо реальная функция ) print(output) ``` вывод: ```` Действие: ``` { "action": "get_weather", "action_input": {"location": "London"} } ``` Мысль: Я проверю, какая погода в Лондоне. Наблюдение: ```` Намного лучше! Давайте создадим фиктивную функцию get weather. В реальной ситуации вы, скорее всего, вызовете API. ```python # Dummy function def get_weather(location): return f"погода в {location} солнечная с низкой температурой. \n" get_weather('London') ``` вывод: ``` 'погода в Лондоне солнечная с низкой температурой. \n' ``` Давайте скомбинируем базовую подсказку, сообщение о завершении выполнения функции и результат выполнения функции в виде Наблюдения и продолжим генерацию. ```python new_prompt = prompt + output + get_weather('London') final_output = client.text_generation( new_prompt, max_new_tokens=200, ) print(final_output) ``` Вот новая подсказка: ```` <|begin_of_text|><|start_header_id|>system<|end_header_id|> Ответить на следующие вопросы как можно лучше. У тебя есть доступ к следующим инструментам: get_weather: Получение текущей погоды в заданном месте Способ использования инструментов заключается в указании json blob. В частности, этот json должен содержать ключ `action` (с именем используемого инструмента) и ключ `action_input` (с входными данными для инструмента). Единственные значения, которые должны быть в поле "action", это: get_weather: Получение текущей погоды в заданном месте, args: {"location": {"type": "string"}} пример использования: {{ "action": "get_weather", "action_input": {"location": "New York"} }} ВСЕГДА используй следующий формат: Вопрос: входной вопрос, на который необходимо ответить. Мысль: ты всегда должен думать о том, какое действие предпринять. Только одно действие за раз в этом формате: Действие: $JSON_BLOB (внутри markdown ячейки) Наблюдение: результат действия. Это наблюдение уникально, полно и является источником истины. ... (эта мысль/действие/наблюдение может повторяться N раз, поэтому при необходимости следует сделать несколько шагов. Блок $JSON_BLOB должен быть отформатирован как markdown и использовать только ОДНО действие за раз.) Ты всегда должен заканчивать свой вывод в следующем формате: Мысль: Теперь я знаю окончательный ответ. Окончательный ответ: окончательный ответ на исходный входной вопрос Теперь начинай! Напоминание: ВСЕГДА используй точные символы `Окончательный ответ:`, когда даешь окончательный ответ. <|eot_id|><|start_header_id|>user<|end_header_id|> Какая погода в Лондоне? <|eot_id|><|start_header_id|>assistant<|end_header_id|> Действие: ``` { "action": "get_weather", "action_input": {"location": {"type": "string", "value": "London"} } ``` Мысль: Я проверю погоду в Лондоне. Наблюдение: погода в Лондоне солнечная с низкой температурой. ```` Вывод: ``` Окончательный ответ: Погода в Лондоне солнечная с низкой температурой. ``` --- Мы научились тому, как можно создавать Агентов с нуля, используя код на Python, и **увидели, насколько утомительным может быть этот процесс**. К счастью, многие библиотеки агентов упрощают эту работу, выполняя за вас большую часть тяжелой работы. Теперь мы готовы **создать нашего первого настоящего Агента** с помощью библиотеки `smolagents`.
agents-course/units/ru-RU/unit1/dummy-agent-library.mdx/0
{ "file_path": "agents-course/units/ru-RU/unit1/dummy-agent-library.mdx", "repo_id": "agents-course", "token_count": 10899 }
16
# Giới thiệu ![Hình ảnh minh họa chương bổ trợ 1](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/bonus-unit1/thumbnail.jpg) Chào mừng bạn đến với **chương bổ trợ đầu tiên** này, nơi ta sẽ học cách **tinh chỉnh (fine-tuning) Mô hình Ngôn ngữ Lớn (LLM) cho function calling**. Với LLMs, function calling đang nhanh chóng trở thành kỹ thuật *phải-biết*. Ý tưởng là thay vì chỉ dựa vào phương pháp prompt-based như trong chương 1, function calling sẽ huấn luyện model của bạn **thực hiện hành động và diễn giải quan sát trong giai đoạn training**, giúp AI trở nên mạnh mẽ hơn. > **Khi nào nên học chương bổ trợ này?** > > Phần này **không bắt buộc** và nâng cao hơn chương 1. Bạn có thể học ngay hoặc quay lại sau khi nâng cao kiến thức nhờ khóa học. > > Đừng lo, chương bổ trợ được thiết kế để cung cấp đầy đủ thông tin cần thiết. Chúng mình sẽ hướng dẫn bạn từng khái niệm cốt lõi về tinh chỉnh model cho function calling dù bạn chưa hiểu sâu về fine-tuning. Để học tốt chương bổ trợ này, bạn cần: 1. Biết cách Tinh chỉnh LLM với Transformers. Nếu chưa biết, [xem tại đây](https://huggingface.co/learn/nlp-course/chapter3/1?fw=pt). 2. Biết dùng `SFTTrainer` để tinh chỉnh model. Tìm hiểu thêm tại [tài liệu này](https://huggingface.co/learn/nlp-course/en/chapter11/1). --- ## Nội dung học 1. **Function Calling** Cách LLMs hiện đại tổ chức hội thoại hiệu quả để kích hoạt **Tools (công cụ)**. 2. **LoRA (Low-Rank Adaptation)** Phương pháp tinh chỉnh **nhẹ và hiệu quả** giúp giảm chi phí tính toán và lưu trữ. LoRA giúp huấn luyện model lớn *nhanh hơn, rẻ hơn, dễ triển khai hơn*. 3. **Chu trình Suy nghĩ → Hành động → Quan sát** trong model Function Calling Cách tiếp cận đơn giản nhưng mạnh mẽ để model quyết định khi nào (và cách nào) gọi function, theo dõi các bước trung gian, và diễn giải kết quả từ Tools/API bên ngoài. 4. **Token Đặc biệt Mới** Chúng ta sẽ giới thiệu **các marker đặc biệt** giúp model phân biệt: - Lý luận nội bộ kiểu "chain-of-thought" (luồng suy luận) - Lệnh gọi function - Phản hồi từ công cụ bên ngoài --- Kết thúc chương bổ trợ này, bạn sẽ có thể: - **Hiểu** cách hoạt động nội bộ của APIs khi sử dụng Tools - **Tinh chỉnh** model bằng kỹ thuật LoRA - **Triển khai** và **tùy chỉnh** chu trình Thought → Act → Observe để tạo workflow Function-calling mạnh mẽ - **Thiết kế và sử dụng** token đặc biệt để tách biệt lý luận nội bộ của model với hành động bên ngoài Và quan trọng nhất: **Bạn sẽ có model được tinh chỉnh để thực hiện function calling!** 🔥 Cùng khám phá **function calling** thôi!
agents-course/units/vi/bonus-unit1/introduction.mdx/0
{ "file_path": "agents-course/units/vi/bonus-unit1/introduction.mdx", "repo_id": "agents-course", "token_count": 1951 }
17
# Kiểm tra nhanh tự đánh giá (không chấm điểm) [[quiz2]] Gì nữa? Lại Quiz á? Chúng mình biết, chúng mình biết... 😅 Nhưng bài kiểm tra ngắn không chấm điểm này giúp bạn **củng cố các khái niệm quan trọng vừa học**. Quiz này bao gồm Mô hình ngôn ngữ lơn (LLM), hệ thống tin nhắn và tools - những thành phần thiết yếu để hiểu và xây dựng AI agent. ### Q1: Đâu là mô tả chính xác nhất về AI Tool? <Question choices={[ { text: "Quy trình chỉ tạo phản hồi văn bản", explain: "", }, { text: "Quy trình thực thi hoặc API bên ngoài cho phép Agent thực hiện tác vụ cụ thể và tương tác với môi trường bên ngoài", explain: "Tools là các hàm thực thi mà Agent có thể sử dụng để thực hiện tác vụ và tương tác với môi trường bên ngoài.", correct: true }, { text: "Tính năng lưu trữ hội thoại của Agent", explain: "", } ]} /> --- ### Q2: AI agent sử dụng Tools như hình thức "hành động" trong môi trường thế nào? <Question choices={[ { text: "Bằng cách thụ động chờ hướng dẫn từ người dùng", explain: "", }, { text: "Chỉ sử dụng các phản hồi được lập trình sẵn", explain: "", }, { text: "Bằng cách yêu cầu LLM sinh code gọi Tool khi cần và chạy Tool thay mặt mô hình", explain: "Agent có thể kích hoạt Tools và sử dụng luồng suy luận để lập kế hoạch/cập nhật kế hoạch dựa trên thông tin thu được.", correct: true } ]} /> --- ### Q3: Mô hình ngôn ngữ lớn (LLM) là gì? <Question choices={[ { text: "Chatbot đơn giản với các câu trả lời định sẵn", explain: "", }, { text: "Mô hình học sâu được huấn luyện trên lượng lớn văn bản để hiểu và tạo ngôn ngữ giống con người", explain: "", correct: true }, { text: "AI dựa trên luật với các lệnh định nghĩa cứng nhắc", explain: "", } ]} /> --- ### Q4: Vai trò của Token đặc biệt trong LLM là gì? <Question choices={[ { text: "Là các từ bổ sung trong từ vựng của mô hình để nâng cao chất lượng sinh văn bản", explain: "", }, { text: "Thực hiện chức năng cụ thể như đánh dấu cuối chuỗi (EOS) hoặc phân tách các vai trò tin nhắn trong mô hình chat", explain: "", correct: true }, { text: "Là token được chèn ngẫu nhiên để tăng tính đa dạng của phản hồi", explain: "", } ]} /> --- ### Q5: Mô hình AI Chat xử lý tin nhắn người dùng nội bộ thế nào? <Question choices={[ { text: "Trực tiếp diễn giải tin nhắn như lệnh có cấu trúc mà không biến đổi", explain: "", }, { text: "Chuyển đổi tin nhắn thành prompt định dạng bằng cách nối các tin nhắn system, user và assistant", explain: "", correct: true }, { text: "Sinh phản hồi ngẫu nhiên dựa trên hội thoại trước đó", explain: "", } ]} /> --- Hiểu rồi chứ? Tuyệt! Giờ hãy **khám phá luồng hoạt động đầy đủ của Agent và bắt đầu xây dựng AI agent đầu tiên thôi!**
agents-course/units/vi/unit1/quiz2.mdx/0
{ "file_path": "agents-course/units/vi/unit1/quiz2.mdx", "repo_id": "agents-course", "token_count": 2043 }
18
# 测验:评估 AI 智能体 让我们评估一下你对本附加单元中所涵盖的智能体追踪和评估概念的理解。 本次测验为可选,不计分。 ### Q1: AI 智能体中的可观测性主要指的是什么? 哪个陈述准确地描述了 AI 智能体可观测性的目的? <Question choices={[ { text: "它涉及通过日志、指标和跨度(spans)追踪内部操作,以理解智能体行为。", explain: "正确!可观测性意味着使用日志、指标和跨度来揭示智能体的内部运作。", correct: true }, { text: "它仅仅专注于降低运行智能体的财务成本。", explain: "可观测性涵盖成本,但不限于此。" }, { text: "它仅指智能体的外部外观和用户界面。", explain: "可观测性关注的是内部流程,而不是用户界面。" }, { text: "它只关心编码风格和代码美学。", explain: "在此背景下,代码风格与可观测性无关。" } ]} /> ### Q2: 以下哪项不是智能体可观测性中常见的监控指标? 选择通常不属于可观测性范畴的指标。 <Question choices={[ { text: "延迟", explain: "延迟通常被追踪以评估智能体的响应能力。" }, { text: "每次智能体运行的成本", explain: "监控成本是可观测性的一个关键方面。" }, { text: "用户反馈和评分", explain: "用户反馈对于评估智能体性能至关重要。" }, { text: "智能体的代码行数", explain: "代码行数不是典型的可观测性指标。", correct: true } ]} /> ### Q3: 什么最能描述 AI 智能体的离线评估? 确定正确离线评估本质的陈述。 <Question choices={[ { text: "在实时环境中使用真实用户交互来评估智能体。", explain: "这描述的是在线评估而非离线评估。" }, { text: "使用包含已知基准(ground truth)的精选数据集来评估智能体性能。", explain: "正确!离线评估使用测试数据集来衡量相对于已知答案的性能。", correct: true }, { text: "实时监控智能体的内部日志。", explain: "这更多地与可观测性相关,而非评估。" }, { text: "在没有任何评估指标的情况下运行智能体。", explain: "这种方法无法提供有意义的见解。" } ]} /> ### Q4: 智能体的在线评估提供了什么优势? 选择最能反映在线评估好处的陈述。 <Question choices={[ { text: "它使用预定义的数据集提供受控的测试场景。", explain: "受控测试是离线评估的好处,而非在线评估。" }, { text: "它捕获实时的用户交互和真实世界的性能数据。", explain: "正确!在线评估通过在实时环境中监控智能体来提供见解。", correct: true }, { text: "它消除了任何离线测试和基准测试的需要。", explain: "离线和在线评估都很重要且互为补充。" }, { text: "它仅仅专注于降低智能体的计算成本。", explain: "成本监控是可观测性的一部分,并非在线评估的主要优势。" } ]} /> ### Q5: OpenTelemetry 在 AI 智能体可观测性和评估中扮演什么角色? 哪个陈述最能描述 OpenTelemetry 在监控 AI 智能体中的作用? <Question choices={[ { text: "它提供了一个标准化的框架来检测代码,从而能够收集用于可观测性的追踪、指标和日志。", explain: "正确!OpenTelemetry 标准化了遥测数据的检测,这对于监控和诊断智能体行为至关重要。", correct: true }, { text: "它通过自动修复代码问题来替代手动调试。", explain: "错误。OpenTelemetry 用于收集遥测数据,而不是调试代码问题。" }, { text: "它主要用作存储历史日志的数据库,不具备实时能力。", explain: "错误。OpenTelemetry 专注于实时遥测数据收集并将数据导出到分析工具。" }, { text: "它通过自动调整模型参数来优化 AI 智能体的计算性能。", explain: "错误。OpenTelemetry 关注的是可观测性而非性能调优。" } ]} /> 恭喜你完成本次测验!🎉 如果你答错了任何问题,可以考虑复习本附加单元的内容以加深理解。如果你做得很好,那么你已经准备好探索智能体可观测性和评估方面更高级的主题了!
agents-course/units/zh-CN/bonus_unit2/quiz.mdx/0
{ "file_path": "agents-course/units/zh-CN/bonus_unit2/quiz.mdx", "repo_id": "agents-course", "token_count": 2975 }
19
# 小测验(不计分)[[quiz1]] 至此您已理解智能体的整体概念,包括其定义和工作原理。现在进行一个简短测验,因为**自我测试**是最佳学习方式,[可避免能力错觉](https://www.coursera.org/lecture/learning-how-to-learn/illusions-of-competence-BuFzf)。这将帮助您发现**需要加强的知识领域**。 本测验为可选项目,不计入评分。 ### 问题1:什么是智能体? 以下哪项最能描述AI智能体? <Question choices={[ { text: "仅处理静态文本且永不与环境交互的系统", explain: "智能体必须具备执行行动并与环境交互的能力", }, { text: "能够推理、规划并使用工具与环境交互以实现特定目标的人工智能模型", explain: "该定义完整涵盖了智能体的本质特征", correct: true }, { text: "仅回答问题但无行动能力的聊天机器人", explain: "此类聊天机器人缺乏执行行动的能力,因此不同于智能体", }, { text: "提供信息但无法执行任务的数字百科全书", explain: "智能体需主动与环境交互,而非仅提供静态信息" } ]} /> --- ### 问题2:规划在智能体中的作用是什么? 为什么智能体在执行行动前需要进行规划? <Question choices={[ { text: "用于记忆过往交互记录", explain: "规划关注的是确定未来行动,而非存储历史交互", }, { text: "确定行动序列并选择满足用户请求的适用工具", explain: "规划帮助智能体确定完成任务的最佳步骤及工具组合", correct: true }, { text: "生成无目的性的随机行动", explain: "规划确保智能体行动具有目的性,避免随机性", }, { text: "执行无需额外推理的文本翻译", explain: "规划涉及构建行动框架,而非简单的文本转换", } ]} /> --- ### 问题3:工具如何增强智能体的能力? 为什么工具对智能体至关重要? <Question choices={[ { text: "工具是冗余组件,不会影响智能体性能", explain: "工具通过支持超越文本生成的操作来扩展智能体能力", }, { text: "工具赋予智能体执行文本生成模型原生无法实现操作的能力,例如冲咖啡或生成图像", explain: "工具使智能体能够与现实世界交互并完成任务", correct: true }, { text: "工具仅用于存储记忆", explain: "工具主要用于执行操作,而非单纯存储数据", }, { text: "工具将智能体限制为仅能进行文本响应", explain: "相反,工具可帮助智能体突破纯文本响应的限制", } ]} /> --- ### 问题4:行动与工具有何区别? 行动和工具之间的关键差异是什么? <Question choices={[ { text: "行动是智能体采取的步骤,工具是智能体用于执行这些行动的外部资源", explain: "行动是高层级目标,工具是智能体可调用的具体功能", correct: true }, { text: "行动和工具是同一概念且可互换使用", explain: "行动是目标或任务,工具是智能体用于实现它们的具体工具", }, { text: "工具是通用性的,而行动仅用于物理交互", explain: "行动可同时包含数字和物理任务", }, { text: "行动需要大语言模型(LLMs)而工具不需要", explain: "虽然 LLMs 帮助决定行动,但行动本身并不依赖 LLMs" } ]} /> --- ### 问题5:大语言模型(LLMs)在智能体中扮演什么角色? LLMs 如何支持智能体的功能实现? <Question choices={[ { text: "作为静态数据库仅存储信息而不处理输入的大语言模型", explain: "大语言模型需主动处理文本输入并生成响应,而非仅作信息存储", }, { text: "作为智能体推理'大脑',通过处理文本输入理解指令并规划行动", explain: "大语言模型赋予智能体解释需求、制定计划并决策后续步骤的能力", correct: true }, { text: "仅用于图像处理而非文本处理的大语言模型", explain: "大语言模型主要处理文本,但也可支持多模态输入交互", }, { text: "未被使用的大语言模型", explain: "大语言模型是现代 AI 智能体的核心组件", } ]} /> --- ### 问题6:以下哪个例子最能体现 AI 智能体? 哪个现实场景最能展示工作中的 AI 智能体? <Question choices={[ { text: "网站上的静态常见问题页面", explain: "静态 FAQ 页面无法动态与用户交互或执行操作", }, { text: "类似 Siri 或 Alexa 的虚拟助手,能够理解语音指令、进行推理并执行设置提醒或发送消息等任务", explain: "该示例包含推理、规划及与环境交互的完整智能体特征", correct: true }, { text: "仅执行算术运算的基础计算器", explain: "计算器遵循固定规则,缺乏推理和规划能力,因此不属于智能体", }, { text: "遵循预设响应模式的游戏 NPC 角色", explain: "除非 NPC 具备推理、规划和工具使用能力,否则不能视为AI智能体" } ]} /> --- 恭喜完成测验 🥳!如果存在理解偏差,建议重读本章以巩固知识。若顺利通过,您已准备好深入探索"智能体大脑": LLMs。
agents-course/units/zh-CN/unit1/quiz1.mdx/0
{ "file_path": "agents-course/units/zh-CN/unit1/quiz1.mdx", "repo_id": "agents-course", "token_count": 3496 }
20
# 在 LlamaIndex 中使用智能体 还记得我们之前那位得力的管家智能体 Alfred 吗?现在他要迎来重大升级了! 在了解了 LlamaIndex 中的工具后,我们可以赋予 Alfred 新的能力来更好地服务我们。 不过在继续之前,让我们先回顾一下智能体(如 Alfred)的核心机制。 在第一单元中我们学习到: > 智能体是一个利用 AI 模型与环境交互以实现用户定义目标的系统。它通过结合推理、规划和动作执行(通常通过外部工具)来完成各种任务。 LlamaIndex 支持**三种主要类型的推理智能体**: ![智能体类型](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/llama-index/agents.png) 1. `函数调用智能体` - 适用于支持调用特定函数的 AI 模型 2. `ReAct 智能体` - 适用于具有聊天或文本完成能力的 AI 模型,擅长处理复杂推理任务 3. `高级自定义智能体` - 使用更复杂的方法处理高阶任务和工作流 <Tip>有关高级智能体的更多信息,请访问 <a href="https://github.com/run-llama/llama_index/blob/main/llama-index-core/llama_index/core/agent/workflow/base_agent.py">BaseWorkflowAgent</a></Tip> ## 初始化智能体 <Tip> 您可以通过 <a href="https://huggingface.co/agents-course/notebooks/blob/main/unit2/llama-index/agents.ipynb" target="_blank">这个 Notebook</a> 跟随代码实践(使用 Google Colab 运行)。 </Tip> 创建智能体时,我们首先需要为其提供**定义其能力的功能/工具集合**。 让我们看看如何使用基础工具创建智能体。当前实现中,智能体会自动使用函数调用 API(如果可用),或标准的 ReAct 智能体循环。 支持工具/函数 API 的 LLM 是相对较新的技术,它们通过避免特定提示工程、允许 LLM 根据提供的模式创建工具调用,提供了强大的工具调用能力。 ReAct 智能体同样擅长复杂推理任务,可与任何具备聊天或文本完成能力的 LLM 配合使用。这类智能体的响应更详细,会展示其决策背后的推理过程。 ```python from llama_index.llms.huggingface_api import HuggingFaceInferenceAPI from llama_index.core.agent.workflow import AgentWorkflow from llama_index.core.tools import FunctionTool # 定义示例工具--类型注释、函数名和 docstrings 都包含在解析的模式中! def multiply(a: int, b: int) -> int: """Multiplies two integers and returns the resulting integer""" return a * b # 初始化 llm llm = HuggingFaceInferenceAPI(model_name="Qwen/Qwen2.5-Coder-32B-Instruct") # 初始化 agent agent = AgentWorkflow.from_tools_or_functions( [FunctionTool.from_defaults(multiply)], llm=llm ) ``` **智能体默认是无状态的**,如需记忆过往交互,需显式使用 `Context` 对象。 这在需要记忆历史交互的场景中非常有用,例如:需要跨消息保持上下文的聊天机器人,或需要追踪长期任务进度的任务管理器。 ```python # stateless response = await agent.run("What is 2 times 2?") # remembering state from llama_index.core.workflow import Context ctx = Context(agent) response = await agent.run("My name is Bob.", ctx=ctx) response = await agent.run("What was my name again?", ctx=ctx) ``` 您会注意到 `LlamaIndex` 中的智能体采用异步模式(使用 Python 的 `await` 操作符)。如果您是 Python 异步编程的新手,或需要复习相关知识,请参考 [官方异步编程指南](https://docs.llamaindex.ai/en/stable/getting_started/async_python/)。 现在我们已经掌握基础知识,接下来让我们探索如何为智能体赋予更复杂的工具能力。 ## 使用 QueryEngineTools 创建 RAG 智能体 **智能体增强检索(Agentic RAG)** 是通过智能体实现数据问答的强大范式。我们可以为 Alfred 配备多种工具来辅助问题解答。 但不同于传统 RAG 直接基于文档回答问题,Alfred 能够自主决定是否使用其他工具或流程来响应查询。 ![智能体增强 RAG](https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit2/llama-index/agentic-rag.png) 将 `QueryEngine` 封装为智能体工具非常简单。 在此过程中,我们需要**定义工具名称和描述**,这些元数据将帮助 LLM 正确选择和使用工具。 以下示例演示如何基于[组件章节](02_components)创建的 `QueryEngine` 加载 `QueryEngineTool`: ```python from llama_index.core.tools import QueryEngineTool query_engine = index.as_query_engine(llm=llm, similarity_top_k=3) # as shown in the previous section query_engine_tool = QueryEngineTool.from_defaults( query_engine=query_engine, name="name", description="a specific description", return_direct=False, ) query_engine_agent = AgentWorkflow.from_tools_or_functions( [query_engine_tool], llm=llm, system_prompt="You are a helpful assistant that has access to a database containing persona descriptions. " ) ``` ## 创建多智能体系统 `AgentWorkflow` 类原生支持多智能体系统。通过为每个智能体分配名称和描述,系统可维护单一活跃会话主体,同时允许智能体之间进行任务交接。 通过精准定义每个智能体的职责边界,我们能够有效提升系统响应消息时的整体准确性。 **LlamaIndex 中的智能体也可直接作为其他智能体的工具**,这种设计支持构建复杂的定制化场景: ```python from llama_index.core.agent.workflow import ( AgentWorkflow, FunctionAgent, ReActAgent, ) # Define some tools def add(a: int, b: int) -> int: """Add two numbers.""" return a + b def subtract(a: int, b: int) -> int: """Subtract two numbers.""" return a - b # 创建智能体配置 # 注意:我们可以在此使用 FunctionAgent 或 ReActAgent。 # FunctionAgent 适用于具有函数调用 API 的 LLM。 # ReActAgent 适用于任何 LLM。 calculator_agent = ReActAgent( name="calculator", description="Performs basic arithmetic operations", system_prompt="You are a calculator assistant. Use your tools for any math operation.", tools=[add, subtract], llm=llm, ) query_agent = ReActAgent( name="info_lookup", description="Looks up information about XYZ", system_prompt="Use your tool to query a RAG system to answer information about XYZ", tools=[query_engine_tool], llm=llm ) # 创建并运行工作流程 agent = AgentWorkflow( agents=[calculator_agent, query_agent], root_agent="calculator" ) # 运行系统 response = await agent.run(user_msg="Can you add 5 and 3?") ``` <Tip>还没学够吗?在<a href="https://docs.llamaindex.ai/en/stable/examples/agent/agent_workflow_basic/">《AgentWorkflow 基本介绍》</a>或<a href="https://docs.llamaindex.ai/en/stable/understanding/agent/">《Agent 学习指南》</a>中,您可以了解到更多关于流媒体、上下文序列化和人在环路中的信息!</Tip> 现在我们已经掌握了 LlamaIndex 中智能体和工具的基础知识,接下来让我们探索如何利用 LlamaIndex 来**创建可配置、易管理的工作流**!
agents-course/units/zh-CN/unit2/llama-index/agents.mdx/0
{ "file_path": "agents-course/units/zh-CN/unit2/llama-index/agents.mdx", "repo_id": "agents-course", "token_count": 3993 }
21
<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/retrieval_agents.ipynb"}, ]} /> # 构建智能驱动的 RAG 系统 <Tip> 您可以通过 <a href="https://huggingface.co/agents-course/notebooks/blob/main/unit2/smolagents/retrieval_agents.ipynb" target="_blank">此 Notebook</a> 跟随代码实践,该文件支持在 Google Colab 中运行。 </Tip> 检索增强生成(Retrieval-Augmented Generation,RAG)系统结合了数据检索和生成模型的能力,以提供上下文感知的响应。例如,用户的查询会被传递给搜索引擎,检索结果与查询一起提供给模型,模型随后根据查询和检索到的信息生成响应。 智能驱动的 RAG(Retrieval-Augmented Generation)通过**将自主智能体与动态知识检索相结合**,扩展了传统 RAG 系统。 传统 RAG 系统使用 LLM 根据检索数据回答查询,而智能驱动的 RAG **实现了对检索和生成流程的智能控制**,从而提高了效率和准确性。 传统 RAG 系统面临关键限制,例如**依赖单次检索步骤**,以及过度关注与用户查询的直接语义相似性,这可能会忽略相关信息。 智能驱动的 RAG 通过允许智能体自主制定搜索查询、评估检索结果并进行多次检索步骤,以生成更定制化和全面的输出,从而解决这些问题。 ## 基于 DuckDuckGo 的基础检索 让我们构建一个能够使用 DuckDuckGo 进行网页搜索的简单智能体。该智能体将检索信息并综合响应来回答查询。通过智能驱动的 RAG,Alfred 的智能体可以: * 搜索最新的超级英雄派对趋势 * 优化结果以包含奢侈元素 * 将信息综合成完整方案 以下是 Alfred 的智能体实现此功能的代码示例: ```python from smolagents import CodeAgent, DuckDuckGoSearchTool, InferenceClientModel # 初始化搜索工具 search_tool = DuckDuckGoSearchTool() # 初始化模型 model = InferenceClientModel() agent = CodeAgent( model=model, tools=[search_tool] ) # 使用示例 response = agent.run( "Search for luxury superhero-themed party ideas, including decorations, entertainment, and catering." ) print(response) ``` 智能体遵循以下流程: 1. **请求分析:** Alfred 的智能体识别查询的关键要素——重点关注装饰、娱乐和餐饮的豪华超级英雄主题派对规划 2. **执行检索:** 智能体利用 DuckDuckGo 搜索最新相关信息,确保符合 Alfred 对奢侈活动的精细要求 3. **信息综合:** 收集结果后,智能体将其处理为覆盖派对所有方面的可执行方案 4. **未来参考存储:** 智能体存储检索信息以便后续活动规划时快速访问,优化后续任务效率 ## 自定义知识库工具 对于专业任务,自定义知识库非常宝贵。让我们创建可以查询技术文档或专业知识的向量数据库工具。通过语义搜索,智能体可以找到与 Alfred 需求最相关的信息。 向量数据库(vector database)是通过专业 ML 模型实现丰富文档表示的集合,能够快速搜索和检索文档。 该方法将预定义知识与语义搜索相结合,为活动规划提供上下文感知解决方案。通过专业知识访问,Alfred 可以完善派对的每个细节。 在此示例中,我们将创建从自定义知识库检索派对策划创意的工具。使用 BM25 检索器搜索知识库并返回最佳结果,同时使用 `RecursiveCharacterTextSplitter` 将文档分割为更小的块以提高搜索效率: ```python from langchain.docstore.document import Document from langchain.text_splitter import RecursiveCharacterTextSplitter from smolagents import Tool from langchain_community.retrievers import BM25Retriever from smolagents import CodeAgent, InferenceClientModel class PartyPlanningRetrieverTool(Tool): name = "party_planning_retriever" description = "Uses semantic search to retrieve relevant party planning ideas for Alfred’s superhero-themed party at Wayne Manor." inputs = { "query": { "type": "string", "description": "The query to perform. This should be a query related to party planning or superhero themes.", } } output_type = "string" def __init__(self, docs, **kwargs): super().__init__(**kwargs) self.retriever = BM25Retriever.from_documents( docs, k=5 # 检索前 5 个文档 ) def forward(self, query: str) -> str: assert isinstance(query, str), "Your search query must be a string" docs = self.retriever.invoke( query, ) return "\nRetrieved ideas:\n" + "".join( [ f"\n\n===== Idea {str(i)} =====\n" + doc.page_content for i, doc in enumerate(docs) ] ) # 模拟派对策划知识库 party_ideas = [ {"text": "A superhero-themed masquerade ball with luxury decor, including gold accents and velvet curtains.", "source": "Party Ideas 1"}, {"text": "Hire a professional DJ who can play themed music for superheroes like Batman and Wonder Woman.", "source": "Entertainment Ideas"}, {"text": "For catering, serve dishes named after superheroes, like 'The Hulk's Green Smoothie' and 'Iron Man's Power Steak.'", "source": "Catering Ideas"}, {"text": "Decorate with iconic superhero logos and projections of Gotham and other superhero cities around the venue.", "source": "Decoration Ideas"}, {"text": "Interactive experiences with VR where guests can engage in superhero simulations or compete in themed games.", "source": "Entertainment Ideas"} ] source_docs = [ Document(page_content=doc["text"], metadata={"source": doc["source"]}) for doc in party_ideas ] # 分割文档以提高搜索效率 text_splitter = RecursiveCharacterTextSplitter( chunk_size=500, chunk_overlap=50, add_start_index=True, strip_whitespace=True, separators=["\n\n", "\n", ".", " ", ""], ) docs_processed = text_splitter.split_documents(source_docs) # 创建检索工具 party_planning_retriever = PartyPlanningRetrieverTool(docs_processed) # 初始化智能体 agent = CodeAgent(tools=[party_planning_retriever], model=InferenceClientModel()) # 使用示例 response = agent.run( "Find ideas for a luxury superhero-themed party, including entertainment, catering, and decoration options." ) print(response) ``` 增强后的智能体能够: 1. 首先检查文档中的相关信息 2. 结合知识库的洞察 3. 在内存中维护对话上下文 ## 增强的检索能力 构建智能驱动的 RAG 系统时,智能体可以采用以下高级策略: 1. **查询重构:** 智能体可以优化原始查询,生成更匹配目标文档的搜索词 2. **多步检索:** 智能体可以进行多次搜索,利用初步结果优化后续查询 3. **多源整合:** 结合来自网页搜索和本地文档等多个来源的信息 4. **结果验证:** 在将检索内容纳入响应前分析其相关性和准确性 有效的智能驱动 RAG 系统需要仔细考虑几个关键方面。智能体**应根据查询类型和上下文选择可用工具**,记忆系统帮助维护对话历史避免重复检索,后备策略确保在主要检索方法失败时系统仍能提供价值,验证步骤则帮助确保检索信息的准确性和相关性。 ## 资源 - [Agentic RAG: 使用查询重构和自查询加速您的 RAG 系统!🚀](https://huggingface.co/learn/cookbook/zh-CN/agent_rag) - 使用 smolagents 开发智能驱动 RAG 系统的实践指南
agents-course/units/zh-CN/unit2/smolagents/retrieval_agents.mdx/0
{ "file_path": "agents-course/units/zh-CN/unit2/smolagents/retrieval_agents.mdx", "repo_id": "agents-course", "token_count": 4342 }
22
# 欢迎来到最后一个单元 [[介绍]] <img src="https://huggingface.co/datasets/agents-course/course-images/resolve/main/en/unit4/thumbnail.jpg" alt="AI Agents Course thumbnail" width="100%"/> 欢迎来到课程的最后一个单元!🎉 到目前为止,您已经**在AI智能体方面建立了坚实的基础**,从理解其组件到创建自己的智能体。有了这些知识,您现在可以**构建强大的智能体**并在这个快速发展的领域中赶上潮流。 这个单元和应用您所学的知识有关。这是您的**最终动手项目**,完成它是您获得**课程证书**的入场券。 ## 挑战是什么? 您将创建自己的智能体并**使用[GAIA基准](https://huggingface.co/spaces/gaia-benchmark/leaderboard)的一个子集评估其性能**。 为了成功完成课程,您的智能体需要在基准测试中得到**30%或更高**的分数。实现这一目标,您将获得**完成证书**,正式认证您的专业知识。🏅 此外,您还可以查看自己在所有课程参与者中的表现!我们提供了一个专门的[**学生排行榜**](https://huggingface.co/spaces/agents-course/Students_leaderboard),您可以提交自己的成绩,并查看整个社区的进展情况。 > 🚨 **提示:更高级的实践单元** > > 请注意,这个单元转向更实用的动手方法。在这一部分取得成功需要**更高级的编码知识**,并且与课程的前期部分相比,需要您在**较少明确指导**的情况下完成任务。 这听起来很棒,对吧?让我们开始吧!🚀
agents-course/units/zh-CN/unit4/introduction.mdx/0
{ "file_path": "agents-course/units/zh-CN/unit4/introduction.mdx", "repo_id": "agents-course", "token_count": 1024 }
23
# Candle Book The book uses [mdBook](https://github.com/rust-lang/mdBook) for building. ## Installation To install mdBook, run `cargo install mdbook`. More instructions can be found [here](https://rust-lang.github.io/mdBook/guide/installation.html). ## Viewing the book To view the book, run `mdbook serve --open candle-book`. More instructions can be found [here](https://rust-lang.github.io/mdBook/guide/creating.html). The book is built automatically in github CI.
candle/candle-book/CONTRIBUTING.md/0
{ "file_path": "candle/candle-book/CONTRIBUTING.md", "repo_id": "candle", "token_count": 140 }
24
# Hello world! We will now create the hello world of the ML world, building a model capable of solving MNIST dataset. Open `src/main.rs` and fill in this content: ```rust # extern crate candle_core; use candle_core::{Device, Result, Tensor}; struct Model { first: Tensor, second: Tensor, } impl Model { fn forward(&self, image: &Tensor) -> Result<Tensor> { let x = image.matmul(&self.first)?; let x = x.relu()?; x.matmul(&self.second) } } fn main() -> Result<()> { // Use Device::new_cuda(0)?; to use the GPU. let device = Device::Cpu; let first = Tensor::randn(0f32, 1.0, (784, 100), &device)?; let second = Tensor::randn(0f32, 1.0, (100, 10), &device)?; let model = Model { first, second }; let dummy_image = Tensor::randn(0f32, 1.0, (1, 784), &device)?; let digit = model.forward(&dummy_image)?; println!("Digit {digit:?} digit"); Ok(()) } ``` Everything should now run with: ```bash cargo run --release ``` ## Using a `Linear` layer. Now that we have this, we might want to complexify things a bit, for instance by adding `bias` and creating the classical `Linear` layer. We can do as such ```rust # extern crate candle_core; # use candle_core::{Device, Result, Tensor}; struct Linear{ weight: Tensor, bias: Tensor, } impl Linear{ fn forward(&self, x: &Tensor) -> Result<Tensor> { let x = x.matmul(&self.weight)?; x.broadcast_add(&self.bias) } } struct Model { first: Linear, second: Linear, } impl Model { fn forward(&self, image: &Tensor) -> Result<Tensor> { let x = self.first.forward(image)?; let x = x.relu()?; self.second.forward(&x) } } ``` This will change the model running code into a new function ```rust # extern crate candle_core; # use candle_core::{Device, Result, Tensor}; # struct Linear{ # weight: Tensor, # bias: Tensor, # } # impl Linear{ # fn forward(&self, x: &Tensor) -> Result<Tensor> { # let x = x.matmul(&self.weight)?; # x.broadcast_add(&self.bias) # } # } # # struct Model { # first: Linear, # second: Linear, # } # # impl Model { # fn forward(&self, image: &Tensor) -> Result<Tensor> { # let x = self.first.forward(image)?; # let x = x.relu()?; # self.second.forward(&x) # } # } fn main() -> Result<()> { // Use Device::new_cuda(0)?; to use the GPU. // Use Device::Cpu; to use the CPU. let device = Device::cuda_if_available(0)?; // Creating a dummy model let weight = Tensor::randn(0f32, 1.0, (784, 100), &device)?; let bias = Tensor::randn(0f32, 1.0, (100, ), &device)?; let first = Linear{weight, bias}; let weight = Tensor::randn(0f32, 1.0, (100, 10), &device)?; let bias = Tensor::randn(0f32, 1.0, (10, ), &device)?; let second = Linear{weight, bias}; let model = Model { first, second }; let dummy_image = Tensor::randn(0f32, 1.0, (1, 784), &device)?; // Inference on the model let digit = model.forward(&dummy_image)?; println!("Digit {digit:?} digit"); Ok(()) } ``` Now it works, it is a great way to create your own layers. But most of the classical layers are already implemented in [candle-nn](https://github.com/huggingface/candle/tree/main/candle-nn). ## Using `candle_nn`. For instance [Linear](https://github.com/huggingface/candle/blob/main/candle-nn/src/linear.rs) is already there. This Linear is coded with PyTorch layout in mind, to reuse better existing models out there, so it uses the transpose of the weights and not the weights directly. So instead we can simplify our example: ```bash cargo add --git https://github.com/huggingface/candle.git candle-nn ``` And rewrite our examples using it ```rust # extern crate candle_core; # extern crate candle_nn; use candle_core::{Device, Result, Tensor}; use candle_nn::{Linear, Module}; struct Model { first: Linear, second: Linear, } impl Model { fn forward(&self, image: &Tensor) -> Result<Tensor> { let x = self.first.forward(image)?; let x = x.relu()?; self.second.forward(&x) } } fn main() -> Result<()> { // Use Device::new_cuda(0)?; to use the GPU. let device = Device::Cpu; // This has changed (784, 100) -> (100, 784) ! let weight = Tensor::randn(0f32, 1.0, (100, 784), &device)?; let bias = Tensor::randn(0f32, 1.0, (100, ), &device)?; let first = Linear::new(weight, Some(bias)); let weight = Tensor::randn(0f32, 1.0, (10, 100), &device)?; let bias = Tensor::randn(0f32, 1.0, (10, ), &device)?; let second = Linear::new(weight, Some(bias)); let model = Model { first, second }; let dummy_image = Tensor::randn(0f32, 1.0, (1, 784), &device)?; let digit = model.forward(&dummy_image)?; println!("Digit {digit:?} digit"); Ok(()) } ``` Feel free to modify this example to use `Conv2d` to create a classical convnet instead. Now that we have the running dummy code we can get to more advanced topics: - [For PyTorch users](../guide/cheatsheet.md) - [Running existing models](../inference/inference.md) - [Training models](../training/training.md)
candle/candle-book/src/guide/hello_world.md/0
{ "file_path": "candle/candle-book/src/guide/hello_world.md", "repo_id": "candle", "token_count": 2069 }
25
# Serialization
candle/candle-book/src/training/serialization.md/0
{ "file_path": "candle/candle-book/src/training/serialization.md", "repo_id": "candle", "token_count": 4 }
26
use crate::benchmarks::{BenchDevice, BenchDeviceHandler}; use candle_core::{DType, Device, Tensor}; use criterion::{black_box, criterion_group, Criterion, Throughput}; use std::time::Instant; fn run(a: &Tensor, b: &Tensor, c: &Tensor) { a.where_cond(b, c).unwrap(); } const fn create_cond_arr<const N: usize>() -> [u8; N] { let mut arr = [0u8; N]; let mut i = 0; while i < N { arr[i] = (i % 2) as u8; i += 1; } arr } const B: usize = 1; const M: usize = 1024; const K: usize = 1024; const SIZE: usize = B * M * K; const DATA: [u8; SIZE] = create_cond_arr::<SIZE>(); fn run_where_cond_benchmark(c: &mut Criterion, device: &Device, dtype: DType, name: &str) { let tensor = Tensor::from_slice(DATA.as_slice(), (B, M, K), device).unwrap(); let on_true = Tensor::ones((B, M, K), dtype, device).unwrap(); let on_false = Tensor::zeros((B, M, K), dtype, device).unwrap(); let elements = B * M * K; // E.g. 2 f32 tensors + 1 u8 tensor let flops = (2 * elements * dtype.size_in_bytes()) + elements; let mut group = c.benchmark_group(device.bench_name(name)); group.throughput(Throughput::Bytes(flops as u64)); group.bench_function("iter", move |b| { b.iter_custom(|iters| { let start = Instant::now(); for _i in 0..iters { run( black_box(&tensor), black_box(&on_true), black_box(&on_false), ); } device.sync().unwrap(); start.elapsed() }) }); group.finish(); } fn criterion_benchmark(c: &mut Criterion) { let device = BenchDeviceHandler::new().unwrap(); for d in device.devices { run_where_cond_benchmark(c, &d, DType::F32, "where_cond_f32"); run_where_cond_benchmark(c, &d, DType::BF16, "where_cond_bf16"); run_where_cond_benchmark(c, &d, DType::F16, "where_cond_f16"); } } criterion_group!(benches, criterion_benchmark);
candle/candle-core/benches/benchmarks/where_cond.rs/0
{ "file_path": "candle/candle-core/benches/benchmarks/where_cond.rs", "repo_id": "candle", "token_count": 939 }
27
//! Implementation of Backend Fns for CPU use crate::backend::{BackendDevice, BackendStorage}; use crate::op::{BinaryOpT, CmpOp, ReduceOp, UnaryOpT}; use crate::{DType, Error, IntDType, Layout, Result, Shape, WithDType}; use float8::F8E4M3; use half::{bf16, f16}; use rayon::prelude::*; mod utils; pub use utils::{ binary_map, binary_map_vec, unary_map, unary_map_vec, Map1, Map1Any, Map2, Map2InPlace, Map2U8, }; const USE_IM2COL_CONV1D: bool = true; const USE_COL2IM_CONV1D_TR: bool = true; const USE_IM2COL_CONV2D: bool = true; // TODO: Maybe we should not implement [Clone] here and instead have an explicit allocator + // intercept the oom errors to avoid panicking and provide a proper error. #[derive(Debug, Clone)] pub enum CpuStorage { U8(Vec<u8>), U32(Vec<u32>), I64(Vec<i64>), BF16(Vec<bf16>), F16(Vec<f16>), F32(Vec<f32>), F64(Vec<f64>), F8E4M3(Vec<F8E4M3>), } #[derive(Debug, Clone)] pub enum CpuStorageRef<'a> { U8(&'a [u8]), U32(&'a [u32]), I64(&'a [i64]), BF16(&'a [bf16]), F16(&'a [f16]), F32(&'a [f32]), F64(&'a [f64]), F8E4M3(&'a [F8E4M3]), } #[derive(Debug, Clone)] pub struct CpuDevice; struct Cmp(CmpOp); impl Map2U8 for Cmp { const OP: &'static str = "cmp"; #[inline(always)] fn f<T: WithDType>( &self, lhs: &[T], lhs_l: &Layout, rhs: &[T], rhs_l: &Layout, ) -> Result<Vec<u8>> { let dst = match self.0 { CmpOp::Eq => binary_map(lhs_l, rhs_l, lhs, rhs, |x, y| u8::from(x == y)), CmpOp::Ne => binary_map(lhs_l, rhs_l, lhs, rhs, |x, y| u8::from(x != y)), CmpOp::Lt => binary_map(lhs_l, rhs_l, lhs, rhs, |x, y| u8::from(x < y)), CmpOp::Le => binary_map(lhs_l, rhs_l, lhs, rhs, |x, y| u8::from(x <= y)), CmpOp::Gt => binary_map(lhs_l, rhs_l, lhs, rhs, |x, y| u8::from(x > y)), CmpOp::Ge => binary_map(lhs_l, rhs_l, lhs, rhs, |x, y| u8::from(x >= y)), }; Ok(dst) } } struct WCond<'a, T: IntDType>(&'a [T], &'a Layout); impl<I: IntDType> Map2 for WCond<'_, I> { const OP: &'static str = "where"; #[inline(always)] fn f<T: WithDType>(&self, t: &[T], t_l: &Layout, f: &[T], f_l: &Layout) -> Result<Vec<T>> { let vs = match ( self.1.contiguous_offsets(), t_l.contiguous_offsets(), f_l.contiguous_offsets(), ) { (Some((o1, o2)), Some((o_t1, o_t2)), Some((o_f1, o_f2))) => { let pred = &self.0[o1..o2]; let t = &t[o_t1..o_t2]; let f = &f[o_f1..o_f2]; pred.iter() .zip(t.iter().zip(f.iter())) .map(|(p, (&t, &f))| if p.is_true() { t } else { f }) .collect::<Vec<_>>() } _ => self .1 .strided_index() .zip(t_l.strided_index().zip(f_l.strided_index())) .map(|(i_p, (i_t, i_f))| { if self.0[i_p].is_true() { t[i_t] } else { f[i_f] } }) .collect::<Vec<_>>(), }; Ok(vs) } } struct ReduceIndex { reduce_dim_index: usize, use_min: bool, return_index: bool, } impl ReduceIndex { // The value gets replaced if f(s[current_acc], s[i]) returns true. #[inline(always)] fn fold_impl<T, U, F, G>(&self, src: &[T], src_l: &Layout, f: F, g: G) -> Result<Vec<U>> where T: Clone + Copy, U: Clone + Copy, F: Fn(T, T) -> bool, G: Fn(T, usize) -> U, { let reduce_dim_size = src_l.dims()[self.reduce_dim_index]; let reduce_dim_stride = src_l.stride()[self.reduce_dim_index]; let dst_len = src_l.shape().elem_count() / reduce_dim_size; let mut dst: Vec<U> = Vec::with_capacity(dst_len); let dst_to_set = dst.spare_capacity_mut(); let dst_to_set = unsafe { std::mem::transmute::<&mut [std::mem::MaybeUninit<U>], &mut [U]>(dst_to_set) }; match src_l.contiguous_offsets() { Some((o1, o2)) => { let src = &src[o1..o2]; if reduce_dim_stride == 1 { for (start_src_i, dst_v) in dst_to_set.iter_mut().enumerate() { let start_src_i = start_src_i * reduce_dim_size; let src = &src[start_src_i..start_src_i + reduce_dim_size]; let mut acc = 0; let mut val = src[0]; for (src_i, &s) in src.iter().enumerate() { if f(val, s) { acc = src_i; val = s } } *dst_v = g(val, acc) } } else { for (start_src_i, dst_v) in dst_to_set.iter_mut().enumerate() { let (p, q) = ( start_src_i / reduce_dim_stride, start_src_i % reduce_dim_stride, ); // start_src_i = p * reduce_dim_stride + q let start_src_i = p * reduce_dim_stride * reduce_dim_size + q; let src = &src[start_src_i..]; let mut acc = 0; let mut val = src[0]; for src_i in 0..reduce_dim_size { let s = src[src_i * reduce_dim_stride]; if f(val, s) { acc = src_i; val = s } } *dst_v = g(val, acc) } } } None => { let l = src_l.narrow(self.reduce_dim_index, 0, 1)?; for (unstr_index, src_index) in l.strided_index().enumerate() { let src = &src[src_index..]; let mut acc = 0; let mut val = src[0]; for src_i in 0..reduce_dim_size { let s = src[src_i * reduce_dim_stride]; if f(val, s) { acc = src_i; val = s } } dst_to_set[unstr_index] = g(val, acc) } } } unsafe { dst.set_len(dst_len) }; Ok(dst) } } impl Map1Any for ReduceIndex { #[inline(always)] fn f<T: WithDType, W: Fn(Vec<T>) -> CpuStorage>( &self, src: &[T], src_l: &Layout, wrap: W, ) -> Result<CpuStorage> { if src_l.shape().elem_count() == 0 { Err(Error::EmptyTensor { op: "reduce" }.bt())? } let dst = match (self.return_index, self.use_min) { (false, true) => wrap(self.fold_impl(src, src_l, |x, y| x > y, |v, _i| v)?), (false, false) => wrap(self.fold_impl(src, src_l, |x, y| x < y, |v, _i| v)?), (true, true) => { CpuStorage::U32(self.fold_impl(src, src_l, |x, y| x > y, |_v, i| i as u32)?) } (true, false) => { CpuStorage::U32(self.fold_impl(src, src_l, |x, y| x < y, |_v, i| i as u32)?) } }; Ok(dst) } } struct ReduceSum<'a> { dst_shape: &'a Shape, reduce_dims: &'a [usize], reduce_dims_and_stride: Vec<(usize, usize)>, } impl ReduceSum<'_> { #[inline(always)] fn fold_impl<T>(&self, src: &[T], src_l: &Layout, start_elt: T) -> Result<Vec<T>> where T: WithDType, { let mut dst = vec![start_elt; self.dst_shape.elem_count()]; match src_l.contiguous_offsets() { Some((o1, o2)) => { let src = &src[o1..o2]; // Handle the case where we reduce over the last dimensions separately as it is // fairly common and easy to optimize. This rely on the layout being contiguous! // reduce_dims is sorted, check if it is ranging from a to n-1. let reduce_over_last_dims = self .reduce_dims .iter() .rev() .enumerate() .all(|(i, &v)| v == src_l.shape().rank() - 1 - i); if reduce_over_last_dims { let reduce_sz = self .reduce_dims_and_stride .iter() .map(|(u, _)| u) .product::<usize>(); for (dst_i, dst_v) in dst.iter_mut().enumerate() { let src_i = dst_i * reduce_sz; unsafe { T::vec_reduce_sum( src[src_i..src_i + reduce_sz].as_ptr(), dst_v, reduce_sz, ) }; } return Ok(dst); }; for (unstr_index, &src) in src.iter().enumerate() { let mut dst_index = unstr_index; // Set the reduce_dims indexes to 0. for &(dim, stride) in self.reduce_dims_and_stride.iter() { // The compiler is able to optimize the following in a single divmod op. let (pre, post) = (dst_index / stride, dst_index % stride); dst_index = (pre / dim) * stride + post; } dst[dst_index] += src; } } None => { for (unstr_index, src_index) in src_l.strided_index().enumerate() { let mut dst_index = unstr_index; // Set the reduce_dims indexes to 0. for &(dim, stride) in self.reduce_dims_and_stride.iter() { // The compiler is able to optimize the following in a single divmod op. let (pre, post) = (dst_index / stride, dst_index % stride); dst_index = (pre / dim) * stride + post; } dst[dst_index] += src[src_index]; } } } Ok(dst) } } impl Map1 for ReduceSum<'_> { #[inline(always)] fn f<T: WithDType>(&self, src: &[T], src_l: &Layout) -> Result<Vec<T>> { self.fold_impl(src, src_l, T::zero()) } } struct Affine(f64, f64); impl Map1 for Affine { fn f<T: WithDType>(&self, vs: &[T], layout: &Layout) -> Result<Vec<T>> { let mul = T::from_f64(self.0); let add = T::from_f64(self.1); Ok(unary_map(vs, layout, |v| v * mul + add)) } } struct AvgPool2D((usize, usize), (usize, usize)); impl Map1 for AvgPool2D { fn f<T: WithDType>(&self, src: &[T], layout: &Layout) -> Result<Vec<T>> { // https://pytorch.org/docs/stable/generated/torch.nn.AvgPool2d.html let (k_h, k_w) = self.0; let (s_h, s_w) = self.1; let (b_sz, c, h, w) = layout.shape().dims4()?; let stride = layout.stride(); let (stride_h, stride_w) = (stride[2], stride[3]); let h_out = (h - k_h) / s_h + 1; let w_out = (w - k_w) / s_w + 1; let src_index = layout.start_offset(); let mut dst = vec![T::zero(); b_sz * c * h_out * w_out]; let scale = 1f64 / (k_h * k_w) as f64; let scale = T::from_f64(scale); for b_idx in 0..b_sz { let dst = &mut dst[b_idx * c * h_out * w_out..]; let src_index = src_index + b_idx * stride[0]; for c_idx in 0..c { let dst = &mut dst[c_idx * h_out * w_out..]; let src_index = src_index + c_idx * stride[1]; for h_idx in 0..h_out { for w_idx in 0..w_out { let mut sum = T::zero(); for m in 0..k_h { for n in 0..k_w { let m = s_h * h_idx + m; let n = s_w * w_idx + n; sum += src[src_index + m * stride_h + n * stride_w] } } dst[h_idx * w_out + w_idx] = sum * scale; } } } } Ok(dst) } } struct MaxPool2D((usize, usize), (usize, usize)); impl Map1 for MaxPool2D { fn f<T: WithDType>(&self, src: &[T], layout: &Layout) -> Result<Vec<T>> { // https://pytorch.org/docs/stable/generated/torch.nn.MaxPool2d.html let (k_h, k_w) = self.0; let (s_h, s_w) = self.1; let (b_sz, c, h, w) = layout.shape().dims4()?; let stride = layout.stride(); let (stride_h, stride_w) = (stride[2], stride[3]); let h_out = (h - k_h) / s_h + 1; let w_out = (w - k_w) / s_w + 1; let src_index = layout.start_offset(); let mut dst = vec![T::zero(); b_sz * c * h_out * w_out]; for b_idx in 0..b_sz { let dst = &mut dst[b_idx * c * h_out * w_out..]; let src_index = src_index + b_idx * stride[0]; for c_idx in 0..c { let dst = &mut dst[c_idx * h_out * w_out..]; let src_index = src_index + c_idx * stride[1]; for h_idx in 0..h_out { for w_idx in 0..w_out { let mut largest = src[src_index + s_h * h_idx * stride_h + s_w * w_idx * stride_w]; for m in 0..k_h { for n in 0..k_w { let m = s_h * h_idx + m; let n = s_w * w_idx + n; if largest < src[src_index + m * stride_h + n * stride_w] { largest = src[src_index + m * stride_h + n * stride_w] } } } dst[h_idx * w_out + w_idx] = largest; } } } } Ok(dst) } } struct UpsampleNearest1D(usize); impl Map1 for UpsampleNearest1D { fn f<T: WithDType>(&self, src: &[T], layout: &Layout) -> Result<Vec<T>> { // TODO: Specialized implementation for the case 2*sz? let dst_sz = self.0; let (b_sz, c, src_sz) = layout.shape().dims3()?; let stride = layout.stride(); let stride_sz = stride[2]; let src_index = layout.start_offset(); let scale_sz = src_sz as f64 / dst_sz as f64; let mut dst = vec![T::zero(); b_sz * c * dst_sz]; let src_idxs = (0..dst_sz) .map(|idx| usize::min(src_sz - 1, (idx as f64 * scale_sz) as usize)) .collect::<Vec<_>>(); for b_idx in 0..b_sz { let dst = &mut dst[b_idx * c * dst_sz..]; let src_index = src_index + b_idx * stride[0]; for c_idx in 0..c { let dst = &mut dst[c_idx * dst_sz..]; let src_index = src_index + c_idx * stride[1]; for (idx, src_idx) in src_idxs.iter().enumerate() { dst[idx] = src[src_index + src_idx * stride_sz] } } } Ok(dst) } } struct UpsampleNearest2D(usize, usize); impl Map1 for UpsampleNearest2D { fn f<T: WithDType>(&self, src: &[T], layout: &Layout) -> Result<Vec<T>> { // TODO: Specialized implementation for the case 2*h, 2*w? let (dst_h, dst_w) = (self.0, self.1); let (b_sz, c, src_h, src_w) = layout.shape().dims4()?; let stride = layout.stride(); let (stride_h, stride_w) = (stride[2], stride[3]); let src_index = layout.start_offset(); let scale_h = src_h as f64 / dst_h as f64; let scale_w = src_w as f64 / dst_w as f64; let mut dst = vec![T::zero(); b_sz * c * dst_h * dst_w]; let src_h_idxs = (0..dst_h) .map(|h_idx| usize::min(src_h - 1, (h_idx as f64 * scale_h) as usize)) .collect::<Vec<_>>(); let src_w_idxs = (0..dst_w) .map(|w_idx| usize::min(src_w - 1, (w_idx as f64 * scale_w) as usize)) .collect::<Vec<_>>(); for b_idx in 0..b_sz { let dst = &mut dst[b_idx * c * dst_h * dst_w..]; let src_index = src_index + b_idx * stride[0]; for c_idx in 0..c { let dst = &mut dst[c_idx * dst_h * dst_w..]; let src_index = src_index + c_idx * stride[1]; for (h_idx, src_h_idx) in src_h_idxs.iter().enumerate() { for (w_idx, src_w_idx) in src_w_idxs.iter().enumerate() { let src_index = src_index + src_h_idx * stride_h + src_w_idx * stride_w; dst[h_idx * dst_w + w_idx] = src[src_index] } } } } Ok(dst) } } struct Gather<'a, I: IntDType> { ids: &'a [I], ids_l: &'a Layout, dim: usize, } impl<I: IntDType> Map1 for Gather<'_, I> { fn f<T: WithDType>(&self, src: &[T], src_l: &Layout) -> Result<Vec<T>> { let ids = match self.ids_l.contiguous_offsets() { Some((a, b)) => &self.ids[a..b], None => Err(Error::RequiresContiguous { op: "gather" }.bt())?, }; let src = match src_l.contiguous_offsets() { Some((a, b)) => &src[a..b], None => Err(Error::RequiresContiguous { op: "gather" }.bt())?, }; let dim = self.dim; let ids_dims = self.ids_l.dims(); let src_dims = src_l.dims(); let dst_len: usize = ids_dims.iter().product(); let dst_left_len: usize = ids_dims[..dim].iter().product(); let dst_dim_len = ids_dims[dim]; let dst_right_len: usize = ids_dims[dim + 1..].iter().product(); let src_dim_len = src_dims[dim]; let src_right_len: usize = src_dims[dim + 1..].iter().product(); let mut dst = vec![T::zero(); dst_len]; for left_i in 0..dst_left_len { let start_src_idx = left_i * src_right_len * src_dim_len; let start_dst_idx = left_i * dst_right_len * dst_dim_len; for i in 0..dst_dim_len { let start_dst_idx = start_dst_idx + i * dst_right_len; for right_i in 0..dst_right_len { let dst_idx = start_dst_idx + right_i; let index = ids[dst_idx]; if index == I::max_value() { dst[dst_idx] = T::zero(); } else { let index = index.as_usize(); if index >= src_dim_len { Err(Error::InvalidIndex { index, size: src_dim_len, op: "gather", } .bt())? } let src_idx = start_src_idx + index * src_right_len + right_i; dst[dst_idx] = src[src_idx] } } } } Ok(dst) } } struct IndexSelect<'a, T: IntDType> { ids: &'a [T], ids_l: &'a Layout, dim: usize, } impl<I: IntDType> Map1 for IndexSelect<'_, I> { fn f<T: WithDType>(&self, src: &[T], layout: &Layout) -> Result<Vec<T>> { let src = match layout.contiguous_offsets() { Some((a, b)) => &src[a..b], None => Err(Error::RequiresContiguous { op: "index-select" }.bt())?, }; let dim = self.dim; let n_ids = match self.ids_l.dims() { [n_ids] => *n_ids, d => Err(Error::UnexpectedNumberOfDims { expected: 1, got: d.len(), shape: self.ids_l.shape().clone(), } .bt())?, }; let stride_ids = self.ids_l.stride()[0]; let mut dst_dims = layout.dims().to_vec(); let src_dim = dst_dims[dim]; dst_dims[dim] = n_ids; let dst_len: usize = dst_dims.iter().product(); let left_len: usize = dst_dims[..dim].iter().product(); let right_len: usize = dst_dims[dim + 1..].iter().product(); let mut dst = vec![T::zero(); dst_len]; for left_i in 0..left_len { let start_src_idx = left_i * right_len * src_dim; let start_dst_idx = left_i * right_len * n_ids; for i in 0..n_ids { let start_dst_idx = start_dst_idx + i * right_len; let index = self.ids[self.ids_l.start_offset() + stride_ids * i]; if index == I::max_value() { dst[start_dst_idx..start_dst_idx + right_len].fill(T::zero()); } else { let index = index.as_usize(); if index >= src_dim { Err(Error::InvalidIndex { index, size: src_dim, op: "index-select", } .bt())? } let start_src_idx = start_src_idx + index * right_len; dst[start_dst_idx..start_dst_idx + right_len] .copy_from_slice(&src[start_src_idx..start_src_idx + right_len]) } } } Ok(dst) } } trait ElemUpdate { fn f<T: WithDType>(dst: &mut T, src: T); } struct Set; struct Add; impl ElemUpdate for Set { fn f<T: WithDType>(dst: &mut T, src: T) { *dst = src } } impl ElemUpdate for Add { fn f<T: WithDType>(dst: &mut T, src: T) { *dst += src } } struct Scatter<'a, I: IntDType, M: ElemUpdate> { ids: &'a [I], ids_l: &'a Layout, dim: usize, _phantom: std::marker::PhantomData<M>, } impl<'a, I: IntDType, M: ElemUpdate> Scatter<'a, I, M> { fn new(ids: &'a [I], ids_l: &'a Layout, dim: usize) -> Self { Self { ids, ids_l, dim, _phantom: Default::default(), } } } impl<I: IntDType, M: ElemUpdate> Map2InPlace for Scatter<'_, I, M> { const OP: &'static str = "scatter"; fn f<T: WithDType>( &self, dst: &mut [T], dst_l: &Layout, src: &[T], src_l: &Layout, ) -> Result<()> { let dst = match dst_l.contiguous_offsets() { None => Err(Error::RequiresContiguous { op: "scatter" }.bt())?, Some((o1, o2)) => &mut dst[o1..o2], }; let src = match src_l.contiguous_offsets() { None => Err(Error::RequiresContiguous { op: "scatter" }.bt())?, Some((o1, o2)) => &src[o1..o2], }; let dim = self.dim; let ids_dims = self.ids_l.dims(); let dst_dims = dst_l.dims(); let dst_dim_len = dst_dims[dim]; let dst_right_len: usize = dst_dims[dim + 1..].iter().product(); let ids_left_len: usize = ids_dims[..dim].iter().product(); let ids_dim_len = ids_dims[dim]; let ids_right_len: usize = ids_dims[dim + 1..].iter().product(); let ids = match self.ids_l.contiguous_offsets() { Some((a, b)) => &self.ids[a..b], None => Err(Error::RequiresContiguous { op: "gather" }.bt())?, }; for left_i in 0..ids_left_len { let start_ids_idx = left_i * ids_right_len * ids_dim_len; let start_dst_idx = left_i * dst_right_len * dst_dim_len; for i in 0..ids_dim_len { let start_ids_idx = start_ids_idx + i * ids_right_len; for right_i in 0..dst_right_len { let ids_idx = start_ids_idx + right_i; let index = ids[ids_idx]; if index == I::max_value() { continue; } let index = index.as_usize(); if index >= dst_dim_len { Err(Error::InvalidIndex { index, size: dst_dim_len, op: "gather", } .bt())? } let dst_idx = start_dst_idx + index * dst_right_len + right_i; M::f(&mut dst[dst_idx], src[ids_idx]) } } } Ok(()) } } struct IndexAdd<'a, I: IntDType> { ids: &'a [I], dim: usize, } impl<I: IntDType> Map2 for IndexAdd<'_, I> { const OP: &'static str = "index-add"; // https://pytorch.org/docs/stable/generated/torch.Tensor.index_add_.html#torch.Tensor.index_add_ // v1, l1 -> self fn f<T: WithDType>(&self, v1: &[T], l1: &Layout, src: &[T], src_l: &Layout) -> Result<Vec<T>> { let dst_len = l1.shape().elem_count(); let mut dst = vec![T::zero(); dst_len]; copy_strided_src_(v1, &mut dst, 0, l1); let src = match src_l.contiguous_offsets() { None => Err(Error::RequiresContiguous { op: "index-add" }.bt())?, Some((o1, o2)) => &src[o1..o2], }; let dim = self.dim; let max_idx = l1.dims()[dim]; let pre_dim = src_l.dims()[..dim].iter().product::<usize>(); let src_dim_sz = src_l.dims()[dim]; let post_dim = src_l.dims()[dim + 1..].iter().product::<usize>(); if dim == 0 { for (src_idx, dst_idx) in self.ids.iter().enumerate() { if *dst_idx == I::max_value() { continue; } let dst_idx = dst_idx.as_usize(); if dst_idx >= max_idx { Err(Error::InvalidIndex { index: dst_idx, op: "index-add", size: max_idx, })? } let src_idx = src_idx * post_dim; let dst_idx = dst_idx * post_dim; let src = &src[src_idx..src_idx + post_dim]; let dst = &mut dst[dst_idx..dst_idx + post_dim]; for (d, &s) in dst.iter_mut().zip(src.iter()) { *d += s } } } else { for (src_idx, dst_idx) in self.ids.iter().enumerate() { if *dst_idx == I::max_value() { continue; } let dst_idx = dst_idx.as_usize(); if dst_idx >= max_idx { Err(Error::InvalidIndex { index: dst_idx, op: "index-add", size: max_idx, })? } for pre_i in 0..pre_dim { let pre_src_i = (pre_i * src_dim_sz + src_idx) * post_dim; let pre_dst_i = (pre_i * max_idx + dst_idx) * post_dim; let src = &src[pre_src_i..pre_src_i + post_dim]; let dst = &mut dst[pre_dst_i..pre_dst_i + post_dim]; for (d, &s) in dst.iter_mut().zip(src.iter()) { *d += s } } } } Ok(dst) } } #[allow(clippy::too_many_arguments)] fn copy2d_<T: Copy>( src: &[T], dst: &mut [T], d1: usize, d2: usize, src_stride1: usize, dst_stride1: usize, src_offset: usize, dst_offset: usize, ) { for i1 in 0..d1 { let dst_idx = i1 * dst_stride1 + dst_offset; let src_idx = i1 * src_stride1 + src_offset; let dst = &mut dst[dst_idx..dst_idx + d2]; let src = &src[src_idx..src_idx + d2]; dst.copy_from_slice(src) } } fn copy_strided_src_<T: Copy>(src: &[T], dst: &mut [T], dst_offset: usize, src_l: &Layout) { match src_l.strided_blocks() { crate::StridedBlocks::SingleBlock { start_offset, len } => { let to_copy = (dst.len() - dst_offset).min(len); dst[dst_offset..dst_offset + to_copy] .copy_from_slice(&src[start_offset..start_offset + to_copy]) } crate::StridedBlocks::MultipleBlocks { block_start_index, block_len: 1, } => { for (dst_index, src_index) in block_start_index.enumerate() { let dst_index = dst_index + dst_offset; if dst_index >= dst.len() { break; } dst[dst_index] = src[src_index] } } crate::StridedBlocks::MultipleBlocks { block_start_index, block_len, } => { let mut dst_index = dst_offset; for src_index in block_start_index { let next_dst_index = dst_index + block_len; if dst_index >= dst.len() { break; } let to_copy = usize::min(block_len, dst.len() - dst_index); dst[dst_index..dst_index + to_copy] .copy_from_slice(&src[src_index..src_index + to_copy]); dst_index = next_dst_index } } } } struct Conv1D<'a>(&'a crate::conv::ParamsConv1D); impl Map2 for Conv1D<'_> { const OP: &'static str = "conv1d"; fn f<T: WithDType>(&self, inp: &[T], inp_l: &Layout, k: &[T], k_l: &Layout) -> Result<Vec<T>> { let p = self.0; let inp = &inp[inp_l.start_offset()..]; let k = &k[k_l.start_offset()..]; let (inp_s0, inp_s1, inp_s2) = crate::shape::dims3(inp_l.stride())?; let (k_s0, k_s1, k_s2) = crate::shape::dims3(k_l.stride())?; let l_out = p.l_out(); let dst_elems = p.c_out * l_out * p.b_size; // The output shape is [b_size, c_out, l_out] let dst = vec![T::zero(); dst_elems]; // TODO: Avoid making this copy if `inp` already has the appropriate layout. let mut inp_cont = vec![T::zero(); p.b_size * p.c_in * p.l_in]; for b_idx in 0..p.b_size { for src_l in 0..p.l_in { for src_c_idx in 0..p.c_in { let inp_idx = b_idx * inp_s0 + src_c_idx * inp_s1 + src_l * inp_s2; inp_cont[b_idx * p.l_in * p.c_in + src_l * p.c_in + src_c_idx] = inp[inp_idx] } } } for offset in 0..p.k_size { (0..p.c_out).into_par_iter().for_each(|dst_c_idx| { let dst_idx = dst_c_idx * l_out; let k_cont = (0..p.c_in) .map(|c_in_idx| k[dst_c_idx * k_s0 + c_in_idx * k_s1 + offset * k_s2]) .collect::<Vec<_>>(); for b_idx in 0..p.b_size { let dst_idx = dst_idx + b_idx * p.c_out * l_out; for dst_l in 0..l_out { let dst_idx = dst_idx + dst_l; let src_l = p.stride * dst_l + offset * p.dilation; if src_l < p.padding || src_l >= p.padding + p.l_in { continue; } let src_l = src_l - p.padding; let inp_cont = &inp_cont[b_idx * p.l_in * p.c_in + src_l * p.c_in..]; assert!(inp_cont.len() >= p.c_in); assert!(k_cont.len() >= p.c_in); let mut d = T::zero(); unsafe { T::vec_dot(inp_cont.as_ptr(), k_cont.as_ptr(), &mut d, p.c_in) } let dst_p = dst.as_ptr(); // Safety: dst_idx are uniques per dst_c_idx which is used to parallelise // the different tasks so no two threads can try to write at the same // location. unsafe { let ptr = dst_p.add(dst_idx) as *mut T; *ptr += d } } } }) } Ok(dst) } } struct Im2Col1D { l_k: usize, stride: usize, dilation: usize, padding: usize, } impl Im2Col1D { fn l_out(&self, l: usize) -> usize { (l + 2 * self.padding - self.dilation * (self.l_k - 1) - 1) / self.stride + 1 } } impl Map1 for Im2Col1D { fn f<T: WithDType>(&self, vs: &[T], layout: &Layout) -> Result<Vec<T>> { let &Self { l_k, stride, dilation, padding, } = self; let (b, c, l) = layout.shape().dims3()?; let l_out = self.l_out(l); let src = &vs[layout.start_offset()..]; let mut dst = vec![T::zero(); b * l_out * c * l_k]; let (src_s0, src_s1, src_s2) = { let s = layout.stride(); (s[0], s[1], s[2]) }; // TODO: provide specialized kernels for the common use cases. // - l_k = 1 // - padding = 0 // - stride = 1 // - dilation = 1 for b_idx in 0..b { let src_idx = b_idx * src_s0; let dst_idx = b_idx * l_out * c * l_k; for l_idx in 0..l_out { let dst_idx = dst_idx + l_idx * c * l_k; for c_idx in 0..c { let dst_idx = dst_idx + c_idx * l_k; let src_idx = c_idx * src_s1 + src_idx; for l_k_idx in 0..l_k { let src_l = l_idx * stride + l_k_idx * dilation; if padding != 0 && (src_l < padding || src_l >= l + padding) { continue; } let src_l = src_l - padding; let src_idx = src_idx + src_l * src_s2; let dst_idx = dst_idx + l_k_idx; dst[dst_idx] = src[src_idx] } } } } Ok(dst) } } struct Im2Col { h_k: usize, w_k: usize, stride: usize, dilation: usize, padding: usize, } impl Im2Col { fn hw_out(&self, h: usize, w: usize) -> (usize, usize) { let h_out = (h + 2 * self.padding - self.dilation * (self.h_k - 1) - 1) / self.stride + 1; let w_out = (w + 2 * self.padding - self.dilation * (self.w_k - 1) - 1) / self.stride + 1; (h_out, w_out) } } impl Map1 for Im2Col { fn f<T: WithDType>(&self, vs: &[T], layout: &Layout) -> Result<Vec<T>> { let &Self { h_k, w_k, stride, dilation, padding, } = self; let (b, c, h, w) = layout.shape().dims4()?; let (h_out, w_out) = self.hw_out(h, w); let src = &vs[layout.start_offset()..]; let mut dst = vec![T::zero(); b * h_out * w_out * c * h_k * w_k]; let (src_s0, src_s1, src_s2, src_s3) = { let s = layout.stride(); (s[0], s[1], s[2], s[3]) }; // TODO: provide specialized kernels for the common use cases. // - h_k = w_k = 1 // - padding = 0 // - stride = 1 // - dilation = 1 for b_idx in 0..b { let src_idx = b_idx * src_s0; let dst_idx = b_idx * h_out * w_out * c * h_k * w_k; for h_idx in 0..h_out { let dst_idx = dst_idx + h_idx * w_out * c * h_k * w_k; for w_idx in 0..w_out { let dst_idx = dst_idx + w_idx * c * h_k * w_k; for c_idx in 0..c { let dst_idx = dst_idx + c_idx * h_k * w_k; let src_idx = c_idx * src_s1 + src_idx; for h_k_idx in 0..h_k { let src_h = h_idx * stride + h_k_idx * dilation; if padding != 0 && (src_h < padding || src_h >= h + padding) { continue; } let src_h = src_h - padding; let src_idx = src_idx + src_h * src_s2; let dst_idx = dst_idx + h_k_idx * w_k; for w_k_idx in 0..w_k { let src_w = w_idx * stride + w_k_idx * dilation; if padding != 0 && (src_w < padding || src_w >= w + padding) { continue; } let src_w = src_w - padding; let src_idx = src_idx + src_w * src_s3; let dst_idx = dst_idx + w_k_idx; dst[dst_idx] = src[src_idx] } } } } } } Ok(dst) } } struct Col2Im1D { stride: usize, } impl Map1 for Col2Im1D { fn f<T: WithDType>(&self, col: &[T], l: &Layout) -> Result<Vec<T>> { let (b_size, l_in, c_out, k_size) = l.shape().dims4()?; let stride = self.stride; let l_out = (l_in - 1) * stride + k_size; let mut im = vec![T::zero(); b_size * c_out * l_out]; let (dst_s0, dst_s1) = (c_out * l_out, l_out); let (src_s0, src_s1, src_s2) = (c_out * k_size * l_in, c_out * k_size, k_size); for l_in_i in 0..l_in { for k_i in 0..k_size { let l_out_i = l_in_i * stride + k_i; for b_i in 0..b_size { for c_i in 0..c_out { let dst_idx = b_i * dst_s0 + c_i * dst_s1 + l_out_i; let src_idx = b_i * src_s0 + l_in_i * src_s1 + c_i * src_s2 + k_i; im[dst_idx] += col[src_idx] } } } } Ok(im) } } struct ConvTranspose1D<'a>(&'a crate::conv::ParamsConvTranspose1D); impl Map2 for ConvTranspose1D<'_> { const OP: &'static str = "conv_transpose1d"; fn f<T: WithDType>(&self, inp: &[T], inp_l: &Layout, k: &[T], k_l: &Layout) -> Result<Vec<T>> { let p = self.0; let inp = &inp[inp_l.start_offset()..]; let k = &k[k_l.start_offset()..]; let (inp_s0, inp_s1, inp_s2) = crate::shape::dims3(inp_l.stride())?; let (k_s0, k_s1, k_s2) = crate::shape::dims3(k_l.stride())?; let l_out = p.l_out(); // Output shape: [b_size, c_out, l_out]. let dst_elems = p.c_out * l_out * p.b_size; let dst = vec![T::zero(); dst_elems]; let dst_s0 = p.c_out * l_out; let dst_s1 = l_out; let dst_s2 = 1; // TODO: Avoid making this copy if `inp` already has the appropriate layout. let mut inp_cont = vec![T::zero(); p.b_size * p.c_in * p.l_in]; let cont_s0 = p.l_in * p.c_in; let cont_s1 = p.c_in; for b_idx in 0..p.b_size { for l_idx in 0..p.l_in { for c_idx in 0..p.c_in { let src_idx = b_idx * inp_s0 + c_idx * inp_s1 + l_idx * inp_s2; let dst_idx = b_idx * cont_s0 + l_idx * cont_s1 + c_idx; inp_cont[dst_idx] = inp[src_idx] } } } for k_idx in 0..p.k_size { (0..p.c_out).into_par_iter().for_each(|dst_c_idx| { let k_cont = (0..p.c_in) .map(|c_in_idx| k[c_in_idx * k_s0 + dst_c_idx * k_s1 + k_idx * k_s2]) .collect::<Vec<_>>(); for b_idx in 0..p.b_size { for l_idx in 0..p.l_in { let out_idx = l_idx * p.stride + k_idx * p.dilation; if out_idx < p.padding { continue; } let out_idx = out_idx - p.padding; if out_idx < l_out { let inp_cont = &inp_cont[b_idx * cont_s0 + l_idx * cont_s1..]; let dst_idx = b_idx * dst_s0 + out_idx * dst_s2 + dst_c_idx * dst_s1; let mut d = T::zero(); unsafe { T::vec_dot(inp_cont.as_ptr(), k_cont.as_ptr(), &mut d, p.c_in) } let dst_p = dst.as_ptr(); // Safety: dst_idx are uniques per dst_c_idx which is used to // parallelise the different tasks so no two threads can try to // write at the same location. unsafe { let ptr = dst_p.add(dst_idx) as *mut T; *ptr += d } } } } }) } Ok(dst) } } struct Conv2D<'a>(&'a crate::conv::ParamsConv2D); impl Map2 for Conv2D<'_> { const OP: &'static str = "conv2d"; fn f<T: WithDType>(&self, inp: &[T], inp_l: &Layout, k: &[T], k_l: &Layout) -> Result<Vec<T>> { let p = self.0; let inp = &inp[inp_l.start_offset()..]; let (inp_s0, inp_s1, inp_s2, inp_s3) = crate::shape::dims4(inp_l.stride())?; let k = &k[k_l.start_offset()..]; let (k_s0, k_s1, k_s2, k_s3) = crate::shape::dims4(k_l.stride())?; let (out_h, out_w) = (p.out_h(), p.out_w()); // Output shape: [b_size, c_out, out_h, out_w]. let dst = vec![T::zero(); p.b_size * p.c_out * out_h * out_w]; // TODO: Avoid making this copy if `inp` already has the appropriate layout. let mut inp_cont = vec![T::zero(); p.b_size * p.c_in * p.i_h * p.i_w]; let cont_s0 = p.i_h * p.i_w * p.c_in; let cont_s1 = p.i_w * p.c_in; let cont_s2 = p.c_in; for b_idx in 0..p.b_size { for h_idx in 0..p.i_h { for w_idx in 0..p.i_w { for c_idx in 0..p.c_in { let src_idx = b_idx * inp_s0 + c_idx * inp_s1 + h_idx * inp_s2 + w_idx * inp_s3; let dst_idx = b_idx * cont_s0 + h_idx * cont_s1 + w_idx * cont_s2 + c_idx; inp_cont[dst_idx] = inp[src_idx] } } } } for offset_h in 0..p.k_h { for offset_w in 0..p.k_w { (0..p.c_out).into_par_iter().for_each(|dst_c_idx| { let dst_idx = dst_c_idx * out_w * out_h; let k_cont = (0..p.c_in) .map(|c_in_idx| { k[dst_c_idx * k_s0 + c_in_idx * k_s1 + offset_h * k_s2 + offset_w * k_s3] }) .collect::<Vec<_>>(); for b_idx in 0..p.b_size { let dst_idx = dst_idx + b_idx * p.c_out * out_h * out_w; for dst_h in 0..out_h { let dst_idx = dst_idx + dst_h * out_w; let src_h = p.stride * dst_h + offset_h * p.dilation; if src_h < p.padding || src_h >= p.i_h + p.padding { continue; } let src_h = src_h - p.padding; for dst_w in 0..out_w { let dst_idx = dst_idx + dst_w; let src_w = p.stride * dst_w + offset_w * p.dilation; if src_w < p.padding || src_w >= p.i_w + p.padding { continue; } let src_w = src_w - p.padding; let inp_cont = &inp_cont [b_idx * cont_s0 + src_h * cont_s1 + src_w * cont_s2..]; assert!(inp_cont.len() >= p.c_in); assert!(k_cont.len() >= p.c_in); let mut d = T::zero(); unsafe { T::vec_dot(inp_cont.as_ptr(), k_cont.as_ptr(), &mut d, p.c_in) } let dst_p = dst.as_ptr(); // Safety: dst_idx are uniques per dst_c_idx which is used to parallelise // the different tasks so no two threads can try to write at the same // location. unsafe { let ptr = dst_p.add(dst_idx) as *mut T; *ptr += d } } } } }); } } Ok(dst) } } struct ConvTranspose2D<'a>(&'a crate::conv::ParamsConvTranspose2D); impl Map2 for ConvTranspose2D<'_> { const OP: &'static str = "conv_transpose2d"; fn f<T: WithDType>(&self, inp: &[T], inp_l: &Layout, k: &[T], k_l: &Layout) -> Result<Vec<T>> { let p = self.0; let inp = &inp[inp_l.start_offset()..]; let (inp_s0, inp_s1, inp_s2, inp_s3) = crate::shape::dims4(inp_l.stride())?; let k = &k[k_l.start_offset()..]; let (k_s0, k_s1, k_s2, k_s3) = crate::shape::dims4(k_l.stride())?; let (out_h, out_w) = (p.out_h(), p.out_w()); // Output shape: [b_size, c_out, out_h, out_w]. let dst = vec![T::zero(); p.b_size * p.c_out * out_h * out_w]; let dst_s0 = p.c_out * out_h * out_w; let dst_s1 = out_h * out_w; let dst_s2 = out_w; let dst_s3 = 1; // TODO: Avoid making this copy if `inp` already has the appropriate layout. let mut inp_cont = vec![T::zero(); p.b_size * p.c_in * p.i_h * p.i_w]; let cont_s0 = p.i_h * p.i_w * p.c_in; let cont_s1 = p.i_w * p.c_in; let cont_s2 = p.c_in; for b_idx in 0..p.b_size { for h_idx in 0..p.i_h { for w_idx in 0..p.i_w { for c_idx in 0..p.c_in { let src_idx = b_idx * inp_s0 + c_idx * inp_s1 + h_idx * inp_s2 + w_idx * inp_s3; let dst_idx = b_idx * cont_s0 + h_idx * cont_s1 + w_idx * cont_s2 + c_idx; inp_cont[dst_idx] = inp[src_idx] } } } } for k_y in 0..p.k_h { for k_x in 0..p.k_w { (0..p.c_out).into_par_iter().for_each(|dst_c_idx| { let k_cont = (0..p.c_in) .map(|c_in_idx| { k[c_in_idx * k_s0 + dst_c_idx * k_s1 + k_y * k_s2 + k_x * k_s3] }) .collect::<Vec<_>>(); for b_idx in 0..p.b_size { for inp_y in 0..p.i_h { for inp_x in 0..p.i_w { let out_x = inp_x * p.stride + k_x * p.dilation; let out_y = inp_y * p.stride + k_y * p.dilation; if out_x < p.padding || out_y < p.padding { continue; } let out_x = out_x - p.padding; let out_y = out_y - p.padding; if out_x < out_w && out_y < out_h { let inp_cont = &inp_cont [b_idx * cont_s0 + inp_y * cont_s1 + inp_x * cont_s2..]; let dst_idx = b_idx * dst_s0 + out_y * dst_s2 + out_x * dst_s3 + dst_c_idx * dst_s1; let mut d = T::zero(); unsafe { T::vec_dot( inp_cont.as_ptr(), k_cont.as_ptr(), &mut d, p.c_in, ) } let dst_p = dst.as_ptr(); // Safety: dst_idx are uniques per dst_c_idx which is used to // parallelise the different tasks so no two threads can try to // write at the same location. unsafe { let ptr = dst_p.add(dst_idx) as *mut T; *ptr += d } } } } } }) } } Ok(dst) } } struct MatMul((usize, usize, usize, usize)); impl MatMul { fn striding_error(&self, lhs_l: &Layout, rhs_l: &Layout, msg: &'static str) -> Error { Error::MatMulUnexpectedStriding(Box::new(crate::error::MatMulUnexpectedStriding { lhs_l: lhs_l.clone(), rhs_l: rhs_l.clone(), bmnk: self.0, msg, })) .bt() } fn ab_skip(&self, lhs_l: &Layout, rhs_l: &Layout) -> Result<(usize, usize)> { let lhs_stride = lhs_l.stride(); let rhs_stride = rhs_l.stride(); let rank = lhs_stride.len(); let (_b, m, n, k) = self.0; let a_skip: usize = match lhs_stride[..rank - 2] { [s1, stride] if s1 == stride * lhs_l.dims()[1] => stride, [_, stride] if lhs_l.dims()[0] == 1 => stride, [stride, _] if lhs_l.dims()[1] == 1 => stride, [stride] => stride, [] => m * k, _ => Err(self.striding_error(lhs_l, rhs_l, "non-contiguous lhs"))?, }; let b_skip: usize = match rhs_stride[..rank - 2] { [s1, stride] if s1 == stride * rhs_l.dims()[1] => stride, [_, stride] if rhs_l.dims()[0] == 1 => stride, [stride, _] if rhs_l.dims()[1] == 1 => stride, [stride] => stride, [] => n * k, _ => Err(self.striding_error(lhs_l, rhs_l, "non-contiguous rhs"))?, }; Ok((a_skip, b_skip)) } } impl Map2 for MatMul { const OP: &'static str = "mat_mul"; #[cfg(all(not(feature = "mkl"), not(feature = "accelerate")))] fn f<T: 'static + WithDType + num_traits::Num + Copy>( &self, lhs: &[T], lhs_l: &Layout, rhs: &[T], rhs_l: &Layout, ) -> Result<Vec<T>> { use gemm::{gemm, Parallelism}; match T::DTYPE { DType::F16 | DType::F32 | DType::F64 => {} _ => Err(Error::UnsupportedDTypeForOp(T::DTYPE, "matmul").bt())?, } let (b, m, n, k) = self.0; let lhs = &lhs[lhs_l.start_offset()..]; let rhs = &rhs[rhs_l.start_offset()..]; let lhs_stride = lhs_l.stride(); let rhs_stride = rhs_l.stride(); let rank = lhs_stride.len(); let lhs_cs = lhs_stride[rank - 1]; let lhs_rs = lhs_stride[rank - 2]; let rhs_cs = rhs_stride[rank - 1]; let rhs_rs = rhs_stride[rank - 2]; let (a_skip, b_skip) = self.ab_skip(lhs_l, rhs_l)?; let c_skip: usize = m * n; let dst_shape: Shape = (m, n).into(); let dst_strides = dst_shape.stride_contiguous(); let dst_rs = dst_strides[0]; let dst_cs = dst_strides[1]; let mut dst = vec![T::zero(); b * m * n]; let num_threads = crate::utils::get_num_threads(); let parallelism = if num_threads > 1 { Parallelism::Rayon(num_threads) } else { Parallelism::None }; let (b, m, n, k) = if b_skip == 0 && a_skip == m * k { // a_skip and c_skip should be updated but step is always 0 so // it wouldn't matter. (1, b * m, n, k) } else if a_skip == 0 && b_skip == n * k { (1, m, b * n, k) } else { (b, m, n, k) }; for step in 0..b { let lhs_p = &lhs[step * a_skip..]; let rhs_p = &rhs[step * b_skip..]; let dst_p = &mut dst[step * c_skip..]; unsafe { gemm( /* m: usize = */ m, /* n: usize = */ n, /* k: usize = */ k, /* dst: *mut T = */ dst_p.as_mut_ptr(), /* dst_cs: isize = */ dst_cs as isize, /* dst_rs: isize = */ dst_rs as isize, /* read_dst: bool = */ false, /* lhs: *const T = */ lhs_p.as_ptr(), /* lhs_cs: isize = */ lhs_cs as isize, /* lhs_rs: isize = */ lhs_rs as isize, /* rhs: *const T = */ rhs_p.as_ptr(), /* rhs_cs: isize = */ rhs_cs as isize, /* rhs_rs: isize = */ rhs_rs as isize, /* alpha: T = */ T::zero(), /* beta: T = */ T::one(), /* conj_dst: bool = */ false, /* conj_lhs: bool = */ false, /* conj_rhs: bool = */ false, parallelism, ) } } Ok(dst) } #[cfg(feature = "accelerate")] fn f<T: 'static + WithDType + num_traits::Num + Copy>( &self, lhs: &[T], lhs_l: &Layout, rhs: &[T], rhs_l: &Layout, ) -> Result<Vec<T>> { let (b, m, n, k) = self.0; let lhs = &lhs[lhs_l.start_offset()..]; let rhs = &rhs[rhs_l.start_offset()..]; let lhs_stride = lhs_l.stride(); let rhs_stride = rhs_l.stride(); let (a_skip, b_skip) = self.ab_skip(lhs_l, rhs_l)?; let c_skip: usize = m * n; 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]; let (lda, transa) = if (rhs_m1 == 1 || n == 1) && (rhs_m2 == n || k == 1) { (n as i32, b'N') } else if rhs_m1 == k && rhs_m2 == 1 { (k as i32, b'T') } else { Err(self.striding_error(lhs_l, rhs_l, "non-contiguous rhs"))? }; // The b tensor has dims batching, m, k (lhs) let (ldb, transb) = if (lhs_m1 == 1 || k == 1) && (lhs_m2 == k || m == 1) { (k as i32, b'N') } else if lhs_m1 == m && lhs_m2 == 1 { (m as i32, b'T') } else { Err(self.striding_error(lhs_l, rhs_l, "non-contiguous lhs"))? }; let mut dst = vec![T::zero(); b * m * n]; match T::DTYPE { DType::F16 => { crate::bail!("the accelerate backend does not support f16 matmul") } DType::F32 => { for step in 0..b { let lhs_p = &lhs[step * a_skip..]; let rhs_p = &rhs[step * b_skip..]; let dst_p = &mut dst[step * c_skip..]; unsafe { let a = rhs_p.as_ptr() as *const f32; let b = lhs_p.as_ptr() as *const f32; let c = dst_p.as_mut_ptr() as *mut f32; let a = std::slice::from_raw_parts(a, a_skip); let b = std::slice::from_raw_parts(b, b_skip); let c = std::slice::from_raw_parts_mut(c, c_skip); crate::accelerate::sgemm( transa, transb, /* m= */ n as i32, /* n= */ m as i32, /* k= */ k as i32, /* alpha= */ 1., /* a= */ a, /* lda= */ lda, /* b= */ b, /* ldb= */ ldb, /* beta= */ 0., /* c= */ c, /* ldc= */ n as i32, ) } } } DType::F64 => { for step in 0..b { let lhs_p = &lhs[step * a_skip..]; let rhs_p = &rhs[step * b_skip..]; let dst_p = &mut dst[step * c_skip..]; unsafe { let a = rhs_p.as_ptr() as *const f64; let b = lhs_p.as_ptr() as *const f64; let c = dst_p.as_mut_ptr() as *mut f64; let a = std::slice::from_raw_parts(a, a_skip); let b = std::slice::from_raw_parts(b, b_skip); let c = std::slice::from_raw_parts_mut(c, c_skip); crate::accelerate::dgemm( transa, transb, /* m= */ n as i32, /* n= */ m as i32, /* k= */ k as i32, /* alpha= */ 1., /* a= */ a, /* lda= */ lda, /* b= */ b, /* ldb= */ ldb, /* beta= */ 0., /* c= */ c, /* ldc= */ n as i32, ) } } } dtype => Err(Error::UnsupportedDTypeForOp(dtype, "matmul").bt())?, } Ok(dst) } #[cfg(feature = "mkl")] fn f<T: 'static + WithDType + num_traits::Num + Copy>( &self, lhs: &[T], lhs_l: &Layout, rhs: &[T], rhs_l: &Layout, ) -> Result<Vec<T>> { let (b, m, n, k) = self.0; let lhs = &lhs[lhs_l.start_offset()..]; let rhs = &rhs[rhs_l.start_offset()..]; let lhs_stride = lhs_l.stride(); let rhs_stride = rhs_l.stride(); let (a_skip, b_skip) = self.ab_skip(lhs_l, rhs_l)?; let c_skip: usize = m * n; 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]; let (lda, transa) = if (rhs_m1 == 1 || n == 1) && (rhs_m2 == n || k == 1) { (n as i32, b'N') } else if rhs_m1 == k && rhs_m2 == 1 { (k as i32, b'T') } else { Err(self.striding_error(lhs_l, rhs_l, "non-contiguous rhs"))? }; // The b tensor has dims batching, m, k (lhs) let (ldb, transb) = if (lhs_m1 == 1 || k == 1) && (lhs_m2 == k || m == 1) { (k as i32, b'N') } else if lhs_m1 == m && lhs_m2 == 1 { (m as i32, b'T') } else { Err(self.striding_error(lhs_l, rhs_l, "non-contiguous lhs"))? }; let mut dst = vec![T::zero(); b * m * n]; match T::DTYPE { DType::F16 => { for step in 0..b { let lhs_p = &lhs[step * a_skip..]; let rhs_p = &rhs[step * b_skip..]; let dst_p = &mut dst[step * c_skip..]; unsafe { let a = rhs_p.as_ptr() as *const f16; let b = lhs_p.as_ptr() as *const f16; let c = dst_p.as_mut_ptr() as *mut f16; let a = std::slice::from_raw_parts(a, a_skip); let b = std::slice::from_raw_parts(b, b_skip); let c = std::slice::from_raw_parts_mut(c, c_skip); crate::mkl::hgemm( transa, transb, /* m= */ n as i32, /* n= */ m as i32, /* k= */ k as i32, /* alpha= */ f16::ONE, /* a= */ a, /* lda= */ lda, /* b= */ b, /* ldb= */ ldb, /* beta= */ f16::ZERO, /* c= */ c, /* ldc= */ n as i32, ) } } } DType::F32 => { for step in 0..b { let lhs_p = &lhs[step * a_skip..]; let rhs_p = &rhs[step * b_skip..]; let dst_p = &mut dst[step * c_skip..]; unsafe { let a = rhs_p.as_ptr() as *const f32; let b = lhs_p.as_ptr() as *const f32; let c = dst_p.as_mut_ptr() as *mut f32; let a = std::slice::from_raw_parts(a, a_skip); let b = std::slice::from_raw_parts(b, b_skip); let c = std::slice::from_raw_parts_mut(c, c_skip); crate::mkl::sgemm( transa, transb, /* m= */ n as i32, /* n= */ m as i32, /* k= */ k as i32, /* alpha= */ 1., /* a= */ a, /* lda= */ lda, /* b= */ b, /* ldb= */ ldb, /* beta= */ 0., /* c= */ c, /* ldc= */ n as i32, ) } } } DType::F64 => { for step in 0..b { let lhs_p = &lhs[step * a_skip..]; let rhs_p = &rhs[step * b_skip..]; let dst_p = &mut dst[step * c_skip..]; unsafe { let a = rhs_p.as_ptr() as *const f64; let b = lhs_p.as_ptr() as *const f64; let c = dst_p.as_mut_ptr() as *mut f64; let a = std::slice::from_raw_parts(a, a_skip); let b = std::slice::from_raw_parts(b, b_skip); let c = std::slice::from_raw_parts_mut(c, c_skip); crate::mkl::dgemm( transa, transb, /* m= */ n as i32, /* n= */ m as i32, /* k= */ k as i32, /* alpha= */ 1., /* a= */ a, /* lda= */ lda, /* b= */ b, /* ldb= */ ldb, /* beta= */ 0., /* c= */ c, /* ldc= */ n as i32, ) } } } dtype => Err(Error::UnsupportedDTypeForOp(dtype, "matmul").bt())?, } Ok(dst) } } fn elu<T: num_traits::Float>(v: T, alpha: T) -> T { if v.is_sign_positive() { v } else { (v.exp() - T::one()) * alpha } } impl CpuStorage { pub fn as_slice<D: WithDType>(&self) -> Result<&[D]> { D::cpu_storage_as_slice(self) } pub fn concat(storages: &[CpuStorage]) -> Result<CpuStorage> { let storage0 = &storages[0]; let s = match storage0 { Self::U8(_) => { let storages = storages .iter() .map(|s| match s { Self::U8(s) => Ok(s.as_slice()), _ => crate::bail!("dtype mismatch"), }) .collect::<Result<Vec<_>>>()? .concat(); Self::U8(storages) } Self::U32(_) => { let storages = storages .iter() .map(|s| match s { Self::U32(s) => Ok(s.as_slice()), _ => crate::bail!("dtype mismatch"), }) .collect::<Result<Vec<_>>>()? .concat(); Self::U32(storages) } Self::I64(_) => { let storages = storages .iter() .map(|s| match s { Self::I64(s) => Ok(s.as_slice()), _ => crate::bail!("dtype mismatch"), }) .collect::<Result<Vec<_>>>()? .concat(); Self::I64(storages) } Self::BF16(_) => { let storages = storages .iter() .map(|s| match s { Self::BF16(s) => Ok(s.as_slice()), _ => crate::bail!("dtype mismatch"), }) .collect::<Result<Vec<_>>>()? .concat(); Self::BF16(storages) } Self::F16(_) => { let storages = storages .iter() .map(|s| match s { Self::F16(s) => Ok(s.as_slice()), _ => crate::bail!("dtype mismatch"), }) .collect::<Result<Vec<_>>>()? .concat(); Self::F16(storages) } Self::F32(_) => { let storages = storages .iter() .map(|s| match s { Self::F32(s) => Ok(s.as_slice()), _ => crate::bail!("dtype mismatch"), }) .collect::<Result<Vec<_>>>()? .concat(); Self::F32(storages) } Self::F64(_) => { let storages = storages .iter() .map(|s| match s { Self::F64(s) => Ok(s.as_slice()), _ => crate::bail!("dtype mismatch"), }) .collect::<Result<Vec<_>>>()? .concat(); Self::F64(storages) } Self::F8E4M3(_) => { let storages = storages .iter() .map(|s| match s { Self::F8E4M3(s) => Ok(s.as_slice()), _ => crate::bail!("dtype mismatch"), }) .collect::<Result<Vec<_>>>()? .concat(); Self::F8E4M3(storages) } }; Ok(s) } } impl BackendStorage for CpuStorage { type Device = CpuDevice; fn dtype(&self) -> DType { match self { Self::U8(_) => DType::U8, Self::U32(_) => DType::U32, Self::I64(_) => DType::I64, Self::BF16(_) => DType::BF16, Self::F16(_) => DType::F16, Self::F32(_) => DType::F32, Self::F64(_) => DType::F64, Self::F8E4M3(_) => DType::F8E4M3, } } fn to_dtype(&self, layout: &Layout, dtype: DType) -> Result<Self> { // TODO: find a way around the quadratic number of cases below. match (self, dtype) { (Self::U8(storage), DType::BF16) => { let data = unary_map(storage, layout, |v| bf16::from_f32(v as f32)); Ok(Self::BF16(data)) } (Self::U32(storage), DType::BF16) => { let data = unary_map(storage, layout, |v| bf16::from_f32(v as f32)); Ok(Self::BF16(data)) } (Self::I64(storage), DType::BF16) => { let data = unary_map(storage, layout, |v| bf16::from_f32(v as f32)); Ok(Self::BF16(data)) } (Self::BF16(storage), DType::BF16) => { let data = unary_map(storage, layout, |v| v); Ok(Self::BF16(data)) } (Self::F16(storage), DType::BF16) => { let data = unary_map(storage, layout, |v| bf16::from_f32(v.to_f32())); Ok(Self::BF16(data)) } (Self::F32(storage), DType::BF16) => { let data = unary_map(storage, layout, bf16::from_f32); Ok(Self::BF16(data)) } (Self::F64(storage), DType::BF16) => { let data = unary_map(storage, layout, bf16::from_f64); Ok(Self::BF16(data)) } (Self::F8E4M3(storage), DType::BF16) => { let data = unary_map(storage, layout, |v| bf16::from_f32(v.to_f32())); Ok(Self::BF16(data)) } (Self::U8(storage), DType::F16) => { let data = unary_map(storage, layout, |v| f16::from_f32(v as f32)); Ok(Self::F16(data)) } (Self::U32(storage), DType::F16) => { let data = unary_map(storage, layout, |v| f16::from_f32(v as f32)); Ok(Self::F16(data)) } (Self::I64(storage), DType::F16) => { let data = unary_map(storage, layout, |v| f16::from_f32(v as f32)); Ok(Self::F16(data)) } (Self::BF16(storage), DType::F16) => { let data = unary_map(storage, layout, |v| f16::from_f32(v.to_f32())); Ok(Self::F16(data)) } (Self::F16(storage), DType::F16) => { let data = unary_map(storage, layout, |v| v); Ok(Self::F16(data)) } (Self::F32(storage), DType::F16) => { let data = unary_map(storage, layout, f16::from_f32); Ok(Self::F16(data)) } (Self::F64(storage), DType::F16) => { let data = unary_map(storage, layout, f16::from_f64); Ok(Self::F16(data)) } (Self::F8E4M3(storage), DType::F16) => { let data = unary_map(storage, layout, |v| f16::from_f32(v.to_f32())); Ok(Self::F16(data)) } (Self::U8(storage), DType::F32) => { let data = unary_map(storage, layout, |v| v as f32); Ok(Self::F32(data)) } (Self::U32(storage), DType::F32) => { let data = unary_map(storage, layout, |v| v as f32); Ok(Self::F32(data)) } (Self::I64(storage), DType::F32) => { let data = unary_map(storage, layout, |v| v as f32); Ok(Self::F32(data)) } (Self::BF16(storage), DType::F32) => { let data = unary_map(storage, layout, |v| v.to_f32()); Ok(Self::F32(data)) } (Self::F16(storage), DType::F32) => { let data = unary_map(storage, layout, |v| v.to_f32()); Ok(Self::F32(data)) } (Self::F32(storage), DType::F32) => { let data = unary_map(storage, layout, |v| v); Ok(Self::F32(data)) } (Self::F64(storage), DType::F32) => { let data = unary_map(storage, layout, |v| v as f32); Ok(Self::F32(data)) } (Self::F8E4M3(storage), DType::F32) => { let data = unary_map(storage, layout, |v| v.to_f32()); Ok(Self::F32(data)) } (Self::U8(storage), DType::U8) => { let data = unary_map(storage, layout, |v| v); Ok(Self::U8(data)) } (Self::BF16(storage), DType::U8) => { let data = unary_map(storage, layout, |v| v.to_f32() as u8); Ok(Self::U8(data)) } (Self::F16(storage), DType::U8) => { let data = unary_map(storage, layout, |v| v.to_f32() as u8); Ok(Self::U8(data)) } (Self::F32(storage), DType::U8) => { let data = unary_map(storage, layout, |v| v as u8); Ok(Self::U8(data)) } (Self::F64(storage), DType::U8) => { let data = unary_map(storage, layout, |v| v as u8); Ok(Self::U8(data)) } (Self::U32(storage), DType::U8) => { let data = unary_map(storage, layout, |v| v as u8); Ok(Self::U8(data)) } (Self::I64(storage), DType::U8) => { let data = unary_map(storage, layout, |v| v as u8); Ok(Self::U8(data)) } (Self::F8E4M3(storage), DType::U8) => { let data = unary_map(storage, layout, |v| v.to_f32() as u8); Ok(Self::U8(data)) } (Self::U8(storage), DType::U32) => { let data = unary_map(storage, layout, |v| v as u32); Ok(Self::U32(data)) } (Self::U32(storage), DType::U32) => { let data = unary_map(storage, layout, |v| v); Ok(Self::U32(data)) } (Self::I64(storage), DType::U32) => { let data = unary_map(storage, layout, |v| v as u32); Ok(Self::U32(data)) } (Self::BF16(storage), DType::U32) => { let data = unary_map(storage, layout, |v| v.to_f32() as u32); Ok(Self::U32(data)) } (Self::F16(storage), DType::U32) => { let data = unary_map(storage, layout, |v| v.to_f32() as u32); Ok(Self::U32(data)) } (Self::F32(storage), DType::U32) => { let data = unary_map(storage, layout, |v| v as u32); Ok(Self::U32(data)) } (Self::F64(storage), DType::U32) => { let data = unary_map(storage, layout, |v| v as u32); Ok(Self::U32(data)) } (Self::F8E4M3(storage), DType::U32) => { let data = unary_map(storage, layout, |v| v.to_f32() as u32); Ok(Self::U32(data)) } (Self::U8(storage), DType::I64) => { let data = unary_map(storage, layout, |v| v as i64); Ok(Self::I64(data)) } (Self::U32(storage), DType::I64) => { let data = unary_map(storage, layout, |v| v as i64); Ok(Self::I64(data)) } (Self::I64(storage), DType::I64) => { let data = unary_map(storage, layout, |v| v); Ok(Self::I64(data)) } (Self::BF16(storage), DType::I64) => { let data = unary_map(storage, layout, |v| v.to_f32() as i64); Ok(Self::I64(data)) } (Self::F16(storage), DType::I64) => { let data = unary_map(storage, layout, |v| v.to_f32() as i64); Ok(Self::I64(data)) } (Self::F32(storage), DType::I64) => { let data = unary_map(storage, layout, |v| v as i64); Ok(Self::I64(data)) } (Self::F64(storage), DType::I64) => { let data = unary_map(storage, layout, |v| v as i64); Ok(Self::I64(data)) } (Self::F8E4M3(storage), DType::I64) => { let data = unary_map(storage, layout, |v| v.to_f32() as i64); Ok(Self::I64(data)) } (Self::U8(storage), DType::F64) => { let data = unary_map(storage, layout, |v| v as f64); Ok(Self::F64(data)) } (Self::U32(storage), DType::F64) => { let data = unary_map(storage, layout, |v| v as f64); Ok(Self::F64(data)) } (Self::I64(storage), DType::F64) => { let data = unary_map(storage, layout, |v| v as f64); Ok(Self::F64(data)) } (Self::BF16(storage), DType::F64) => { let data = unary_map(storage, layout, |v| v.to_f64()); Ok(Self::F64(data)) } (Self::F16(storage), DType::F64) => { let data = unary_map(storage, layout, |v| v.to_f64()); Ok(Self::F64(data)) } (Self::F32(storage), DType::F64) => { let data = unary_map(storage, layout, |v| v as f64); Ok(Self::F64(data)) } (Self::F64(storage), DType::F64) => { let data = unary_map(storage, layout, |v| v); Ok(Self::F64(data)) } (Self::F8E4M3(storage), DType::F64) => { let data = unary_map(storage, layout, |v| v.to_f64()); Ok(Self::F64(data)) } (Self::U8(storage), DType::F8E4M3) => { let data = unary_map(storage, layout, |v| F8E4M3::from_f32(v as f32)); Ok(Self::F8E4M3(data)) } (Self::U32(storage), DType::F8E4M3) => { let data = unary_map(storage, layout, |v| F8E4M3::from_f32(v as f32)); Ok(Self::F8E4M3(data)) } (Self::I64(storage), DType::F8E4M3) => { let data = unary_map(storage, layout, |v| F8E4M3::from_f32(v as f32)); Ok(Self::F8E4M3(data)) } (Self::BF16(storage), DType::F8E4M3) => { let data = unary_map(storage, layout, |v| F8E4M3::from(v.to_f32())); Ok(Self::F8E4M3(data)) } (Self::F16(storage), DType::F8E4M3) => { let data = unary_map(storage, layout, |v| F8E4M3::from_f32(v.to_f32())); Ok(Self::F8E4M3(data)) } (Self::F32(storage), DType::F8E4M3) => { let data = unary_map(storage, layout, F8E4M3::from_f32); Ok(Self::F8E4M3(data)) } (Self::F64(storage), DType::F8E4M3) => { let data = unary_map(storage, layout, F8E4M3::from_f64); Ok(Self::F8E4M3(data)) } (Self::F8E4M3(storage), DType::F8E4M3) => { let data = unary_map(storage, layout, |v| v); Ok(Self::F8E4M3(data)) } } } fn reduce_op(&self, op: ReduceOp, layout: &Layout, reduce_dims: &[usize]) -> Result<Self> { match op { ReduceOp::Sum => { let src_dims = layout.dims(); let mut dst_dims = src_dims.to_vec(); for &dim in reduce_dims.iter() { dst_dims[dim] = 1; } let dst_shape = Shape::from(dst_dims); let mut reduce_dims = reduce_dims.to_vec(); // Sort the reduce_dims as they have to be processed from left to right when converting the // indexes. reduce_dims.sort(); let reduce_dims_and_stride: Vec<_> = reduce_dims .iter() .map(|&d| (src_dims[d], src_dims[d + 1..].iter().product::<usize>())) .collect(); ReduceSum { dst_shape: &dst_shape, reduce_dims: &reduce_dims, reduce_dims_and_stride, } .map(self, layout) } ReduceOp::Min | ReduceOp::ArgMin | ReduceOp::Max | ReduceOp::ArgMax => { let reduce_dim_index = match reduce_dims { [reduce_dim_index] => *reduce_dim_index, _ => { let op = match op { ReduceOp::Min => "min", ReduceOp::ArgMin => "argmin", ReduceOp::Max => "max", ReduceOp::ArgMax => "argmax", _ => unreachable!(), }; let dims = reduce_dims.to_vec(); Err(Error::OnlySingleDimension { op, dims })? } }; let (use_min, return_index) = match op { ReduceOp::Min => (true, false), ReduceOp::ArgMin => (true, true), ReduceOp::Max => (false, false), ReduceOp::ArgMax => (false, true), _ => unreachable!(), }; ReduceIndex { reduce_dim_index, use_min, return_index, } .map(self, layout) } } } fn cmp(&self, op: CmpOp, rhs: &Self, lhs_l: &Layout, rhs_l: &Layout) -> Result<Self> { Cmp(op).map(self, lhs_l, rhs, rhs_l) } fn affine(&self, layout: &Layout, mul: f64, add: f64) -> Result<Self> { Affine(mul, add).map(self, layout) } fn avg_pool2d( &self, layout: &Layout, kernel_size: (usize, usize), stride: (usize, usize), ) -> Result<Self> { AvgPool2D(kernel_size, stride).map(self, layout) } fn max_pool2d( &self, layout: &Layout, kernel_size: (usize, usize), stride: (usize, usize), ) -> Result<Self> { MaxPool2D(kernel_size, stride).map(self, layout) } fn upsample_nearest1d(&self, layout: &Layout, sz: usize) -> Result<Self> { UpsampleNearest1D(sz).map(self, layout) } fn upsample_nearest2d(&self, layout: &Layout, h: usize, w: usize) -> Result<Self> { UpsampleNearest2D(h, w).map(self, layout) } fn powf(&self, layout: &Layout, e: f64) -> Result<Self> { use num_traits::Float; // TODO: Have some generic map for functions that apply on num_traits::Float elements. match self { Self::BF16(storage) => { let data = unary_map(storage, layout, |v| v.powf(bf16::from_f64(e))); Ok(Self::BF16(data)) } Self::F16(storage) => { let data = unary_map(storage, layout, |v| v.powf(f16::from_f64(e))); Ok(Self::F16(data)) } Self::F32(storage) => { let data = unary_map(storage, layout, |v| v.powf(e as f32)); Ok(Self::F32(data)) } Self::F64(storage) => { let data = unary_map(storage, layout, |v| v.powf(e)); Ok(Self::F64(data)) } Self::F8E4M3(storage) => { let data = unary_map(storage, layout, |v| v.powf(F8E4M3::from_f64(e))); Ok(Self::F8E4M3(data)) } Self::U8(_) => Err(Error::UnsupportedDTypeForOp(DType::U8, "elu").bt()), Self::U32(_) => Err(Error::UnsupportedDTypeForOp(DType::U32, "elu").bt()), Self::I64(_) => Err(Error::UnsupportedDTypeForOp(DType::I64, "elu").bt()), } } fn elu(&self, layout: &Layout, alpha: f64) -> Result<Self> { // TODO: Have some generic map for functions that apply on num_traits::Float elements. match self { Self::BF16(storage) => { let data = unary_map(storage, layout, |v| elu(v, bf16::from_f64(alpha))); Ok(Self::BF16(data)) } Self::F16(storage) => { let data = unary_map(storage, layout, |v| elu(v, f16::from_f64(alpha))); Ok(Self::F16(data)) } Self::F32(storage) => { let data = unary_map(storage, layout, |v| elu(v, f32::from_f64(alpha))); Ok(Self::F32(data)) } Self::F64(storage) => { let data = unary_map(storage, layout, |v| elu(v, alpha)); Ok(Self::F64(data)) } Self::F8E4M3(storage) => { let data = unary_map(storage, layout, |v| elu(v, F8E4M3::from_f64(alpha))); Ok(Self::F8E4M3(data)) } Self::U8(_) => Err(Error::UnsupportedDTypeForOp(DType::U8, "elu").bt()), Self::U32(_) => Err(Error::UnsupportedDTypeForOp(DType::U32, "elu").bt()), Self::I64(_) => Err(Error::UnsupportedDTypeForOp(DType::I64, "elu").bt()), } } fn unary_impl<B: UnaryOpT>(&self, layout: &Layout) -> Result<Self> { match self { Self::BF16(storage) => { if B::BF16_VEC { let data = unary_map_vec(storage, layout, B::bf16, B::bf16_vec); Ok(Self::BF16(data)) } else { let data = unary_map(storage, layout, B::bf16); Ok(Self::BF16(data)) } } Self::F16(storage) => { if B::F16_VEC { let data = unary_map_vec(storage, layout, B::f16, B::f16_vec); Ok(Self::F16(data)) } else { let data = unary_map(storage, layout, B::f16); Ok(Self::F16(data)) } } Self::F32(storage) => { if B::F32_VEC { let data = unary_map_vec(storage, layout, B::f32, B::f32_vec); Ok(Self::F32(data)) } else { let data = unary_map(storage, layout, B::f32); Ok(Self::F32(data)) } } Self::F64(storage) => { if B::F64_VEC { let data = unary_map_vec(storage, layout, B::f64, B::f64_vec); Ok(Self::F64(data)) } else { let data = unary_map(storage, layout, B::f64); Ok(Self::F64(data)) } } Self::F8E4M3(storage) => { if B::F8E4M3_VEC { let data = unary_map_vec(storage, layout, B::f8e4m3, B::f8e4m3_vec); Ok(Self::F8E4M3(data)) } else { let data = unary_map(storage, layout, B::f8e4m3); Ok(Self::F8E4M3(data)) } } Self::U8(storage) => { let data = unary_map(storage, layout, B::u8); Ok(Self::U8(data)) } Self::U32(storage) => { let data = unary_map(storage, layout, B::u32); Ok(Self::U32(data)) } Self::I64(storage) => { let data = unary_map(storage, layout, B::i64); Ok(Self::I64(data)) } } } fn binary_impl<B: BinaryOpT>( &self, rhs: &Self, lhs_l: &Layout, rhs_l: &Layout, ) -> Result<Self> { match (self, rhs) { (Self::BF16(lhs), Self::BF16(rhs)) => { let data = if B::BF16_VEC { binary_map_vec(lhs_l, rhs_l, lhs, rhs, B::bf16, B::bf16_vec) } else { binary_map(lhs_l, rhs_l, lhs, rhs, B::bf16) }; Ok(Self::BF16(data)) } (Self::F16(lhs), Self::F16(rhs)) => { let data = if B::F16_VEC { binary_map_vec(lhs_l, rhs_l, lhs, rhs, B::f16, B::f16_vec) } else { binary_map(lhs_l, rhs_l, lhs, rhs, B::f16) }; Ok(Self::F16(data)) } (Self::F32(lhs), Self::F32(rhs)) => { let data = if B::F32_VEC { binary_map_vec(lhs_l, rhs_l, lhs, rhs, B::f32, B::f32_vec) } else { binary_map(lhs_l, rhs_l, lhs, rhs, B::f32) }; Ok(Self::F32(data)) } (Self::F64(lhs), Self::F64(rhs)) => { let data = if B::F64_VEC { binary_map_vec(lhs_l, rhs_l, lhs, rhs, B::f64, B::f64_vec) } else { binary_map(lhs_l, rhs_l, lhs, rhs, B::f64) }; Ok(Self::F64(data)) } (Self::U32(lhs), Self::U32(rhs)) => { let data = if B::U32_VEC { binary_map_vec(lhs_l, rhs_l, lhs, rhs, B::u32, B::u32_vec) } else { binary_map(lhs_l, rhs_l, lhs, rhs, B::u32) }; Ok(Self::U32(data)) } (Self::I64(lhs), Self::I64(rhs)) => { let data = if B::I64_VEC { binary_map_vec(lhs_l, rhs_l, lhs, rhs, B::i64, B::i64_vec) } else { binary_map(lhs_l, rhs_l, lhs, rhs, B::i64) }; Ok(Self::I64(data)) } (Self::U8(lhs), Self::U8(rhs)) => { let data = if B::U8_VEC { binary_map_vec(lhs_l, rhs_l, lhs, rhs, B::u8, B::u8_vec) } else { binary_map(lhs_l, rhs_l, lhs, rhs, B::u8) }; Ok(Self::U8(data)) } _ => { // This should be covered by the dtype check above. Err(Error::DTypeMismatchBinaryOp { lhs: self.dtype(), rhs: rhs.dtype(), op: B::NAME, } .bt()) } } } fn copy2d( &self, dst: &mut Self, d1: usize, d2: usize, src_s: usize, dst_s: usize, src_o: usize, dst_o: usize, ) -> Result<()> { match (self, dst) { (Self::U8(src), Self::U8(dst)) => copy2d_(src, dst, d1, d2, src_s, dst_s, src_o, dst_o), (Self::U32(src), Self::U32(dst)) => { copy2d_(src, dst, d1, d2, src_s, dst_s, src_o, dst_o) } (Self::I64(src), Self::I64(dst)) => { copy2d_(src, dst, d1, d2, src_s, dst_s, src_o, dst_o) } (Self::BF16(src), Self::BF16(dst)) => { copy2d_(src, dst, d1, d2, src_s, dst_s, src_o, dst_o) } (Self::F16(src), Self::F16(dst)) => { copy2d_(src, dst, d1, d2, src_s, dst_s, src_o, dst_o) } (Self::F32(src), Self::F32(dst)) => { copy2d_(src, dst, d1, d2, src_s, dst_s, src_o, dst_o) } (Self::F64(src), Self::F64(dst)) => { copy2d_(src, dst, d1, d2, src_s, dst_s, src_o, dst_o) } (_, dst) => { return Err(Error::DTypeMismatchBinaryOp { lhs: self.dtype(), rhs: dst.dtype(), op: "copy2d", } .bt()); } } Ok(()) } fn copy_strided_src(&self, dst: &mut Self, dst_offset: usize, src_l: &Layout) -> Result<()> { match (self, dst) { (Self::U8(src), Self::U8(dst)) => copy_strided_src_(src, dst, dst_offset, src_l), (Self::U32(src), Self::U32(dst)) => copy_strided_src_(src, dst, dst_offset, src_l), (Self::I64(src), Self::I64(dst)) => copy_strided_src_(src, dst, dst_offset, src_l), (Self::BF16(src), Self::BF16(dst)) => copy_strided_src_(src, dst, dst_offset, src_l), (Self::F16(src), Self::F16(dst)) => copy_strided_src_(src, dst, dst_offset, src_l), (Self::F32(src), Self::F32(dst)) => copy_strided_src_(src, dst, dst_offset, src_l), (Self::F64(src), Self::F64(dst)) => copy_strided_src_(src, dst, dst_offset, src_l), (_, dst) => { // This should be covered by the dtype check above. return Err(Error::DTypeMismatchBinaryOp { lhs: self.dtype(), rhs: dst.dtype(), op: "copy_strided", } .bt()); } } Ok(()) } fn where_cond( &self, layout: &Layout, t: &Self, t_l: &Layout, f: &Self, f_l: &Layout, ) -> Result<Self> { match self { Self::U8(pred) => WCond(pred, layout).map(t, t_l, f, f_l), Self::U32(pred) => WCond(pred, layout).map(t, t_l, f, f_l), Self::I64(pred) => WCond(pred, layout).map(t, t_l, f, f_l), _ => Err(Error::UnsupportedDTypeForOp(self.dtype(), "where-cond")), } } fn conv1d( &self, l: &Layout, kernel: &Self, kernel_l: &Layout, params: &crate::conv::ParamsConv1D, ) -> Result<Self> { if !USE_IM2COL_CONV1D { return Conv1D(params).map(self, l, kernel, kernel_l); } let op = Im2Col1D { l_k: params.k_size, padding: params.padding, stride: params.stride, dilation: params.dilation, }; let col = op.map(self, l)?; let b = params.b_size; let n = params.c_out; let l_out = params.l_out(); let k = op.l_k * params.c_in; let m = l_out; let col_l = Layout::contiguous((b, m, k)); let res = if kernel_l.is_contiguous() { let kernel_l = Layout::contiguous_with_offset((1, n, k), kernel_l.start_offset()) .transpose(1, 2)? .broadcast_as((b, k, n))?; col.matmul(kernel, (b, m, n, k), &col_l, &kernel_l)? } else { // Make the kernel contiguous if not already the case. let mut kernel_c = unsafe { self.device() .alloc_uninit(kernel_l.shape(), kernel.dtype())? }; kernel.copy_strided_src(&mut kernel_c, 0, kernel_l)?; let kernel_l = Layout::contiguous_with_offset((1, n, k), kernel_l.start_offset()) .transpose(1, 2)? .broadcast_as((b, k, n))?; col.matmul(kernel, (b, m, n, k), &col_l, &kernel_l)? }; let res_l = Layout::contiguous((b, l_out, params.c_out)).transpose(1, 2)?; let mut res_t = unsafe { self.device().alloc_uninit(res_l.shape(), res.dtype())? }; res.copy_strided_src(&mut res_t, 0, &res_l)?; Ok(res_t) } fn conv_transpose1d( &self, l: &Layout, kernel: &Self, kernel_l: &Layout, params: &crate::conv::ParamsConvTranspose1D, ) -> Result<Self> { let can_use_col2im = kernel_l.is_contiguous() && params.dilation == 1 && params.padding == 0 && params.output_padding == 0; if USE_COL2IM_CONV1D_TR && can_use_col2im { let (b_size, c_in, l_in) = l.shape().dims3()?; let (c_in2, c_out, k_size) = kernel_l.shape().dims3()?; if !kernel_l.is_contiguous() { crate::bail!( "convtr1d: the second argument (kernel) has to be contiguous {kernel_l:?}" ) } if c_in != c_in2 { crate::bail!( "convtr1d: shape mismatch on c_in {:?} {:?}", l.shape(), kernel_l.shape() ) } let col = { // This merges the last two dimensions of the kernel together. let kernel_l_mm = Layout::new( (b_size, c_in, k_size * c_out).into(), vec![0, k_size * c_out, 1], kernel_l.start_offset(), ); self.matmul( kernel, ( b_size, /* m */ l_in, /* n */ c_out * k_size, /* k */ c_in, ), &l.transpose(1, 2)?, &kernel_l_mm, )? }; let col_l = Layout::contiguous((b_size, l_in, c_out, k_size)); Col2Im1D { stride: params.stride, } .map(&col, &col_l) } else { ConvTranspose1D(params).map(self, l, kernel, kernel_l) } } fn conv2d( &self, l: &Layout, kernel: &Self, kernel_l: &Layout, params: &crate::conv::ParamsConv2D, ) -> Result<Self> { if !USE_IM2COL_CONV2D { return Conv2D(params).map(self, l, kernel, kernel_l); } let op = Im2Col { h_k: params.k_h, w_k: params.k_w, padding: params.padding, stride: params.stride, dilation: params.dilation, }; let col = op.map(self, l)?; let b = params.b_size; let n = params.c_out; let (h_out, w_out) = (params.out_h(), params.out_w()); let k = op.h_k * op.w_k * params.c_in; let m = h_out * w_out; let col_l = Layout::contiguous((b, m, k)); let res = if kernel_l.is_contiguous() { let kernel_l = Layout::contiguous_with_offset((1, n, k), kernel_l.start_offset()) .transpose(1, 2)? .broadcast_as((b, k, n))?; col.matmul(kernel, (b, m, n, k), &col_l, &kernel_l)? } else { // Make the kernel contiguous if not already the case. let mut kernel_c = unsafe { self.device() .alloc_uninit(kernel_l.shape(), kernel.dtype())? }; kernel.copy_strided_src(&mut kernel_c, 0, kernel_l)?; let kernel_l = Layout::contiguous_with_offset((1, n, k), kernel_l.start_offset()) .transpose(1, 2)? .broadcast_as((b, k, n))?; col.matmul(kernel, (b, m, n, k), &col_l, &kernel_l)? }; let res_l = Layout::contiguous((b, h_out, w_out, params.c_out)) .transpose(1, 2)? .transpose(1, 3)?; let mut res_t = unsafe { self.device().alloc_uninit(res_l.shape(), res.dtype())? }; res.copy_strided_src(&mut res_t, 0, &res_l)?; Ok(res_t) } fn conv_transpose2d( &self, l: &Layout, kernel: &Self, kernel_l: &Layout, params: &crate::conv::ParamsConvTranspose2D, ) -> Result<Self> { ConvTranspose2D(params).map(self, l, kernel, kernel_l) } fn index_select(&self, ids: &Self, l: &Layout, ids_l: &Layout, dim: usize) -> Result<Self> { match ids { Self::U8(ids) => IndexSelect { ids, ids_l, dim }.map(self, l), Self::U32(ids) => IndexSelect { ids, ids_l, dim }.map(self, l), Self::I64(ids) => IndexSelect { ids, ids_l, dim }.map(self, l), _ => Err(Error::UnsupportedDTypeForOp(self.dtype(), "index-select").bt()), } } fn gather(&self, l: &Layout, ids: &Self, ids_l: &Layout, dim: usize) -> Result<Self> { match ids { Self::U8(ids) => Gather { ids, ids_l, dim }.map(self, l), Self::U32(ids) => Gather { ids, ids_l, dim }.map(self, l), Self::I64(ids) => Gather { ids, ids_l, dim }.map(self, l), _ => Err(Error::UnsupportedDTypeForOp(self.dtype(), "gather").bt()), } } fn scatter_set( &mut self, l: &Layout, ids: &Self, ids_l: &Layout, src: &Self, src_l: &Layout, dim: usize, ) -> Result<()> { match ids { Self::U8(ids) => Scatter::<_, Set>::new(ids, ids_l, dim).map(self, l, src, src_l), Self::U32(ids) => Scatter::<_, Set>::new(ids, ids_l, dim).map(self, l, src, src_l), Self::I64(ids) => Scatter::<_, Set>::new(ids, ids_l, dim).map(self, l, src, src_l), _ => Err(Error::UnsupportedDTypeForOp(self.dtype(), "scatter").bt()), } } fn scatter_add_set( &mut self, l: &Layout, ids: &Self, ids_l: &Layout, src: &Self, src_l: &Layout, dim: usize, ) -> Result<()> { match ids { Self::U8(ids) => Scatter::<_, Add>::new(ids, ids_l, dim).map(self, l, src, src_l), Self::U32(ids) => Scatter::<_, Add>::new(ids, ids_l, dim).map(self, l, src, src_l), Self::I64(ids) => Scatter::<_, Add>::new(ids, ids_l, dim).map(self, l, src, src_l), _ => Err(Error::UnsupportedDTypeForOp(self.dtype(), "scatter-add").bt()), } } fn index_add( &self, l: &Layout, ids: &Self, ids_l: &Layout, src: &Self, src_l: &Layout, dim: usize, ) -> Result<Self> { match ids { Self::U8(ids) => { let ids = match ids_l.contiguous_offsets() { Some((a, b)) => &ids[a..b], None => Err(Error::RequiresContiguous { op: "index-add" }.bt())?, }; IndexAdd { ids, dim }.map(self, l, src, src_l) } Self::U32(ids) => { let ids = match ids_l.contiguous_offsets() { Some((a, b)) => &ids[a..b], None => Err(Error::RequiresContiguous { op: "index-add" }.bt())?, }; IndexAdd { ids, dim }.map(self, l, src, src_l) } Self::I64(ids) => { let ids = match ids_l.contiguous_offsets() { Some((a, b)) => &ids[a..b], None => Err(Error::RequiresContiguous { op: "index-add" }.bt())?, }; IndexAdd { ids, dim }.map(self, l, src, src_l) } _ => Err(Error::UnsupportedDTypeForOp(self.dtype(), "index-add").bt()), } } fn matmul( &self, rhs: &Self, bmnk: (usize, usize, usize, usize), lhs_l: &Layout, rhs_l: &Layout, ) -> Result<Self> { MatMul(bmnk).map(self, lhs_l, rhs, rhs_l) } fn device(&self) -> &Self::Device { &CpuDevice } fn try_clone(&self, _: &Layout) -> Result<Self> { Ok(self.clone()) } fn to_cpu_storage(&self) -> Result<CpuStorage> { Ok(self.clone()) } fn const_set(&mut self, s: crate::scalar::Scalar, l: &Layout) -> Result<()> { use crate::scalar::Scalar; fn set<T: crate::WithDType>(src: &mut [T], l: &Layout, s: T) { match l.strided_blocks() { crate::StridedBlocks::SingleBlock { start_offset, len } => { src[start_offset..start_offset + len].fill(s) } crate::StridedBlocks::MultipleBlocks { block_start_index, block_len: 1, } => { for src_index in block_start_index { src[src_index] = s } } crate::StridedBlocks::MultipleBlocks { block_start_index, block_len, } => { for src_index in block_start_index { src[src_index..src_index + block_len].fill(s) } } } } match (self, s) { (Self::BF16(storage), Scalar::BF16(v)) => set(storage, l, v), (Self::F16(storage), Scalar::F16(v)) => set(storage, l, v), (Self::F32(storage), Scalar::F32(v)) => set(storage, l, v), (Self::F64(storage), Scalar::F64(v)) => set(storage, l, v), (Self::U8(storage), Scalar::U8(v)) => set(storage, l, v), (Self::U32(storage), Scalar::U32(v)) => set(storage, l, v), (Self::I64(storage), Scalar::I64(v)) => set(storage, l, v), (Self::F8E4M3(storage), Scalar::F8E4M3(v)) => set(storage, l, v), (st, s) => crate::bail!( "const_set dtype mismatch, expected {:?} but got {:?}", st.dtype(), s ), } Ok(()) } } impl BackendDevice for CpuDevice { type Storage = CpuStorage; fn location(&self) -> crate::DeviceLocation { crate::DeviceLocation::Cpu } fn same_device(&self, _: &Self) -> bool { true } fn storage_from_slice<T: crate::WithDType>(&self, s: &[T]) -> Result<Self::Storage> { Ok(T::to_cpu_storage(s)) } fn storage_from_cpu_storage(&self, s: &CpuStorage) -> Result<Self::Storage> { Ok(s.clone()) } fn storage_from_cpu_storage_owned(&self, s: CpuStorage) -> Result<Self::Storage> { Ok(s) } fn new(_: usize) -> Result<Self> { Ok(Self) } fn set_seed(&self, _seed: u64) -> Result<()> { crate::bail!("cannot seed the CPU rng with set_seed") } fn rand_uniform(&self, shape: &Shape, dtype: DType, min: f64, max: f64) -> Result<CpuStorage> { use rand::prelude::*; let elem_count = shape.elem_count(); let mut rng = rand::rng(); match dtype { DType::U8 | DType::U32 | DType::I64 => { Err(Error::UnsupportedDTypeForOp(dtype, "rand_uniform").bt()) } DType::BF16 => { let mut data = Vec::with_capacity(elem_count); let uniform = rand::distr::Uniform::new(bf16::from_f64(min), bf16::from_f64(max)) .map_err(Error::wrap)?; for _i in 0..elem_count { data.push(rng.sample::<bf16, _>(uniform)) } Ok(CpuStorage::BF16(data)) } DType::F16 => { let mut data = Vec::with_capacity(elem_count); let uniform = rand::distr::Uniform::new(f16::from_f64(min), f16::from_f64(max)) .map_err(Error::wrap)?; for _i in 0..elem_count { data.push(rng.sample::<f16, _>(uniform)) } Ok(CpuStorage::F16(data)) } DType::F8E4M3 => { let mut data = Vec::with_capacity(elem_count); let uniform = rand::distr::Uniform::new(F8E4M3::from_f64(min), F8E4M3::from_f64(max)) .map_err(Error::wrap)?; for _i in 0..elem_count { data.push(rng.sample::<F8E4M3, _>(uniform)) } Ok(CpuStorage::F8E4M3(data)) } DType::F32 => { let mut data = Vec::with_capacity(elem_count); let uniform = rand::distr::Uniform::new(min as f32, max as f32).map_err(Error::wrap)?; for _i in 0..elem_count { data.push(rng.sample::<f32, _>(uniform)) } Ok(CpuStorage::F32(data)) } DType::F64 => { let mut data = Vec::with_capacity(elem_count); let uniform = rand::distr::Uniform::new(min, max).map_err(Error::wrap)?; for _i in 0..elem_count { data.push(rng.sample::<f64, _>(uniform)) } Ok(CpuStorage::F64(data)) } } } fn rand_normal(&self, shape: &Shape, dtype: DType, mean: f64, std: f64) -> Result<CpuStorage> { use rand::prelude::*; let elem_count = shape.elem_count(); let mut rng = rand::rng(); match dtype { DType::U8 | DType::U32 | DType::I64 => { Err(Error::UnsupportedDTypeForOp(dtype, "rand_normal").bt()) } DType::BF16 => { let mut data = Vec::with_capacity(elem_count); let normal = rand_distr::Normal::new(bf16::from_f64(mean), bf16::from_f64(std)) .map_err(Error::wrap)?; for _i in 0..elem_count { data.push(normal.sample(&mut rng)) } Ok(CpuStorage::BF16(data)) } DType::F16 => { let mut data = Vec::with_capacity(elem_count); let normal = rand_distr::Normal::new(f16::from_f64(mean), f16::from_f64(std)) .map_err(Error::wrap)?; for _i in 0..elem_count { data.push(normal.sample(&mut rng)) } Ok(CpuStorage::F16(data)) } DType::F8E4M3 => { let mut data = Vec::with_capacity(elem_count); let normal = rand_distr::Normal::new(F8E4M3::from_f64(mean), F8E4M3::from_f64(std)) .map_err(Error::wrap)?; for _i in 0..elem_count { data.push(normal.sample(&mut rng)) } Ok(CpuStorage::F8E4M3(data)) } DType::F32 => { let mut data = Vec::with_capacity(elem_count); let normal = rand_distr::Normal::new(mean as f32, std as f32).map_err(Error::wrap)?; for _i in 0..elem_count { data.push(normal.sample(&mut rng)) } Ok(CpuStorage::F32(data)) } DType::F64 => { let mut data = Vec::with_capacity(elem_count); let normal = rand_distr::Normal::new(mean, std).map_err(Error::wrap)?; for _i in 0..elem_count { data.push(normal.sample(&mut rng)) } Ok(CpuStorage::F64(data)) } } } #[allow(clippy::uninit_vec)] unsafe fn alloc_uninit(&self, shape: &Shape, dtype: DType) -> Result<CpuStorage> { let elem_count = shape.elem_count(); // The code below is highly unsafe but hopefully not directly unsound as we only consider // types that are Copy, not Drop, and for which all bit patterns are proper values. // It's still pretty risky, see the following for more details: // https://github.com/rust-lang/rust-clippy/issues/4483 let storage = match dtype { DType::U8 => { let mut v = Vec::with_capacity(elem_count); v.set_len(elem_count); CpuStorage::U8(v) } DType::U32 => { let mut v = Vec::with_capacity(elem_count); v.set_len(elem_count); CpuStorage::U32(v) } DType::I64 => { let mut v = Vec::with_capacity(elem_count); v.set_len(elem_count); CpuStorage::I64(v) } DType::BF16 => { let mut v = Vec::with_capacity(elem_count); v.set_len(elem_count); CpuStorage::BF16(v) } DType::F16 => { let mut v = Vec::with_capacity(elem_count); v.set_len(elem_count); CpuStorage::F16(v) } DType::F32 => { let mut v = Vec::with_capacity(elem_count); v.set_len(elem_count); CpuStorage::F32(v) } DType::F64 => { let mut v = Vec::with_capacity(elem_count); v.set_len(elem_count); CpuStorage::F64(v) } DType::F8E4M3 => { let mut v = Vec::with_capacity(elem_count); v.set_len(elem_count); CpuStorage::F8E4M3(v) } }; Ok(storage) } fn zeros_impl(&self, shape: &Shape, dtype: DType) -> Result<CpuStorage> { let elem_count = shape.elem_count(); let storage = match dtype { DType::U8 => CpuStorage::U8(vec![0u8; elem_count]), DType::U32 => CpuStorage::U32(vec![0u32; elem_count]), DType::I64 => CpuStorage::I64(vec![0i64; elem_count]), DType::BF16 => CpuStorage::BF16(vec![bf16::ZERO; elem_count]), DType::F16 => CpuStorage::F16(vec![f16::ZERO; elem_count]), DType::F8E4M3 => CpuStorage::F8E4M3(vec![F8E4M3::ZERO; elem_count]), DType::F32 => CpuStorage::F32(vec![0f32; elem_count]), DType::F64 => CpuStorage::F64(vec![0f64; elem_count]), }; Ok(storage) } fn synchronize(&self) -> Result<()> { Ok(()) } } #[macro_export] macro_rules! map_dtype { ($name:expr, $storage:ident, $fn:expr, ($($dtypes:ident),+)) => { match $storage { $(CpuStorage::$dtypes(__e) => CpuStorage::$dtypes($fn(__e)),)* s => Err(Error::UnsupportedDTypeForOp(s.dtype(), $name).bt())?, } }; }
candle/candle-core/src/cpu_backend/mod.rs/0
{ "file_path": "candle/candle-core/src/cpu_backend/mod.rs", "repo_id": "candle", "token_count": 69775 }
28
//! ML framework for Rust //! //! ```rust //! use candle_core::{Tensor, DType, Device}; //! # use candle_core::Error; //! # fn main() -> Result<(), Error>{ //! //! let a = Tensor::arange(0f32, 6f32, &Device::Cpu)?.reshape((2, 3))?; //! let b = Tensor::arange(0f32, 12f32, &Device::Cpu)?.reshape((3, 4))?; //! let c = a.matmul(&b)?; //! //! # Ok(())} //! ``` //! //! ## Features //! //! - Simple syntax (looks and feels like PyTorch) //! - CPU and Cuda backends (and M1 support) //! - Enable serverless (CPU) small and fast deployments //! - Model training //! - Distributed computing (NCCL). //! - Models out of the box (Llama, Whisper, Falcon, ...) //! //! ## FAQ //! //! - Why Candle? //! //! Candle stems from the need to reduce binary size in order to *enable serverless* //! possible by making the whole engine smaller than PyTorch very large library volume //! //! And simply *removing Python* from production workloads. //! Python can really add overhead in more complex workflows and the [GIL](https://www.backblaze.com/blog/the-python-gil-past-present-and-future/) is a notorious source of headaches. //! //! Rust is cool, and a lot of the HF ecosystem already has Rust crates [safetensors](https://github.com/huggingface/safetensors) and [tokenizers](https://github.com/huggingface/tokenizers) //! //! ## Other Crates //! //! Candle consists of a number of crates. This crate holds core the common data structures but you may wish //! to look at the docs for the other crates which can be found here: //! //! - [candle-core](https://docs.rs/candle-core/). Core Datastructures and DataTypes. //! - [candle-nn](https://docs.rs/candle-nn/). Building blocks for Neural Nets. //! - [candle-datasets](https://docs.rs/candle-datasets/). Rust access to commonly used Datasets like MNIST. //! - [candle-examples](https://docs.rs/candle-examples/). Examples of Candle in Use. //! - [candle-onnx](https://docs.rs/candle-onnx/). Loading and using ONNX models. //! - [candle-pyo3](https://docs.rs/candle-pyo3/). Access to Candle from Python. //! - [candle-transformers](https://docs.rs/candle-transformers/). Candle implemntation of many published transformer models. //! #[cfg(feature = "accelerate")] mod accelerate; pub mod backend; pub mod backprop; pub mod conv; mod convert; pub mod cpu; pub mod cpu_backend; #[cfg(feature = "cuda")] pub mod cuda_backend; mod custom_op; mod device; pub mod display; mod dtype; pub mod dummy_cuda_backend; mod dummy_metal_backend; pub mod error; mod indexer; pub mod layout; #[cfg(feature = "metal")] pub mod metal_backend; #[cfg(feature = "mkl")] mod mkl; pub mod npy; pub mod op; pub mod pickle; pub mod quantized; pub mod safetensors; pub mod scalar; pub mod shape; mod sort; mod storage; pub mod streaming; mod strided_index; mod tensor; mod tensor_cat; pub mod test_utils; pub mod utils; mod variable; #[cfg(feature = "cudnn")] pub use cuda_backend::cudnn; pub use cpu_backend::{CpuStorage, CpuStorageRef}; pub use custom_op::{CustomOp1, CustomOp2, CustomOp3, InplaceOp1, InplaceOp2, InplaceOp3, UgIOp1}; pub use device::{Device, DeviceLocation, NdArray}; pub use dtype::{DType, DTypeParseError, FloatDType, IntDType, WithDType}; pub use error::{Context, Error, Result}; pub use indexer::{IndexOp, TensorIndexer}; pub use layout::Layout; pub use shape::{Shape, D}; pub use storage::Storage; pub use streaming::{StreamTensor, StreamingBinOp, StreamingModule}; pub use strided_index::{StridedBlocks, StridedIndex}; pub use tensor::{Tensor, TensorId}; pub use variable::Var; #[cfg(feature = "cuda")] pub use cuda_backend as cuda; #[cfg(not(feature = "cuda"))] pub use dummy_cuda_backend as cuda; pub use cuda::{CudaDevice, CudaStorage}; #[cfg(feature = "metal")] pub use metal_backend::{MetalDevice, MetalError, MetalStorage}; #[cfg(not(feature = "metal"))] pub use dummy_metal_backend::{MetalDevice, MetalError, MetalStorage}; #[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; pub trait ToUsize2 { fn to_usize2(self) -> (usize, usize); } impl ToUsize2 for usize { fn to_usize2(self) -> (usize, usize) { (self, self) } } impl ToUsize2 for (usize, usize) { fn to_usize2(self) -> (usize, usize) { self } } /// Defining a module with forward method using a single argument. pub trait Module { fn forward(&self, xs: &Tensor) -> Result<Tensor>; } impl<T: Fn(&Tensor) -> Result<Tensor>> Module for T { fn forward(&self, xs: &Tensor) -> Result<Tensor> { self(xs) } } impl<M: Module> Module for Option<&M> { fn forward(&self, xs: &Tensor) -> Result<Tensor> { match self { None => Ok(xs.clone()), Some(m) => m.forward(xs), } } } /// A single forward method using a single single tensor argument and a flag to /// separate the training and evaluation behaviors. pub trait ModuleT { fn forward_t(&self, xs: &Tensor, train: bool) -> Result<Tensor>; } impl<M: Module> ModuleT for M { fn forward_t(&self, xs: &Tensor, _train: bool) -> Result<Tensor> { self.forward(xs) } }
candle/candle-core/src/lib.rs/0
{ "file_path": "candle/candle-core/src/lib.rs", "repo_id": "candle", "token_count": 1894 }
29
use super::k_quants::{ BlockQ2K, BlockQ3K, BlockQ4K, BlockQ4_0, BlockQ5K, BlockQ6K, BlockQ8K, BlockQ8_0, QK8_0, QK_K, }; use crate::Result; use byteorder::{ByteOrder, LittleEndian}; #[allow(unused_imports)] #[cfg(target_arch = "arm")] use core::arch::arm::*; #[allow(unused_imports)] #[cfg(target_arch = "aarch64")] use core::arch::aarch64::*; #[inline(always)] unsafe fn vdotq_s32(a: int8x16_t, b: int8x16_t) -> int32x4_t { // TODO: dotprod let p0 = vmull_s8(vget_low_s8(a), vget_low_s8(b)); let p1 = vmull_s8(vget_high_s8(a), vget_high_s8(b)); vaddq_s32(vpaddlq_s16(p0), vpaddlq_s16(p1)) } #[inline(always)] pub(crate) fn vec_dot_q4_0_q8_0(n: usize, xs: &[BlockQ4_0], ys: &[BlockQ8_0]) -> Result<f32> { let qk = QK8_0; let nb = n / qk; if n % QK8_0 != 0 { crate::bail!("vec_dot_q4_0_q8_0: {n} is not divisible by {qk}") } unsafe { let mut sumv0 = vdupq_n_f32(0.0f32); for i in 0..nb { let x0 = &xs[i]; let y0 = &ys[i]; let m4b = vdupq_n_u8(0x0F); let s8b = vdupq_n_s8(0x8); let v0_0 = vld1q_u8(x0.qs.as_ptr()); // 4-bit -> 8-bit let v0_0l = vreinterpretq_s8_u8(vandq_u8(v0_0, m4b)); let v0_0h = vreinterpretq_s8_u8(vshrq_n_u8(v0_0, 4)); // sub 8 let v0_0ls = vsubq_s8(v0_0l, s8b); let v0_0hs = vsubq_s8(v0_0h, s8b); // load y let v1_0l = vld1q_s8(y0.qs.as_ptr()); let v1_0h = vld1q_s8(y0.qs.as_ptr().add(16)); let pl0 = vdotq_s32(v0_0ls, v1_0l); let ph0 = vdotq_s32(v0_0hs, v1_0h); sumv0 = vmlaq_n_f32( sumv0, vcvtq_f32_s32(vaddq_s32(pl0, ph0)), x0.d.to_f32() * y0.d.to_f32(), ); } Ok(vaddvq_f32(sumv0)) } } #[inline(always)] pub(crate) fn vec_dot_q8_0_q8_0(n: usize, xs: &[BlockQ8_0], ys: &[BlockQ8_0]) -> Result<f32> { let qk = QK8_0; if n % QK8_0 != 0 { crate::bail!("vec_dot_q8_0_q8_0: {n} is not divisible by {qk}") } let nb = n / QK8_0; unsafe { let mut sumv0 = vdupq_n_f32(0.0f32); for i in 0..nb { let x0 = &xs[i]; let y0 = &ys[i]; let x0_0 = vld1q_s8(x0.qs.as_ptr()); let x0_1 = vld1q_s8(x0.qs.as_ptr().add(16)); // load y let y0_0 = vld1q_s8(y0.qs.as_ptr()); let y0_1 = vld1q_s8(y0.qs.as_ptr().add(16)); let p0 = vdotq_s32(x0_0, y0_0); let p1 = vdotq_s32(x0_1, y0_1); sumv0 = vmlaq_n_f32( sumv0, vcvtq_f32_s32(vaddq_s32(p0, p1)), x0.d.to_f32() * y0.d.to_f32(), ); } Ok(vaddvq_f32(sumv0)) } } #[inline(always)] pub(crate) fn vec_dot_q8k_q8k(n: usize, xs: &[BlockQ8K], ys: &[BlockQ8K]) -> Result<f32> { let qk = QK_K; if n % QK_K != 0 { crate::bail!("vec_dot_q8k_q8k: {n} is not divisible by {qk}") } let mut sumf = 0f32; for (xs, ys) in xs.iter().zip(ys.iter()) { unsafe { let mut sum_i = vdupq_n_s32(0); let scale = xs.d * ys.d; let xs = xs.qs.as_ptr(); let ys = ys.qs.as_ptr(); for i in (0..QK_K).step_by(16) { let xs = vld1q_s8(xs.add(i)); let ys = vld1q_s8(ys.add(i)); let xy = vdotq_s32(xs, ys); sum_i = vaddq_s32(sum_i, xy) } sumf += vaddvq_s32(sum_i) as f32 * scale } } Ok(sumf) } #[inline(always)] pub(crate) fn vec_dot_q6k_q8k(n: usize, xs: &[BlockQ6K], ys: &[BlockQ8K]) -> Result<f32> { if n % QK_K != 0 { crate::bail!("vec_dot_q6k_q8k: {n} is not divisible by {QK_K}") } let mut sum = 0f32; unsafe { let m4b = vdupq_n_u8(0xF); let mone = vdupq_n_u8(3); for (x, y) in xs.iter().zip(ys.iter()) { let d_all = x.d.to_f32(); let mut q6 = x.ql.as_ptr(); let mut qh = x.qh.as_ptr(); let mut q8 = y.qs.as_ptr(); let mut scale = x.scales.as_ptr(); let q8sums = vld1q_s16_x2(y.bsums.as_ptr()); let scales = vld1q_s8(scale); let q6scales = int16x8x2_t( vmovl_s8(vget_low_s8(scales)), vmovl_s8(vget_high_s8(scales)), ); let prod = vaddq_s32( vaddq_s32( vmull_s16(vget_low_s16(q8sums.0), vget_low_s16(q6scales.0)), vmull_s16(vget_high_s16(q8sums.0), vget_high_s16(q6scales.0)), ), vaddq_s32( vmull_s16(vget_low_s16(q8sums.1), vget_low_s16(q6scales.1)), vmull_s16(vget_high_s16(q8sums.1), vget_high_s16(q6scales.1)), ), ); let isum_mins = vaddvq_s32(prod); let mut isum = 0i32; for _j in 0..QK_K / 128 { let qhbits = vld1q_u8_x2(qh); qh = qh.add(32); let q6bits = vld1q_u8_x4(q6); q6 = q6.add(64); let q8bytes = vld1q_s8_x4(q8); q8 = q8.add(64); let q6h_0 = vshlq_n_u8(vandq_u8(mone, qhbits.0), 4); let q6h_1 = vshlq_n_u8(vandq_u8(mone, qhbits.1), 4); let shifted = vshrq_n_u8(qhbits.0, 2); let q6h_2 = vshlq_n_u8(vandq_u8(mone, shifted), 4); let shifted = vshrq_n_u8(qhbits.1, 2); let q6h_3 = vshlq_n_u8(vandq_u8(mone, shifted), 4); let q6bytes_0 = vreinterpretq_s8_u8(vorrq_u8(vandq_u8(q6bits.0, m4b), q6h_0)); let q6bytes_1 = vreinterpretq_s8_u8(vorrq_u8(vandq_u8(q6bits.1, m4b), q6h_1)); let q6bytes_2 = vreinterpretq_s8_u8(vorrq_u8(vandq_u8(q6bits.2, m4b), q6h_2)); let q6bytes_3 = vreinterpretq_s8_u8(vorrq_u8(vandq_u8(q6bits.3, m4b), q6h_3)); let p0 = vdotq_s32(q6bytes_0, q8bytes.0); let p1 = vdotq_s32(q6bytes_1, q8bytes.1); let (scale0, scale1) = (*scale as i32, *scale.add(1) as i32); isum += vaddvq_s32(p0) * scale0 + vaddvq_s32(p1) * scale1; scale = scale.add(2); let p2 = vdotq_s32(q6bytes_2, q8bytes.2); let p3 = vdotq_s32(q6bytes_3, q8bytes.3); let (scale0, scale1) = (*scale as i32, *scale.add(1) as i32); isum += vaddvq_s32(p2) * scale0 + vaddvq_s32(p3) * scale1; scale = scale.add(2); let q8bytes = vld1q_s8_x4(q8); q8 = q8.add(64); let shifted = vshrq_n_u8(qhbits.0, 4); let q6h_0 = vshlq_n_u8(vandq_u8(mone, shifted), 4); let shifted = vshrq_n_u8(qhbits.1, 4); let q6h_1 = vshlq_n_u8(vandq_u8(mone, shifted), 4); let shifted = vshrq_n_u8(qhbits.0, 6); let q6h_2 = vshlq_n_u8(vandq_u8(mone, shifted), 4); let shifted = vshrq_n_u8(qhbits.1, 6); let q6h_3 = vshlq_n_u8(vandq_u8(mone, shifted), 4); let q6bytes_0 = vreinterpretq_s8_u8(vorrq_u8(vshrq_n_u8(q6bits.0, 4), q6h_0)); let q6bytes_1 = vreinterpretq_s8_u8(vorrq_u8(vshrq_n_u8(q6bits.1, 4), q6h_1)); let q6bytes_2 = vreinterpretq_s8_u8(vorrq_u8(vshrq_n_u8(q6bits.2, 4), q6h_2)); let q6bytes_3 = vreinterpretq_s8_u8(vorrq_u8(vshrq_n_u8(q6bits.3, 4), q6h_3)); let p0 = vdotq_s32(q6bytes_0, q8bytes.0); let p1 = vdotq_s32(q6bytes_1, q8bytes.1); let (scale0, scale1) = (*scale as i32, *scale.add(1) as i32); isum += vaddvq_s32(p0) * scale0 + vaddvq_s32(p1) * scale1; scale = scale.add(2); let p2 = vdotq_s32(q6bytes_2, q8bytes.2); let p3 = vdotq_s32(q6bytes_3, q8bytes.3); let (scale0, scale1) = (*scale as i32, *scale.add(1) as i32); isum += vaddvq_s32(p2) * scale0 + vaddvq_s32(p3) * scale1; scale = scale.add(2); } sum += d_all * y.d * ((isum - 32 * isum_mins) as f32); } } Ok(sum) } #[inline(always)] pub(crate) fn vec_dot_q5k_q8k(n: usize, xs: &[BlockQ5K], ys: &[BlockQ8K]) -> Result<f32> { if n % QK_K != 0 { crate::bail!("vec_dot_q5k_q8k: {n} is not divisible by {QK_K}") } let mut sumf = 0f32; let mut utmp = [0u32; 4]; const KMASK1: u32 = 0x3f3f3f3f; const KMASK2: u32 = 0x0f0f0f0f; const KMASK3: u32 = 0x03030303; unsafe { let m4b = vdupq_n_u8(0xF); let mone = vdupq_n_u8(1); let mtwo = vdupq_n_u8(2); for (x, y) in xs.iter().zip(ys.iter()) { let d = y.d * x.d.to_f32(); let dmin = y.d * x.dmin.to_f32(); let q8sums = vpaddq_s16( vld1q_s16(y.bsums.as_ptr()), vld1q_s16(y.bsums.as_ptr().add(8)), ); LittleEndian::read_u32_into(&x.scales, &mut utmp[0..3]); utmp[3] = ((utmp[2] >> 4) & KMASK2) | (((utmp[1] >> 6) & KMASK3) << 4); let uaux = utmp[1] & KMASK1; utmp[1] = (utmp[2] & KMASK2) | (((utmp[0] >> 6) & KMASK3) << 4); utmp[2] = uaux; utmp[0] &= KMASK1; let mins8 = vld1_u8((utmp.as_ptr() as *const u8).add(8)); let mins = vreinterpretq_s16_u16(vmovl_u8(mins8)); let prod = vaddq_s32( vmull_s16(vget_low_s16(q8sums), vget_low_s16(mins)), vmull_s16(vget_high_s16(q8sums), vget_high_s16(mins)), ); let sumi_mins = vaddvq_s32(prod); let mut scales = utmp.as_ptr() as *const u8; let mut q5 = x.qs.as_ptr(); let mut q8 = y.qs.as_ptr(); let mut qhbits = vld1q_u8_x2(x.qh.as_ptr()); let mut sumi = 0i32; for _j in 0..QK_K / 64 { let q5bits = vld1q_u8_x2(q5); q5 = q5.add(32); let q8bytes = vld1q_s8_x4(q8); q8 = q8.add(64); let q5h_0 = vshlq_n_u8(vandq_u8(mone, qhbits.0), 4); let q5h_1 = vshlq_n_u8(vandq_u8(mone, qhbits.1), 4); let q5h_2 = vshlq_n_u8(vandq_u8(mtwo, qhbits.0), 3); let q5h_3 = vshlq_n_u8(vandq_u8(mtwo, qhbits.1), 3); qhbits.0 = vshrq_n_u8(qhbits.0, 2); qhbits.1 = vshrq_n_u8(qhbits.1, 2); let q5bytes_0 = vreinterpretq_s8_u8(vorrq_u8(vandq_u8(q5bits.0, m4b), q5h_0)); let q5bytes_1 = vreinterpretq_s8_u8(vorrq_u8(vandq_u8(q5bits.1, m4b), q5h_1)); let q5bytes_2 = vreinterpretq_s8_u8(vorrq_u8(vshrq_n_u8(q5bits.0, 4), q5h_2)); let q5bytes_3 = vreinterpretq_s8_u8(vorrq_u8(vshrq_n_u8(q5bits.1, 4), q5h_3)); let p0 = vdotq_s32(q5bytes_0, q8bytes.0); let p1 = vdotq_s32(q5bytes_1, q8bytes.1); sumi += vaddvq_s32(vaddq_s32(p0, p1)) * *scales as i32; scales = scales.add(1); let p2 = vdotq_s32(q5bytes_2, q8bytes.2); let p3 = vdotq_s32(q5bytes_3, q8bytes.3); sumi += vaddvq_s32(vaddq_s32(p2, p3)) * *scales as i32; scales = scales.add(1); } sumf += d * sumi as f32 - dmin * sumi_mins as f32; } } Ok(sumf) } #[inline(always)] pub(crate) fn vec_dot_q4k_q8k(n: usize, xs: &[BlockQ4K], ys: &[BlockQ8K]) -> Result<f32> { if n % QK_K != 0 { crate::bail!("vec_dot_q4k_q8k: {n} is not divisible by {QK_K}") } let mut sumf = 0f32; let mut utmp = [0u32; 4]; let mut scales = [0u8; 16]; const KMASK1: u32 = 0x3f3f3f3f; const KMASK2: u32 = 0x0f0f0f0f; const KMASK3: u32 = 0x03030303; unsafe { let m4b = vdupq_n_u8(0xF); for (x, y) in xs.iter().zip(ys.iter()) { let d = y.d * x.d.to_f32(); let dmin = y.d * x.dmin.to_f32(); let q8sums = vpaddq_s16( vld1q_s16(y.bsums.as_ptr()), vld1q_s16(y.bsums.as_ptr().add(8)), ); LittleEndian::read_u32_into(&x.scales, &mut utmp[0..3]); let mins8 = vld1_u32( [ utmp[1] & KMASK1, ((utmp[2] >> 4) & KMASK2) | (((utmp[1] >> 6) & KMASK3) << 4), ] .as_ptr(), ); utmp[1] = (utmp[2] & KMASK2) | (((utmp[0] >> 6) & KMASK3) << 4); utmp[0] &= KMASK1; let mins = vreinterpretq_s16_u16(vmovl_u8(vreinterpret_u8_u32(mins8))); let prod = vaddq_s32( vmull_s16(vget_low_s16(q8sums), vget_low_s16(mins)), vmull_s16(vget_high_s16(q8sums), vget_high_s16(mins)), ); sumf -= dmin * vaddvq_s32(prod) as f32; LittleEndian::write_u32_into(&utmp, &mut scales); let mut q4 = x.qs.as_ptr(); let mut q8 = y.qs.as_ptr(); let mut sumi1 = 0i32; let mut sumi2 = 0i32; for j in 0..QK_K / 64 { let q4bits = vld1q_u8_x2(q4); q4 = q4.add(32); let q8bytes = vld1q_s8_x2(q8); q8 = q8.add(32); let q4bytes = int8x16x2_t( vreinterpretq_s8_u8(vandq_u8(q4bits.0, m4b)), vreinterpretq_s8_u8(vandq_u8(q4bits.1, m4b)), ); let p0 = vdotq_s32(q4bytes.0, q8bytes.0); let p1 = vdotq_s32(q4bytes.1, q8bytes.1); sumi1 += vaddvq_s32(vaddq_s32(p0, p1)) * scales[2 * j] as i32; let q8bytes = vld1q_s8_x2(q8); q8 = q8.add(32); let q4bytes = int8x16x2_t( vreinterpretq_s8_u8(vshrq_n_u8(q4bits.0, 4)), vreinterpretq_s8_u8(vshrq_n_u8(q4bits.1, 4)), ); let p2 = vdotq_s32(q4bytes.0, q8bytes.0); let p3 = vdotq_s32(q4bytes.1, q8bytes.1); sumi2 += vaddvq_s32(vaddq_s32(p2, p3)) * scales[2 * j + 1] as i32; } sumf += d * (sumi1 + sumi2) as f32; } } Ok(sumf) } #[inline(always)] pub(crate) fn vec_dot_q3k_q8k(n: usize, xs: &[BlockQ3K], ys: &[BlockQ8K]) -> Result<f32> { if n % QK_K != 0 { crate::bail!("vec_dot_q3k_q8k: {n} is not divisible by {QK_K}") } let mut sumf = 0f32; let mut utmp = [0u32; 4]; let mut aux = [0u32; 3]; const KMASK1: u32 = 0x03030303; const KMASK2: u32 = 0x0f0f0f0f; unsafe { let m3b = vdupq_n_u8(0x3); let m0 = vdupq_n_u8(1); let m1 = vshlq_n_u8(m0, 1); let m2 = vshlq_n_u8(m0, 2); let m3 = vshlq_n_u8(m0, 3); for (x, y) in xs.iter().zip(ys.iter()) { let d = y.d * x.d.to_f32(); let mut q3 = x.qs.as_ptr(); let qh = x.hmask.as_ptr(); let mut q8 = y.qs.as_ptr(); let mut qhbits = vld1q_u8_x2(qh); let mut isum = 0i32; // Set up scales LittleEndian::read_u32_into(&x.scales, &mut aux); utmp[3] = ((aux[1] >> 4) & KMASK2) | (((aux[2] >> 6) & KMASK1) << 4); utmp[2] = ((aux[0] >> 4) & KMASK2) | (((aux[2] >> 4) & KMASK1) << 4); utmp[1] = (aux[1] & KMASK2) | (((aux[2] >> 2) & KMASK1) << 4); utmp[0] = (aux[0] & KMASK2) | ((aux[2] & KMASK1) << 4); let mut scale = utmp.as_mut_ptr() as *mut i8; for j in 0..16 { *scale.add(j) -= 32i8 } for j in 0..QK_K / 128 { let q3bits = vld1q_u8_x2(q3); q3 = q3.add(32); let q8bytes_1 = vld1q_s8_x4(q8); q8 = q8.add(64); let q8bytes_2 = vld1q_s8_x4(q8); q8 = q8.add(64); let q3h_0 = vshlq_n_u8(vbicq_u8(m0, qhbits.0), 2); let q3h_1 = vshlq_n_u8(vbicq_u8(m0, qhbits.1), 2); let q3h_2 = vshlq_n_u8(vbicq_u8(m1, qhbits.0), 1); let q3h_3 = vshlq_n_u8(vbicq_u8(m1, qhbits.1), 1); let q3bytes_0 = vsubq_s8( vreinterpretq_s8_u8(vandq_u8(q3bits.0, m3b)), vreinterpretq_s8_u8(q3h_0), ); let q3bytes_1 = vsubq_s8( vreinterpretq_s8_u8(vandq_u8(q3bits.1, m3b)), vreinterpretq_s8_u8(q3h_1), ); let q3bytes_2 = vsubq_s8( vreinterpretq_s8_u8(vandq_u8(vshrq_n_u8(q3bits.0, 2), m3b)), vreinterpretq_s8_u8(q3h_2), ); let q3bytes_3 = vsubq_s8( vreinterpretq_s8_u8(vandq_u8(vshrq_n_u8(q3bits.1, 2), m3b)), vreinterpretq_s8_u8(q3h_3), ); let p0 = vdotq_s32(q3bytes_0, q8bytes_1.0); let p1 = vdotq_s32(q3bytes_1, q8bytes_1.1); let p2 = vdotq_s32(q3bytes_2, q8bytes_1.2); let p3 = vdotq_s32(q3bytes_3, q8bytes_1.3); isum += vaddvq_s32(p0) * *scale as i32 + vaddvq_s32(p1) * *scale.add(1) as i32 + vaddvq_s32(p2) * *scale.add(2) as i32 + vaddvq_s32(p3) * *scale.add(3) as i32; scale = scale.add(4); let q3h_0 = vbicq_u8(m2, qhbits.0); let q3h_1 = vbicq_u8(m2, qhbits.1); let q3h_2 = vshrq_n_u8(vbicq_u8(m3, qhbits.0), 1); let q3h_3 = vshrq_n_u8(vbicq_u8(m3, qhbits.1), 1); let q3bytes_0 = vsubq_s8( vreinterpretq_s8_u8(vandq_u8(vshrq_n_u8(q3bits.0, 4), m3b)), vreinterpretq_s8_u8(q3h_0), ); let q3bytes_1 = vsubq_s8( vreinterpretq_s8_u8(vandq_u8(vshrq_n_u8(q3bits.1, 4), m3b)), vreinterpretq_s8_u8(q3h_1), ); let q3bytes_2 = vsubq_s8( vreinterpretq_s8_u8(vandq_u8(vshrq_n_u8(q3bits.0, 6), m3b)), vreinterpretq_s8_u8(q3h_2), ); let q3bytes_3 = vsubq_s8( vreinterpretq_s8_u8(vandq_u8(vshrq_n_u8(q3bits.1, 6), m3b)), vreinterpretq_s8_u8(q3h_3), ); let p0 = vdotq_s32(q3bytes_0, q8bytes_2.0); let p1 = vdotq_s32(q3bytes_1, q8bytes_2.1); let p2 = vdotq_s32(q3bytes_2, q8bytes_2.2); let p3 = vdotq_s32(q3bytes_3, q8bytes_2.3); isum += vaddvq_s32(p0) * *scale as i32 + vaddvq_s32(p1) * *scale.add(1) as i32 + vaddvq_s32(p2) * *scale.add(2) as i32 + vaddvq_s32(p3) * *scale.add(3) as i32; scale = scale.add(4); if j == 0 { qhbits.0 = vshrq_n_u8(qhbits.0, 4); qhbits.1 = vshrq_n_u8(qhbits.1, 4); } } sumf += d * isum as f32; } } Ok(sumf) } #[inline(always)] pub(crate) fn vec_dot_q2k_q8k(n: usize, xs: &[BlockQ2K], ys: &[BlockQ8K]) -> Result<f32> { if n % QK_K != 0 { crate::bail!("vec_dot_q2k_q8k: {n} is not divisible by {QK_K}") } let mut sumf = 0f32; let mut aux = [0u8; 16]; unsafe { let m3 = vdupq_n_u8(0x3); let m4 = vdupq_n_u8(0xF); for (x, y) in xs.iter().zip(ys.iter()) { let d = y.d * x.d.to_f32(); let dmin = -y.d * x.dmin.to_f32(); let mut q2 = x.qs.as_ptr(); let mut q8 = y.qs.as_ptr(); let sc = x.scales.as_ptr(); let mins_and_scales = vld1q_u8(sc); let scales = vandq_u8(mins_and_scales, m4); vst1q_u8(aux.as_mut_ptr(), scales); let mins = vshrq_n_u8(mins_and_scales, 4); let q8sums = vld1q_s16_x2(y.bsums.as_ptr()); let mins16 = int16x8x2_t( vreinterpretq_s16_u16(vmovl_u8(vget_low_u8(mins))), vreinterpretq_s16_u16(vmovl_u8(vget_high_u8(mins))), ); let s0 = vaddq_s32( vmull_s16(vget_low_s16(mins16.0), vget_low_s16(q8sums.0)), vmull_s16(vget_high_s16(mins16.0), vget_high_s16(q8sums.0)), ); let s1 = vaddq_s32( vmull_s16(vget_low_s16(mins16.1), vget_low_s16(q8sums.1)), vmull_s16(vget_high_s16(mins16.1), vget_high_s16(q8sums.1)), ); sumf += dmin * vaddvq_s32(vaddq_s32(s0, s1)) as f32; let mut isum = 0i32; let mut is = 0usize; // TODO: dotprod for _j in 0..QK_K / 128 { let q2bits = vld1q_u8_x2(q2); q2 = q2.add(32); let q8bytes = vld1q_s8_x2(q8); q8 = q8.add(32); let mut q2bytes = int8x16x2_t( vreinterpretq_s8_u8(vandq_u8(q2bits.0, m3)), vreinterpretq_s8_u8(vandq_u8(q2bits.1, m3)), ); isum += multiply_accum_with_scale(&aux, is, 0, q2bytes, q8bytes); let q8bytes = vld1q_s8_x2(q8); q8 = q8.add(32); q2bytes.0 = vreinterpretq_s8_u8(vandq_u8(vshrq_n_u8(q2bits.0, 2), m3)); q2bytes.1 = vreinterpretq_s8_u8(vandq_u8(vshrq_n_u8(q2bits.1, 2), m3)); isum += multiply_accum_with_scale(&aux, is, 2, q2bytes, q8bytes); let q8bytes = vld1q_s8_x2(q8); q8 = q8.add(32); q2bytes.0 = vreinterpretq_s8_u8(vandq_u8(vshrq_n_u8(q2bits.0, 4), m3)); q2bytes.1 = vreinterpretq_s8_u8(vandq_u8(vshrq_n_u8(q2bits.1, 4), m3)); isum += multiply_accum_with_scale(&aux, is, 4, q2bytes, q8bytes); let q8bytes = vld1q_s8_x2(q8); q8 = q8.add(32); q2bytes.0 = vreinterpretq_s8_u8(vandq_u8(vshrq_n_u8(q2bits.0, 6), m3)); q2bytes.1 = vreinterpretq_s8_u8(vandq_u8(vshrq_n_u8(q2bits.1, 6), m3)); isum += multiply_accum_with_scale(&aux, is, 6, q2bytes, q8bytes); is += 8; } sumf += d * isum as f32; } } Ok(sumf) } #[inline(always)] unsafe fn multiply_accum_with_scale( aux: &[u8; 16], is: usize, index: usize, q2bytes: int8x16x2_t, q8bytes: int8x16x2_t, ) -> i32 { let p1 = vdotq_s32(q2bytes.0, q8bytes.0); let p2 = vdotq_s32(q2bytes.1, q8bytes.1); vaddvq_s32(p1) * aux[is + index] as i32 + vaddvq_s32(p2) * aux[is + 1 + index] as i32 }
candle/candle-core/src/quantized/neon.rs/0
{ "file_path": "candle/candle-core/src/quantized/neon.rs", "repo_id": "candle", "token_count": 15290 }
30
use candle_core::backend::BackendStorage; use candle_core::cpu_backend; use candle_core::test_utils::to_vec1_round; use candle_core::{CpuStorage, CustomOp1, DType, Device, Error, Layout, Result, Shape, Tensor}; fn fwd<T: num_traits::Float>(v: T, alpha: f64) -> T { if v.is_sign_positive() { v } else { let alpha = T::from(alpha).unwrap_or(T::nan()); (v.exp() - T::one()) * alpha } } struct Elu { alpha: f64, } impl CustomOp1 for Elu { fn name(&self) -> &'static str { "elu" } fn cpu_fwd(&self, s: &CpuStorage, l: &Layout) -> Result<(CpuStorage, Shape)> { let storage = candle_core::map_dtype!( "elu", s, |s| cpu_backend::unary_map(s, l, |v| fwd(v, self.alpha)), (F8E4M3, BF16, F16, F32, F64) ); Ok((storage, l.shape().clone())) } } #[test] fn custom_op1_no_backward() -> Result<()> { let cpu = &Device::Cpu; let t = Tensor::arange(0u32, 12u32, cpu)?.to_dtype(DType::F32)?; let t = (t - 5.)?; let elu_t = t.apply_op1_no_bwd(&Elu { alpha: 1. })?; assert_eq!( to_vec1_round(&elu_t, 4)?, &[-0.9933, -0.9817, -0.9502, -0.8647, -0.6321, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0] ); Ok(()) } // Define a similar struct as Elu but with backward support. fn bwd<T: num_traits::Float>(v: T, alpha: f64) -> T { if v.is_sign_positive() { T::one() } else { let alpha = T::from(alpha).unwrap_or(T::nan()); v.exp() * alpha } } struct EluBackward { alpha: f64, } impl CustomOp1 for EluBackward { fn name(&self) -> &'static str { "elu-bwd" } fn cpu_fwd(&self, s: &CpuStorage, l: &Layout) -> Result<(CpuStorage, Shape)> { let storage = candle_core::map_dtype!( "elu-bwd", s, |s| cpu_backend::unary_map(s, l, |v| bwd(v, self.alpha)), (F8E4M3, BF16, F16, F32, F64) ); Ok((storage, l.shape().clone())) } } struct EluWithBackward(Elu); impl EluWithBackward { fn new(alpha: f64) -> Self { Self(Elu { alpha }) } } impl CustomOp1 for EluWithBackward { fn name(&self) -> &'static str { "elu" } fn cpu_fwd(&self, s: &CpuStorage, l: &Layout) -> Result<(CpuStorage, Shape)> { self.0.cpu_fwd(s, l) } fn bwd(&self, arg: &Tensor, _res: &Tensor, grad_res: &Tensor) -> Result<Option<Tensor>> { let alpha = self.0.alpha; let bwd = arg.apply_op1(EluBackward { alpha })?; Ok(Some(grad_res.mul(&bwd)?)) } } #[test] fn custom_op1_with_backward() -> Result<()> { let cpu = &Device::Cpu; let t = candle_core::Var::new(&[-2f32, 0f32, 2f32], cpu)?; let elu_t = t.apply_op1(EluWithBackward::new(2.))?; assert_eq!(to_vec1_round(&elu_t, 4)?, &[-1.7293, 0.0, 2.0]); let grads = elu_t.backward()?; let grad_x = grads.get(&t).unwrap(); assert_eq!(to_vec1_round(grad_x, 4)?, [0.2707, 1.0, 1.0]); Ok(()) } impl candle_core::InplaceOp1 for Elu { fn name(&self) -> &'static str { "elu" } fn cpu_fwd(&self, s: &mut CpuStorage, _l: &Layout) -> Result<()> { let alpha = self.alpha; match s { CpuStorage::F8E4M3(s) => s.iter_mut().for_each(|v| *v = fwd(*v, alpha)), CpuStorage::BF16(s) => s.iter_mut().for_each(|v| *v = fwd(*v, alpha)), CpuStorage::F16(s) => s.iter_mut().for_each(|v| *v = fwd(*v, alpha)), CpuStorage::F32(s) => s.iter_mut().for_each(|v| *v = fwd(*v, alpha)), CpuStorage::F64(s) => s.iter_mut().for_each(|v| *v = fwd(*v, alpha)), _ => candle_core::bail!("unsupported dtype for inplace elu"), } Ok(()) } } #[test] fn inplace_op1() -> Result<()> { let cpu = &Device::Cpu; let t = Tensor::arange(0u32, 12u32, cpu)?.to_dtype(DType::F32)?; let t = (t - 5.)?; t.inplace_op1(&Elu { alpha: 1. })?; assert_eq!( to_vec1_round(&t, 4)?, &[-0.9933, -0.9817, -0.9502, -0.8647, -0.6321, 0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0] ); Ok(()) } #[cfg(any(feature = "cuda", feature = "metal"))] #[allow(clippy::approx_constant)] #[test] fn ug_op() -> Result<()> { let kernel = { use ug::lang::op; let layout = ug::Layout::from_shape(&[12]); let ptr = op::Arg::ptr(ug::DType::F32); let src = op::load(ptr.id(), layout.clone(), ug::DType::F32)?; let src = op::unary(op::UnaryOp::Exp, src)?; let st = op::store(ptr.id(), layout, src)?; let kernel = op::Kernel::new("exp".to_string(), vec![ptr], vec![st]); let opts: ug::lower_op::Opts = Default::default(); kernel.lower(&opts)? }; let device = if candle_core::utils::cuda_is_available() { Device::new_cuda(0)? } else if candle_core::utils::metal_is_available() { Device::new_metal(0)? } else { candle_core::bail!("metal/cuda is mandatory for this test") }; let op = candle_core::UgIOp1::new("test", kernel, &device)?; let t = Tensor::arange(0u32, 12u32, &device)?.to_dtype(DType::F32)?; t.inplace_op1(&op)?; assert_eq!( to_vec1_round(&t, 2)?, &[ 1.0, 2.72, 7.39, 20.09, 54.6, 148.41, 403.43, 1096.63, 2980.96, 8103.08, 22026.47, 59874.13 ] ); Ok(()) }
candle/candle-core/tests/custom_op_tests.rs/0
{ "file_path": "candle/candle-core/tests/custom_op_tests.rs", "repo_id": "candle", "token_count": 2784 }
31
# candle-based Experimental, not instruction-tuned small LLM from the Hazy Research group, combining local and linear attention layers. [Blogpost](https://hazyresearch.stanford.edu/blog/2024-03-03-based) [Simple linear attention language models balance the recall-throughput tradeoff](https://arxiv.org/abs/2402.18668) ## Running an example ```bash $ cargo run --example based --release -- --prompt "Flying monkeys are" --which 1b-50b --sample-len 100 Flying monkeys are a common sight in the wild, but they are also a threat to humans. The new study, published today (July 31) in the journal Science Advances, shows that the monkeys are using their brains to solve the problem of how to get around the problem. "We found that the monkeys were using a strategy called 'cognitive mapping' - they would use their brains to map out the route ahead," says lead author Dr. David J. Smith from the University of California ```
candle/candle-examples/examples/based/README.md/0
{ "file_path": "candle/candle-examples/examples/based/README.md", "repo_id": "candle", "token_count": 243 }
32
* candle-codegeex4_9b THUDM/CodeGeeX4 is a versatile model for all AI software development scenarios, including code completion, code interpreter, web search, function calling, repository-level Q&A and much more. - [[https://github.com/THUDM/CodeGeeX4][Github]] - [[https://codegeex.cn/][HomePage]] - [[https://huggingface.co/THUDM/codegeex4-all-9b][huggingface]] ** Running with ~cuda~ #+begin_src shell cargo run --example codegeex4-9b --release --features cuda -- --prompt "please write a insertion sort in rust" --sample-len 300 #+end_src ** Running with ~cpu~ #+begin_src shell cargo run --example codegeex4-9b --release -- --cpu --prompt "please write a insertion sort in rust" --sample-len 300 #+end_src ** Output_Example *** Input #+begin_src shell cargo run --release --features cuda -- --prompt 'please write a FFT in rust' --sample-len 500 --cache /root/autodl-tmp #+end_src *** Output #+begin_src shell avx: false, neon: false, simd128: false, f16c: false temp: 0.95 repeat-penalty: 1.10 repeat-last-n: 64 cache path /root/autodl-tmp Prompt: [please write a FFT in rust] Using Seed 11511762269791786684 DType is BF16 transofrmer layers create 模型加载完毕 4 starting the inference loop 开始生成 samplelen 500 500 tokens generated (34.60 token/s) Result: Sure, I can help you with that. Here's an example of a Fast Fourier Transform (FFT) implementation in Rust: ```rust use num_complex::Complex; fn fft(input: &[Complex<f64> > ] ) -> Vec<Complex<f64> > > { let n = input.len(); if n == 1 { return vec![input[0]]]; } let mut even = vec![]; let mut odd = vec![]; for i in 0..n { if i % 2 == 0 { even.push(input[i]); } else { odd.push(input[i]); } } let even_fft = fft(&even); let odd_fft = fft(&odd); let mut output = vec![]; for k in 0..n/2 { let t = Complex::new(0.0, -2.0 * std::f64::consts::PI * (k as f64) / (n as f64))) ).exp(); output.push(even_fft[k] + odd_fft[k] * t]); output.push(even_fft[k] - odd_fft[k] * t]); } return output; } ``` This implementation uses the Cooley-Tukey algorithm to perform the FFT. The function takes an array of complex numbers and returns an array of complex numbers which is the result of the FFT. #+end_src * Citation #+begin_src @inproceedings{zheng2023codegeex, title={CodeGeeX: A Pre-Trained Model for Code Generation with Multilingual Benchmarking on HumanEval-X}, author={Qinkai Zheng and Xiao Xia and Xu Zou and Yuxiao Dong and Shan Wang and Yufei Xue and Zihan Wang and Lei Shen and Andi Wang and Yang Li and Teng Su and Zhilin Yang and Jie Tang}, booktitle={Proceedings of the 29th ACM SIGKDD Conference on Knowledge Discovery and Data Mining}, pages={5673--5684}, year={2023} } #+end_src
candle/candle-examples/examples/codegeex4-9b/README.org/0
{ "file_path": "candle/candle-examples/examples/codegeex4-9b/README.org", "repo_id": "candle", "token_count": 1132 }
33
#[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::efficientvit; #[derive(Clone, Copy, Debug, ValueEnum)] enum Which { M0, M1, M2, M3, M4, M5, } impl Which { fn model_filename(&self) -> String { let name = match self { Self::M0 => "m0", Self::M1 => "m1", Self::M2 => "m2", Self::M3 => "m3", Self::M4 => "m4", Self::M5 => "m5", }; format!("timm/efficientvit_{name}.r224_in1k") } fn config(&self) -> efficientvit::Config { match self { Self::M0 => efficientvit::Config::m0(), Self::M1 => efficientvit::Config::m1(), Self::M2 => efficientvit::Config::m2(), Self::M3 => efficientvit::Config::m3(), Self::M4 => efficientvit::Config::m4(), Self::M5 => efficientvit::Config::m5(), } } } #[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::M0)] 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 = efficientvit::efficientvit(&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/efficientvit/main.rs/0
{ "file_path": "candle/candle-examples/examples/efficientvit/main.rs", "repo_id": "candle", "token_count": 1277 }
34
#[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::gemma::{Config as Config1, Model as Model1}; use candle_transformers::models::gemma2::{Config as Config2, Model as Model2}; use candle_transformers::models::gemma3::{Config as Config3, Model as Model3}; use candle::{DType, Device, Tensor}; use candle_examples::token_output_stream::TokenOutputStream; use candle_nn::VarBuilder; use candle_transformers::generation::LogitsProcessor; use hf_hub::{api::sync::Api, Repo, RepoType}; use tokenizers::Tokenizer; #[derive(Clone, Debug, Copy, PartialEq, Eq, clap::ValueEnum)] enum Which { #[value(name = "2b")] Base2B, #[value(name = "7b")] Base7B, #[value(name = "2b-it")] Instruct2B, #[value(name = "7b-it")] Instruct7B, #[value(name = "1.1-2b-it")] InstructV1_1_2B, #[value(name = "1.1-7b-it")] InstructV1_1_7B, #[value(name = "code-2b")] CodeBase2B, #[value(name = "code-7b")] CodeBase7B, #[value(name = "code-2b-it")] CodeInstruct2B, #[value(name = "code-7b-it")] CodeInstruct7B, #[value(name = "2-2b")] BaseV2_2B, #[value(name = "2-2b-it")] InstructV2_2B, #[value(name = "2-9b")] BaseV2_9B, #[value(name = "2-9b-it")] InstructV2_9B, #[value(name = "3-1b")] BaseV3_1B, #[value(name = "3-1b-it")] InstructV3_1B, } enum Model { V1(Model1), V2(Model2), V3(Model3), } impl Model { fn forward(&mut self, input_ids: &Tensor, pos: usize) -> candle::Result<Tensor> { match self { Self::V1(m) => m.forward(input_ids, pos), Self::V2(m) => m.forward(input_ids, pos), Self::V3(m) => m.forward(input_ids, pos), } } } 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("<eos>") { Some(token) => token, None => anyhow::bail!("cannot find the <eos> token"), }; let eot_token = match self.tokenizer.get_token("<end_of_turn>") { Some(token) => token, None => { println!( "Warning: <end_of_turn> token not found in tokenizer, using <eos> as a backup" ); eos_token } }; let start_gen = std::time::Instant::now(); for index in 0..sample_len { let context_size = if index > 0 { 1 } else { tokens.len() }; let start_pos = tokens.len().saturating_sub(context_size); let ctxt = &tokens[start_pos..]; let input = Tensor::new(ctxt, &self.device)?.unsqueeze(0)?; let logits = self.model.forward(&input, start_pos)?; let logits = logits.squeeze(0)?.squeeze(0)?.to_dtype(DType::F32)?; let logits = if self.repeat_penalty == 1. { logits } else { let start_at = tokens.len().saturating_sub(self.repeat_last_n); candle_transformers::utils::apply_repeat_penalty( &logits, self.repeat_penalty, &tokens[start_at..], )? }; let next_token = self.logits_processor.sample(&logits)?; tokens.push(next_token); generated_tokens += 1; if next_token == eos_token || next_token == eot_token { break; } if let Some(t) = self.tokenizer.next_token(next_token)? { print!("{t}"); std::io::stdout().flush()?; } } let dt = start_gen.elapsed(); if let Some(rest) = self.tokenizer.decode_rest().map_err(E::msg)? { print!("{rest}"); } std::io::stdout().flush()?; println!( "\n{generated_tokens} tokens generated ({:.2} token/s)", generated_tokens as f64 / dt.as_secs_f64(), ); Ok(()) } } #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] struct Args { /// Run on CPU rather than on GPU. #[arg(long)] cpu: bool, /// Enable tracing (generates a trace-timestamp.json file). #[arg(long)] tracing: bool, #[arg(long)] prompt: String, /// The temperature used to generate samples. #[arg(long)] temperature: Option<f64>, /// Nucleus sampling probability cutoff. #[arg(long)] top_p: Option<f64>, /// The seed to use when generating random samples. #[arg(long, default_value_t = 299792458)] seed: u64, /// The length of the sample to generate (in tokens). #[arg(long, short = 'n', default_value_t = 10000)] sample_len: usize, #[arg(long)] model_id: Option<String>, #[arg(long, default_value = "main")] revision: String, #[arg(long)] tokenizer_file: Option<String>, #[arg(long)] config_file: Option<String>, #[arg(long)] weight_files: Option<String>, /// Penalty to be applied for repeating tokens, 1. means no penalty. #[arg(long, default_value_t = 1.1)] repeat_penalty: f32, /// The context size to consider for the repeat penalty. #[arg(long, default_value_t = 64)] repeat_last_n: usize, /// The model to use. #[arg(long, default_value = "2-2b")] which: Which, #[arg(long)] use_flash_attn: bool, } fn main() -> Result<()> { use tracing_chrome::ChromeLayerBuilder; use tracing_subscriber::prelude::*; let args = Args::parse(); let _guard = if args.tracing { let (chrome_layer, guard) = ChromeLayerBuilder::new().build(); tracing_subscriber::registry().with(chrome_layer).init(); Some(guard) } else { None }; println!( "avx: {}, neon: {}, simd128: {}, f16c: {}", candle::utils::with_avx(), candle::utils::with_neon(), candle::utils::with_simd128(), candle::utils::with_f16c() ); println!( "temp: {:.2} repeat-penalty: {:.2} repeat-last-n: {}", args.temperature.unwrap_or(0.), args.repeat_penalty, args.repeat_last_n ); let start = std::time::Instant::now(); let api = Api::new()?; let model_id = match &args.model_id { Some(model_id) => model_id.to_string(), None => match args.which { Which::InstructV1_1_2B => "google/gemma-1.1-2b-it".to_string(), Which::InstructV1_1_7B => "google/gemma-1.1-7b-it".to_string(), Which::Base2B => "google/gemma-2b".to_string(), Which::Base7B => "google/gemma-7b".to_string(), Which::Instruct2B => "google/gemma-2b-it".to_string(), Which::Instruct7B => "google/gemma-7b-it".to_string(), Which::CodeBase2B => "google/codegemma-2b".to_string(), Which::CodeBase7B => "google/codegemma-7b".to_string(), Which::CodeInstruct2B => "google/codegemma-2b-it".to_string(), Which::CodeInstruct7B => "google/codegemma-7b-it".to_string(), Which::BaseV2_2B => "google/gemma-2-2b".to_string(), Which::InstructV2_2B => "google/gemma-2-2b-it".to_string(), Which::BaseV2_9B => "google/gemma-2-9b".to_string(), Which::InstructV2_9B => "google/gemma-2-9b-it".to_string(), Which::BaseV3_1B => "google/gemma-3-1b-pt".to_string(), Which::InstructV3_1B => "google/gemma-3-1b-it".to_string(), }, }; let repo = api.repo(Repo::with_revision( model_id, RepoType::Model, args.revision, )); let tokenizer_filename = match args.tokenizer_file { Some(file) => std::path::PathBuf::from(file), None => repo.get("tokenizer.json")?, }; let config_filename = match args.config_file { Some(file) => std::path::PathBuf::from(file), None => repo.get("config.json")?, }; let filenames = match args.weight_files { Some(files) => files .split(',') .map(std::path::PathBuf::from) .collect::<Vec<_>>(), None => match args.which { Which::BaseV3_1B | Which::InstructV3_1B => vec![repo.get("model.safetensors")?], _ => candle_examples::hub_load_safetensors(&repo, "model.safetensors.index.json")?, }, }; println!("retrieved the files in {:?}", start.elapsed()); let tokenizer = Tokenizer::from_file(tokenizer_filename).map_err(E::msg)?; let start = std::time::Instant::now(); let device = candle_examples::device(args.cpu)?; let dtype = if device.is_cuda() { DType::BF16 } else { DType::F32 }; let vb = unsafe { VarBuilder::from_mmaped_safetensors(&filenames, dtype, &device)? }; let model = match args.which { Which::Base2B | Which::Base7B | Which::Instruct2B | Which::Instruct7B | Which::InstructV1_1_2B | Which::InstructV1_1_7B | Which::CodeBase2B | Which::CodeBase7B | Which::CodeInstruct2B | Which::CodeInstruct7B => { let config: Config1 = serde_json::from_reader(std::fs::File::open(config_filename)?)?; let model = Model1::new(args.use_flash_attn, &config, vb)?; Model::V1(model) } Which::BaseV2_2B | Which::InstructV2_2B | Which::BaseV2_9B | Which::InstructV2_9B => { let config: Config2 = serde_json::from_reader(std::fs::File::open(config_filename)?)?; let model = Model2::new(args.use_flash_attn, &config, vb)?; Model::V2(model) } Which::BaseV3_1B | Which::InstructV3_1B => { let config: Config3 = serde_json::from_reader(std::fs::File::open(config_filename)?)?; let model = Model3::new(args.use_flash_attn, &config, vb)?; Model::V3(model) } }; 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, ); let prompt = match args.which { Which::Base2B | Which::Base7B | Which::Instruct2B | Which::Instruct7B | Which::InstructV1_1_2B | Which::InstructV1_1_7B | Which::CodeBase2B | Which::CodeBase7B | Which::CodeInstruct2B | Which::CodeInstruct7B | Which::BaseV2_2B | Which::InstructV2_2B | Which::BaseV2_9B | Which::InstructV2_9B | Which::BaseV3_1B => args.prompt, Which::InstructV3_1B => { format!( "<start_of_turn> user\n{}<end_of_turn>\n<start_of_turn> model\n", args.prompt ) } }; pipeline.run(&prompt, args.sample_len)?; Ok(()) }
candle/candle-examples/examples/gemma/main.rs/0
{ "file_path": "candle/candle-examples/examples/gemma/main.rs", "repo_id": "candle", "token_count": 6074 }
35
use crate::model::{Cache, Config, Llama}; use candle::{DType, Device, Result}; use candle_datasets::nlp::tinystories::{Dataset, DatasetRandomIter}; use candle_nn::Optimizer; fn valid_loss( dataset: &Dataset, model: &Llama, args: &crate::TrainingCmd, device: &Device, cache: &mut Cache, ) -> Result<f64> { let iter = DatasetRandomIter::new(dataset, true, model.config.seq_len, device.clone()); let batch_iter = candle_datasets::Batcher::new_r2(iter).batch_size(args.batch_size); let mut sum_ce = 0f64; let mut cnt = 0usize; for inp_tgt in batch_iter.take(50) { let (inp, tgt) = inp_tgt?; let logits = model.forward(&inp, 0, cache)?; let loss = candle_nn::loss::cross_entropy(&logits.flatten_to(1)?, &tgt.flatten_to(1)?)?; sum_ce += loss.to_vec0::<f32>()? as f64; cnt += 1; } Ok(sum_ce / cnt as f64) } pub fn run(args: &crate::TrainingCmd, common_args: &crate::Args) -> Result<()> { let device = candle_examples::device(common_args.cpu)?; let dataset = Dataset::new(&args.pretokenized_dir)?; println!( "loaded dataset, train: {} files, valid: {} files", dataset.train_tokens(), dataset.valid_tokens() ); let varmap = candle_nn::VarMap::new(); let vb = candle_nn::VarBuilder::from_varmap(&varmap, DType::F32, &device); let config = Config::tiny_15m(); let iter = DatasetRandomIter::new(&dataset, false, config.seq_len, device.clone()); let batch_iter = candle_datasets::Batcher::new_r2(iter).batch_size(args.batch_size); let mut cache = Cache::new(false, &config, vb.pp("rot"))?; let model = Llama::load(vb, config)?; let params = candle_nn::ParamsAdamW { lr: args.learning_rate, ..Default::default() }; let mut opt = candle_nn::AdamW::new(varmap.all_vars(), params)?; for (batch_index, batch) in batch_iter.enumerate() { let (inp, tgt) = batch?; let logits = model.forward(&inp, 0, &mut cache)?; let loss = candle_nn::loss::cross_entropy(&logits.flatten_to(1)?, &tgt.flatten_to(1)?)?; opt.backward_step(&loss)?; if batch_index > 0 && batch_index % 100 == 0 { // TODO: Add a way to deactivate the backprop graph tracking when computing the // validation loss. let loss = valid_loss(&dataset, &model, args, &device, &mut cache)?; println!("{batch_index} {loss}"); } if batch_index > 0 && batch_index % 1000 == 0 { varmap.save("checkpoint.safetensors")? } } Ok(()) }
candle/candle-examples/examples/llama2-c/training.rs/0
{ "file_path": "candle/candle-examples/examples/llama2-c/training.rs", "repo_id": "candle", "token_count": 1144 }
36
# candle-mobileone [MobileOne: An Improved One millisecond Mobile Backbone](https://arxiv.org/abs/2206.04040). This candle implementation uses a pre-trained MobileOne 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 mobileone --release -- --image candle-examples/examples/yolo-v8/assets/bike.jpg --which s2 loaded image Tensor[dims 3, 224, 224; f32] model built mountain bike, all-terrain bike, off-roader: 79.33% bicycle-built-for-two, tandem bicycle, tandem: 15.32% crash helmet : 2.58% unicycle, monocycle : 1.70% alp : 0.21% ```
candle/candle-examples/examples/mobileone/README.md/0
{ "file_path": "candle/candle-examples/examples/mobileone/README.md", "repo_id": "candle", "token_count": 254 }
37
#[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; use candle::{IndexOp, D}; use candle_examples::save_image; use clap::{Parser, ValueEnum}; #[derive(Clone, Copy, Debug, ValueEnum)] enum Which { SqueezeNet, EfficientNet, EsrGan, } #[derive(Parser)] struct Args { #[arg(long)] image: String, #[arg(long)] model: Option<String>, /// The model to be used. #[arg(value_enum, long, default_value_t = Which::SqueezeNet)] which: Which, } pub fn main() -> anyhow::Result<()> { let args = Args::parse(); let image = match args.which { Which::SqueezeNet | Which::EfficientNet => { candle_examples::imagenet::load_image224(&args.image)? } Which::EsrGan => candle_examples::imagenet::load_image_with_std_mean( &args.image, 128, &[0.0f32, 0.0, 0.0], &[1.0f32, 1.0, 1.0], )?, }; let image = match args.which { Which::SqueezeNet => image, Which::EfficientNet => image.permute((1, 2, 0))?, Which::EsrGan => image, }; println!("loaded image {image:?}"); let model = match args.model { Some(model) => std::path::PathBuf::from(model), None => match args.which { Which::SqueezeNet => hf_hub::api::sync::Api::new()? .model("lmz/candle-onnx".into()) .get("squeezenet1.1-7.onnx")?, Which::EfficientNet => hf_hub::api::sync::Api::new()? .model("onnx/EfficientNet-Lite4".into()) .get("efficientnet-lite4-11.onnx")?, Which::EsrGan => hf_hub::api::sync::Api::new()? .model("qualcomm/Real-ESRGAN-x4plus".into()) .get("Real-ESRGAN-x4plus.onnx")?, }, }; let model = candle_onnx::read_file(model)?; let graph = model.graph.as_ref().unwrap(); let mut inputs = std::collections::HashMap::new(); inputs.insert(graph.input[0].name.to_string(), image.unsqueeze(0)?); let mut outputs = candle_onnx::simple_eval(&model, inputs)?; let output = outputs.remove(&graph.output[0].name).unwrap(); let prs = match args.which { Which::SqueezeNet => candle_nn::ops::softmax(&output, D::Minus1)?, Which::EfficientNet => output, Which::EsrGan => output, }; match args.which { Which::EfficientNet | Which::SqueezeNet => { let prs = prs.i(0)?.to_vec1::<f32>()?; // Sort the predictions and take the top 5 let mut top: Vec<_> = prs.iter().enumerate().collect(); top.sort_by(|a, b| b.1.partial_cmp(a.1).unwrap()); let top = top.into_iter().take(5).collect::<Vec<_>>(); // Print the top predictions for &(i, p) in &top { println!( "{:50}: {:.2}%", candle_examples::imagenet::CLASSES[i], p * 100.0 ); } } Which::EsrGan => { let max_pixel_val = candle::Tensor::try_from(255.0f32)? .to_device(prs.device())? .broadcast_as(prs.shape())?; let out = (prs * max_pixel_val)?.i(0)?.to_dtype(candle::DType::U8)?; let pb = std::path::PathBuf::from(args.image); let input_file_name = pb.file_name().unwrap(); let mut output_file_name = std::ffi::OsString::from("super_"); output_file_name.push(input_file_name); save_image(&out, output_file_name)?; } } Ok(()) }
candle/candle-examples/examples/onnx/main.rs/0
{ "file_path": "candle/candle-examples/examples/onnx/main.rs", "repo_id": "candle", "token_count": 1834 }
38
use std::collections::VecDeque; use candle::{DType, Device, Error, Module, Result, Tensor, Var}; use candle_nn::{ func, linear, sequential::seq, Activation, AdamW, Optimizer, ParamsAdamW, Sequential, VarBuilder, VarMap, }; use rand::{distr::Uniform, rng, Rng}; use super::gym_env::GymEnv; pub struct OuNoise { mu: f64, theta: f64, sigma: f64, state: Tensor, } impl OuNoise { pub fn new(mu: f64, theta: f64, sigma: f64, size_action: usize) -> Result<Self> { Ok(Self { mu, theta, sigma, state: Tensor::ones(size_action, DType::F32, &Device::Cpu)?, }) } pub fn sample(&mut self) -> Result<Tensor> { let rand = Tensor::randn_like(&self.state, 0.0, 1.0)?; let dx = ((self.theta * (self.mu - &self.state)?)? + (self.sigma * rand)?)?; self.state = (&self.state + dx)?; Ok(self.state.clone()) } } #[derive(Clone)] struct Transition { state: Tensor, action: Tensor, reward: Tensor, next_state: Tensor, terminated: bool, truncated: bool, } impl Transition { fn new( state: &Tensor, action: &Tensor, reward: &Tensor, next_state: &Tensor, terminated: bool, truncated: bool, ) -> Self { Self { state: state.clone(), action: action.clone(), reward: reward.clone(), next_state: next_state.clone(), terminated, truncated, } } } pub struct ReplayBuffer { buffer: VecDeque<Transition>, capacity: usize, size: usize, } impl ReplayBuffer { pub fn new(capacity: usize) -> Self { Self { buffer: VecDeque::with_capacity(capacity), capacity, size: 0, } } pub fn push( &mut self, state: &Tensor, action: &Tensor, reward: &Tensor, next_state: &Tensor, terminated: bool, truncated: bool, ) { if self.size == self.capacity { self.buffer.pop_front(); } else { self.size += 1; } self.buffer.push_back(Transition::new( state, action, reward, next_state, terminated, truncated, )); } #[allow(clippy::type_complexity)] pub fn random_batch( &self, batch_size: usize, ) -> Result<Option<(Tensor, Tensor, Tensor, Tensor, Vec<bool>, Vec<bool>)>> { if self.size < batch_size { Ok(None) } else { let transitions: Vec<&Transition> = rng() .sample_iter(Uniform::try_from(0..self.size).map_err(Error::wrap)?) .take(batch_size) .map(|i| self.buffer.get(i).unwrap()) .collect(); let states: Vec<Tensor> = transitions .iter() .map(|t| t.state.unsqueeze(0)) .collect::<Result<_>>()?; let actions: Vec<Tensor> = transitions .iter() .map(|t| t.action.unsqueeze(0)) .collect::<Result<_>>()?; let rewards: Vec<Tensor> = transitions .iter() .map(|t| t.reward.unsqueeze(0)) .collect::<Result<_>>()?; let next_states: Vec<Tensor> = transitions .iter() .map(|t| t.next_state.unsqueeze(0)) .collect::<Result<_>>()?; let terminateds: Vec<bool> = transitions.iter().map(|t| t.terminated).collect(); let truncateds: Vec<bool> = transitions.iter().map(|t| t.truncated).collect(); Ok(Some(( Tensor::cat(&states, 0)?, Tensor::cat(&actions, 0)?, Tensor::cat(&rewards, 0)?, Tensor::cat(&next_states, 0)?, terminateds, truncateds, ))) } } } fn track( varmap: &mut VarMap, vb: &VarBuilder, target_prefix: &str, network_prefix: &str, dims: &[(usize, usize)], tau: f64, ) -> Result<()> { for (i, &(in_dim, out_dim)) in dims.iter().enumerate() { let target_w = vb.get((out_dim, in_dim), &format!("{target_prefix}-fc{i}.weight"))?; let network_w = vb.get((out_dim, in_dim), &format!("{network_prefix}-fc{i}.weight"))?; varmap.set_one( format!("{target_prefix}-fc{i}.weight"), ((tau * network_w)? + ((1.0 - tau) * target_w)?)?, )?; let target_b = vb.get(out_dim, &format!("{target_prefix}-fc{i}.bias"))?; let network_b = vb.get(out_dim, &format!("{network_prefix}-fc{i}.bias"))?; varmap.set_one( format!("{target_prefix}-fc{i}.bias"), ((tau * network_b)? + ((1.0 - tau) * target_b)?)?, )?; } Ok(()) } #[allow(unused)] struct Actor<'a> { varmap: VarMap, vb: VarBuilder<'a>, network: Sequential, target_network: Sequential, size_state: usize, size_action: usize, dims: Vec<(usize, usize)>, } impl Actor<'_> { fn new(device: &Device, dtype: DType, size_state: usize, size_action: usize) -> Result<Self> { let mut varmap = VarMap::new(); let vb = VarBuilder::from_varmap(&varmap, dtype, device); let dims = vec![(size_state, 400), (400, 300), (300, size_action)]; let make_network = |prefix: &str| { let seq = seq() .add(linear( dims[0].0, dims[0].1, vb.pp(format!("{prefix}-fc0")), )?) .add(Activation::Relu) .add(linear( dims[1].0, dims[1].1, vb.pp(format!("{prefix}-fc1")), )?) .add(Activation::Relu) .add(linear( dims[2].0, dims[2].1, vb.pp(format!("{prefix}-fc2")), )?) .add(func(|xs| xs.tanh())); Ok::<Sequential, Error>(seq) }; let network = make_network("actor")?; let target_network = make_network("target-actor")?; // this sets the two networks to be equal to each other using tau = 1.0 track(&mut varmap, &vb, "target-actor", "actor", &dims, 1.0)?; Ok(Self { varmap, vb, network, target_network, size_state, size_action, dims, }) } fn forward(&self, state: &Tensor) -> Result<Tensor> { self.network.forward(state) } fn target_forward(&self, state: &Tensor) -> Result<Tensor> { self.target_network.forward(state) } fn track(&mut self, tau: f64) -> Result<()> { track( &mut self.varmap, &self.vb, "target-actor", "actor", &self.dims, tau, ) } } #[allow(unused)] struct Critic<'a> { varmap: VarMap, vb: VarBuilder<'a>, network: Sequential, target_network: Sequential, size_state: usize, size_action: usize, dims: Vec<(usize, usize)>, } impl Critic<'_> { fn new(device: &Device, dtype: DType, size_state: usize, size_action: usize) -> Result<Self> { let mut varmap = VarMap::new(); let vb = VarBuilder::from_varmap(&varmap, dtype, device); let dims: Vec<(usize, usize)> = vec![(size_state + size_action, 400), (400, 300), (300, 1)]; let make_network = |prefix: &str| { let seq = seq() .add(linear( dims[0].0, dims[0].1, vb.pp(format!("{prefix}-fc0")), )?) .add(Activation::Relu) .add(linear( dims[1].0, dims[1].1, vb.pp(format!("{prefix}-fc1")), )?) .add(Activation::Relu) .add(linear( dims[2].0, dims[2].1, vb.pp(format!("{prefix}-fc2")), )?); Ok::<Sequential, Error>(seq) }; let network = make_network("critic")?; let target_network = make_network("target-critic")?; // this sets the two networks to be equal to each other using tau = 1.0 track(&mut varmap, &vb, "target-critic", "critic", &dims, 1.0)?; Ok(Self { varmap, vb, network, target_network, size_state, size_action, dims, }) } fn forward(&self, state: &Tensor, action: &Tensor) -> Result<Tensor> { let xs = Tensor::cat(&[action, state], 1)?; self.network.forward(&xs) } fn target_forward(&self, state: &Tensor, action: &Tensor) -> Result<Tensor> { let xs = Tensor::cat(&[action, state], 1)?; self.target_network.forward(&xs) } fn track(&mut self, tau: f64) -> Result<()> { track( &mut self.varmap, &self.vb, "target-critic", "critic", &self.dims, tau, ) } } #[allow(unused)] #[allow(clippy::upper_case_acronyms)] pub struct DDPG<'a> { actor: Actor<'a>, actor_optim: AdamW, critic: Critic<'a>, critic_optim: AdamW, gamma: f64, tau: f64, replay_buffer: ReplayBuffer, ou_noise: OuNoise, size_state: usize, size_action: usize, pub train: bool, } impl DDPG<'_> { #[allow(clippy::too_many_arguments)] pub fn new( device: &Device, size_state: usize, size_action: usize, train: bool, actor_lr: f64, critic_lr: f64, gamma: f64, tau: f64, buffer_capacity: usize, ou_noise: OuNoise, ) -> Result<Self> { let filter_by_prefix = |varmap: &VarMap, prefix: &str| { varmap .data() .lock() .unwrap() .iter() .filter_map(|(name, var)| name.starts_with(prefix).then_some(var.clone())) .collect::<Vec<Var>>() }; let actor = Actor::new(device, DType::F32, size_state, size_action)?; let actor_optim = AdamW::new( filter_by_prefix(&actor.varmap, "actor"), ParamsAdamW { lr: actor_lr, ..Default::default() }, )?; let critic = Critic::new(device, DType::F32, size_state, size_action)?; let critic_optim = AdamW::new( filter_by_prefix(&critic.varmap, "critic"), ParamsAdamW { lr: critic_lr, ..Default::default() }, )?; Ok(Self { actor, actor_optim, critic, critic_optim, gamma, tau, replay_buffer: ReplayBuffer::new(buffer_capacity), ou_noise, size_state, size_action, train, }) } pub fn remember( &mut self, state: &Tensor, action: &Tensor, reward: &Tensor, next_state: &Tensor, terminated: bool, truncated: bool, ) { self.replay_buffer .push(state, action, reward, next_state, terminated, truncated) } pub fn actions(&mut self, state: &Tensor) -> Result<f32> { let actions = self .actor .forward(&state.detach().unsqueeze(0)?)? .squeeze(0)?; let actions = if self.train { (actions + self.ou_noise.sample()?)? } else { actions }; actions.squeeze(0)?.to_scalar::<f32>() } pub fn train(&mut self, batch_size: usize) -> Result<()> { let (states, actions, rewards, next_states, _, _) = match self.replay_buffer.random_batch(batch_size)? { Some(v) => v, _ => return Ok(()), }; let q_target = self .critic .target_forward(&next_states, &self.actor.target_forward(&next_states)?)?; let q_target = (rewards + (self.gamma * q_target)?.detach())?; let q = self.critic.forward(&states, &actions)?; let diff = (q_target - q)?; let critic_loss = diff.sqr()?.mean_all()?; self.critic_optim.backward_step(&critic_loss)?; let actor_loss = self .critic .forward(&states, &self.actor.forward(&states)?)? .mean_all()? .neg()?; self.actor_optim.backward_step(&actor_loss)?; self.critic.track(self.tau)?; self.actor.track(self.tau)?; Ok(()) } } // The impact of the q value of the next state on the current state's q value. const GAMMA: f64 = 0.99; // The weight for updating the target networks. const TAU: f64 = 0.005; // The capacity of the replay buffer used for sampling training data. const REPLAY_BUFFER_CAPACITY: usize = 100_000; // The training batch size for each training iteration. const TRAINING_BATCH_SIZE: usize = 100; // The total number of episodes. const MAX_EPISODES: usize = 100; // The maximum length of an episode. const EPISODE_LENGTH: usize = 200; // The number of training iterations after one episode finishes. const TRAINING_ITERATIONS: usize = 200; // Ornstein-Uhlenbeck process parameters. const MU: f64 = 0.0; const THETA: f64 = 0.15; const SIGMA: f64 = 0.1; const ACTOR_LEARNING_RATE: f64 = 1e-4; const CRITIC_LEARNING_RATE: f64 = 1e-3; pub fn run() -> Result<()> { let env = GymEnv::new("Pendulum-v1")?; println!("action space: {}", env.action_space()); println!("observation space: {:?}", env.observation_space()); let size_state = env.observation_space().iter().product::<usize>(); let size_action = env.action_space(); let mut agent = DDPG::new( &Device::Cpu, size_state, size_action, true, ACTOR_LEARNING_RATE, CRITIC_LEARNING_RATE, GAMMA, TAU, REPLAY_BUFFER_CAPACITY, OuNoise::new(MU, THETA, SIGMA, size_action)?, )?; let mut rng = rand::rng(); for episode in 0..MAX_EPISODES { // let mut state = env.reset(episode as u64)?; let mut state = env.reset(rng.random::<u64>())?; let mut total_reward = 0.0; for _ in 0..EPISODE_LENGTH { let mut action = 2.0 * agent.actions(&state)?; action = action.clamp(-2.0, 2.0); let step = env.step(vec![action])?; total_reward += step.reward; agent.remember( &state, &Tensor::new(vec![action], &Device::Cpu)?, &Tensor::new(vec![step.reward as f32], &Device::Cpu)?, &step.state, step.terminated, step.truncated, ); if step.terminated || step.truncated { break; } state = step.state; } println!("episode {episode} with total reward of {total_reward}"); for _ in 0..TRAINING_ITERATIONS { agent.train(TRAINING_BATCH_SIZE)?; } } println!("Testing..."); agent.train = false; for episode in 0..10 { // let mut state = env.reset(episode as u64)?; let mut state = env.reset(rng.random::<u64>())?; let mut total_reward = 0.0; for _ in 0..EPISODE_LENGTH { let mut action = 2.0 * agent.actions(&state)?; action = action.clamp(-2.0, 2.0); let step = env.step(vec![action])?; total_reward += step.reward; if step.terminated || step.truncated { break; } state = step.state; } println!("episode {episode} with total reward of {total_reward}"); } Ok(()) }
candle/candle-examples/examples/reinforcement-learning/ddpg.rs/0
{ "file_path": "candle/candle-examples/examples/reinforcement-learning/ddpg.rs", "repo_id": "candle", "token_count": 8545 }
39
[ { "index": 1, "color": "#787878", "label": "wall" }, { "index": 2, "color": "#B47878", "label": "building;edifice" }, { "index": 3, "color": "#06E6E6", "label": "sky" }, { "index": 4, "color": "#503232", "label": "floor;flooring" }, { "index": 5, "color": "#04C803", "label": "tree" }, { "index": 6, "color": "#787850", "label": "ceiling" }, { "index": 7, "color": "#8C8C8C", "label": "road;route" }, { "index": 8, "color": "#CC05FF", "label": "bed" }, { "index": 9, "color": "#E6E6E6", "label": "windowpane;window" }, { "index": 10, "color": "#04FA07", "label": "grass" }, { "index": 11, "color": "#E005FF", "label": "cabinet" }, { "index": 12, "color": "#EBFF07", "label": "sidewalk;pavement" }, { "index": 13, "color": "#96053D", "label": "person;individual;someone;somebody;mortal;soul" }, { "index": 14, "color": "#787846", "label": "earth;ground" }, { "index": 15, "color": "#08FF33", "label": "door;double;door" }, { "index": 16, "color": "#FF0652", "label": "table" }, { "index": 17, "color": "#8FFF8C", "label": "mountain;mount" }, { "index": 18, "color": "#CCFF04", "label": "plant;flora;plant;life" }, { "index": 19, "color": "#FF3307", "label": "curtain;drape;drapery;mantle;pall" }, { "index": 20, "color": "#CC4603", "label": "chair" }, { "index": 21, "color": "#0066C8", "label": "car;auto;automobile;machine;motorcar" }, { "index": 22, "color": "#3DE6FA", "label": "water" }, { "index": 23, "color": "#FF0633", "label": "painting;picture" }, { "index": 24, "color": "#0B66FF", "label": "sofa;couch;lounge" }, { "index": 25, "color": "#FF0747", "label": "shelf" }, { "index": 26, "color": "#FF09E0", "label": "house" }, { "index": 27, "color": "#0907E6", "label": "sea" }, { "index": 28, "color": "#DCDCDC", "label": "mirror" }, { "index": 29, "color": "#FF095C", "label": "rug;carpet;carpeting" }, { "index": 30, "color": "#7009FF", "label": "field" }, { "index": 31, "color": "#08FFD6", "label": "armchair" }, { "index": 32, "color": "#07FFE0", "label": "seat" }, { "index": 33, "color": "#FFB806", "label": "fence;fencing" }, { "index": 34, "color": "#0AFF47", "label": "desk" }, { "index": 35, "color": "#FF290A", "label": "rock;stone" }, { "index": 36, "color": "#07FFFF", "label": "wardrobe;closet;press" }, { "index": 37, "color": "#E0FF08", "label": "lamp" }, { "index": 38, "color": "#6608FF", "label": "bathtub;bathing;tub;bath;tub" }, { "index": 39, "color": "#FF3D06", "label": "railing;rail" }, { "index": 40, "color": "#FFC207", "label": "cushion" }, { "index": 41, "color": "#FF7A08", "label": "base;pedestal;stand" }, { "index": 42, "color": "#00FF14", "label": "box" }, { "index": 43, "color": "#FF0829", "label": "column;pillar" }, { "index": 44, "color": "#FF0599", "label": "signboard;sign" }, { "index": 45, "color": "#0633FF", "label": "chest;of;drawers;chest;bureau;dresser" }, { "index": 46, "color": "#EB0CFF", "label": "counter" }, { "index": 47, "color": "#A09614", "label": "sand" }, { "index": 48, "color": "#00A3FF", "label": "sink" }, { "index": 49, "color": "#8C8C8C", "label": "skyscraper" }, { "index": 50, "color": "#FA0A0F", "label": "fireplace;hearth;open;fireplace" }, { "index": 51, "color": "#14FF00", "label": "refrigerator;icebox" }, { "index": 52, "color": "#1FFF00", "label": "grandstand;covered;stand" }, { "index": 53, "color": "#FF1F00", "label": "path" }, { "index": 54, "color": "#FFE000", "label": "stairs;steps" }, { "index": 55, "color": "#99FF00", "label": "runway" }, { "index": 56, "color": "#0000FF", "label": "case;display;case;showcase;vitrine" }, { "index": 57, "color": "#FF4700", "label": "pool;table;billiard;table;snooker;table" }, { "index": 58, "color": "#00EBFF", "label": "pillow" }, { "index": 59, "color": "#00ADFF", "label": "screen;door;screen" }, { "index": 60, "color": "#1F00FF", "label": "stairway;staircase" }, { "index": 61, "color": "#0BC8C8", "label": "river" }, { "index": 62, "color": "#FF5200", "label": "bridge;span" }, { "index": 63, "color": "#00FFF5", "label": "bookcase" }, { "index": 64, "color": "#003DFF", "label": "blind;screen" }, { "index": 65, "color": "#00FF70", "label": "coffee;table;cocktail;table" }, { "index": 66, "color": "#00FF85", "label": "toilet;can;commode;crapper;pot;potty;stool;throne" }, { "index": 67, "color": "#FF0000", "label": "flower" }, { "index": 68, "color": "#FFA300", "label": "book" }, { "index": 69, "color": "#FF6600", "label": "hill" }, { "index": 70, "color": "#C2FF00", "label": "bench" }, { "index": 71, "color": "#008FFF", "label": "countertop" }, { "index": 72, "color": "#33FF00", "label": "stove;kitchen;stove;range;kitchen;range;cooking;stove" }, { "index": 73, "color": "#0052FF", "label": "palm;palm;tree" }, { "index": 74, "color": "#00FF29", "label": "kitchen;island" }, { "index": 75, "color": "#00FFAD", "label": "computer;computing;machine;computing;device;data;processor;electronic;computer;information;processing;system" }, { "index": 76, "color": "#0A00FF", "label": "swivel;chair" }, { "index": 77, "color": "#ADFF00", "label": "boat" }, { "index": 78, "color": "#00FF99", "label": "bar" }, { "index": 79, "color": "#FF5C00", "label": "arcade;machine" }, { "index": 80, "color": "#FF00FF", "label": "hovel;hut;hutch;shack;shanty" }, { "index": 81, "color": "#FF00F5", "label": "bus;autobus;coach;charabanc;double-decker;jitney;motorbus;motorcoach;omnibus;passenger;vehicle" }, { "index": 82, "color": "#FF0066", "label": "towel" }, { "index": 83, "color": "#FFAD00", "label": "light;light;source" }, { "index": 84, "color": "#FF0014", "label": "truck;motortruck" }, { "index": 85, "color": "#FFB8B8", "label": "tower" }, { "index": 86, "color": "#001FFF", "label": "chandelier;pendant;pendent" }, { "index": 87, "color": "#00FF3D", "label": "awning;sunshade;sunblind" }, { "index": 88, "color": "#0047FF", "label": "streetlight;street;lamp" }, { "index": 89, "color": "#FF00CC", "label": "booth;cubicle;stall;kiosk" }, { "index": 90, "color": "#00FFC2", "label": "television;television;receiver;television;set;tv;tv;set;idiot;box;boob;tube;telly;goggle;box" }, { "index": 91, "color": "#00FF52", "label": "airplane;aeroplane;plane" }, { "index": 92, "color": "#000AFF", "label": "dirt;track" }, { "index": 93, "color": "#0070FF", "label": "apparel;wearing;apparel;dress;clothes" }, { "index": 94, "color": "#3300FF", "label": "pole" }, { "index": 95, "color": "#00C2FF", "label": "land;ground;soil" }, { "index": 96, "color": "#007AFF", "label": "bannister;banister;balustrade;balusters;handrail" }, { "index": 97, "color": "#00FFA3", "label": "escalator;moving;staircase;moving;stairway" }, { "index": 98, "color": "#FF9900", "label": "ottoman;pouf;pouffe;puff;hassock" }, { "index": 99, "color": "#00FF0A", "label": "bottle" }, { "index": 100, "color": "#FF7000", "label": "buffet;counter;sideboard" }, { "index": 101, "color": "#8FFF00", "label": "poster;posting;placard;notice;bill;card" }, { "index": 102, "color": "#5200FF", "label": "stage" }, { "index": 103, "color": "#A3FF00", "label": "van" }, { "index": 104, "color": "#FFEB00", "label": "ship" }, { "index": 105, "color": "#08B8AA", "label": "fountain" }, { "index": 106, "color": "#8500FF", "label": "conveyer;belt;conveyor;belt;conveyer;conveyor;transporter" }, { "index": 107, "color": "#00FF5C", "label": "canopy" }, { "index": 108, "color": "#B800FF", "label": "washer;automatic;washer;washing;machine" }, { "index": 109, "color": "#FF001F", "label": "plaything;toy" }, { "index": 110, "color": "#00B8FF", "label": "swimming;pool;swimming;bath;natatorium" }, { "index": 111, "color": "#00D6FF", "label": "stool" }, { "index": 112, "color": "#FF0070", "label": "barrel;cask" }, { "index": 113, "color": "#5CFF00", "label": "basket;handbasket" }, { "index": 114, "color": "#00E0FF", "label": "waterfall;falls" }, { "index": 115, "color": "#70E0FF", "label": "tent;collapsible;shelter" }, { "index": 116, "color": "#46B8A0", "label": "bag" }, { "index": 117, "color": "#A300FF", "label": "minibike;motorbike" }, { "index": 118, "color": "#9900FF", "label": "cradle" }, { "index": 119, "color": "#47FF00", "label": "oven" }, { "index": 120, "color": "#FF00A3", "label": "ball" }, { "index": 121, "color": "#FFCC00", "label": "food;solid;food" }, { "index": 122, "color": "#FF008F", "label": "step;stair" }, { "index": 123, "color": "#00FFEB", "label": "tank;storage;tank" }, { "index": 124, "color": "#85FF00", "label": "trade;name;brand;name;brand;marque" }, { "index": 125, "color": "#FF00EB", "label": "microwave;microwave;oven" }, { "index": 126, "color": "#F500FF", "label": "pot;flowerpot" }, { "index": 127, "color": "#FF007A", "label": "animal;animate;being;beast;brute;creature;fauna" }, { "index": 128, "color": "#FFF500", "label": "bicycle;bike;wheel;cycle" }, { "index": 129, "color": "#0ABED4", "label": "lake" }, { "index": 130, "color": "#D6FF00", "label": "dishwasher;dish;washer;dishwashing;machine" }, { "index": 131, "color": "#00CCFF", "label": "screen;silver;screen;projection;screen" }, { "index": 132, "color": "#1400FF", "label": "blanket;cover" }, { "index": 133, "color": "#FFFF00", "label": "sculpture" }, { "index": 134, "color": "#0099FF", "label": "hood;exhaust;hood" }, { "index": 135, "color": "#0029FF", "label": "sconce" }, { "index": 136, "color": "#00FFCC", "label": "vase" }, { "index": 137, "color": "#2900FF", "label": "traffic;light;traffic;signal;stoplight" }, { "index": 138, "color": "#29FF00", "label": "tray" }, { "index": 139, "color": "#AD00FF", "label": "ashcan;trash;can;garbage;can;wastebin;ash;bin;ash-bin;ashbin;dustbin;trash;barrel;trash;bin" }, { "index": 140, "color": "#00F5FF", "label": "fan" }, { "index": 141, "color": "#4700FF", "label": "pier;wharf;wharfage;dock" }, { "index": 142, "color": "#7A00FF", "label": "crt;screen" }, { "index": 143, "color": "#00FFB8", "label": "plate" }, { "index": 144, "color": "#005CFF", "label": "monitor;monitoring;device" }, { "index": 145, "color": "#B8FF00", "label": "bulletin;board;notice;board" }, { "index": 146, "color": "#0085FF", "label": "shower" }, { "index": 147, "color": "#FFD600", "label": "radiator" }, { "index": 148, "color": "#19C2C2", "label": "glass;drinking;glass" }, { "index": 149, "color": "#66FF00", "label": "clock" }, { "index": 150, "color": "#5C00FF", "label": "flag" } ]
candle/candle-examples/examples/segformer/assets/labels.json/0
{ "file_path": "candle/candle-examples/examples/segformer/assets/labels.json", "repo_id": "candle", "token_count": 6397 }
40
def remove_prefix(text, prefix): return text[text.startswith(prefix) and len(prefix):] nps = {} for k, v in model.state_dict().items(): k = remove_prefix(k, 'module_list.') nps[k] = v.detach().numpy() np.savez('yolo-v3.ot', **nps)
candle/candle-examples/examples/yolo-v3/extract-weights.py/0
{ "file_path": "candle/candle-examples/examples/yolo-v3/extract-weights.py", "repo_id": "candle", "token_count": 98 }
41
/****************************************************************************** * Copyright (c) 2023, Tri Dao. ******************************************************************************/ #pragma once #include "cute/algorithm/copy.hpp" #include "cutlass/cutlass.h" #include "cutlass/layout/layout.h" #include <cutlass/numeric_types.h> using namespace cute; template<int kHeadDim_, int kBlockM_, int kBlockN_, int kNWarps_, typename elem_type=cutlass::half_t> struct Flash_kernel_traits_sm90 { #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 using Element = elem_type; static constexpr bool Has_cp_async = true; #else using Element = cutlass::half_t; static constexpr bool Has_cp_async = false; #endif using ElementAccum = float; using index_t = uint32_t; #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 800 using MMA_Atom_Arch = std::conditional_t< std::is_same_v<elem_type, cutlass::half_t>, MMA_Atom<SM80_16x8x16_F32F16F16F32_TN>, MMA_Atom<SM80_16x8x16_F32BF16BF16F32_TN> >; using ValLayoutMNK = Layout<Shape<_1, _2, _1>>; #else using MMA_Atom_Arch = MMA_Atom<SM75_16x8x8_F32F16F16F32_TN>; using ValLayoutMNK = Layout<Shape<_1, _2, _2>>; #endif #if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 750 using SmemCopyAtom = Copy_Atom<SM75_U32x4_LDSM_N, elem_type>; using SmemCopyAtomTransposed = Copy_Atom<SM75_U16x8_LDSM_T, elem_type>; #else using SmemCopyAtom = Copy_Atom<DefaultCopy, elem_type>; using SmemCopyAtomTransposed = Copy_Atom<DefaultCopy, elem_type>; #endif }; template<int kHeadDim_, int kBlockM_, int kBlockN_, int kNWarps_, bool Is_Q_in_regs_=false, bool Share_Q_K_smem_=false, typename elem_type=cutlass::half_t, typename Base=Flash_kernel_traits_sm90<kHeadDim_, kBlockM_, kBlockN_, kNWarps_, elem_type> > struct Flash_fwd_kernel_traits : public Base { using Element = typename Base::Element; using ElementAccum = typename Base::ElementAccum; using index_t = typename Base::index_t; static constexpr bool Has_cp_async = Base::Has_cp_async; using SmemCopyAtom = typename Base::SmemCopyAtom; using SmemCopyAtomTransposed = typename Base::SmemCopyAtomTransposed; static constexpr bool Share_Q_K_smem = Share_Q_K_smem_; static constexpr bool Is_Q_in_regs = Is_Q_in_regs_ || Share_Q_K_smem; // The number of threads. static constexpr int kNWarps = kNWarps_; static constexpr int kNThreads = kNWarps * 32; static constexpr int kBlockM = kBlockM_; static constexpr int kBlockN = kBlockN_; static constexpr int kHeadDim = kHeadDim_; static_assert(kHeadDim % 32 == 0); static constexpr int kBlockKSmem = kHeadDim % 64 == 0 ? 64 : 32; static constexpr int kBlockKGmem = kHeadDim % 128 == 0 ? 128 : (kHeadDim % 64 == 0 ? 64 : 32); static constexpr int kSwizzle = kBlockKSmem == 32 ? 2 : 3; using TiledMma = TiledMMA< typename Base::MMA_Atom_Arch, Layout<Shape<Int<kNWarps>,_1,_1>>, // 4x1x1 or 8x1x1 thread group typename Base::ValLayoutMNK>; // 1x2x1 or 1x2x2 value group for 16x16x16 MMA and LDSM using SmemLayoutAtomQ = decltype( composition(Swizzle<kSwizzle, 3, 3>{}, // This has to be kBlockKSmem, using kHeadDim gives wrong results for d=128 Layout<Shape<_8, Int<kBlockKSmem>>, Stride<Int<kBlockKSmem>, _1>>{})); using SmemLayoutQ = decltype(tile_to_shape( SmemLayoutAtomQ{}, Shape<Int<kBlockM>, Int<kHeadDim>>{})); using SmemLayoutKV = decltype(tile_to_shape( SmemLayoutAtomQ{}, Shape<Int<kBlockN>, Int<kHeadDim>>{})); using SmemLayoutAtomVtransposed = decltype( composition(Swizzle<kSwizzle, 3, 3>{}, // This has to be kBlockN and not 8, otherwise we get wrong results for d=128 Layout<Shape<Int<kBlockKSmem>, Int<kBlockN>>, Stride<_1, Int<kBlockKSmem>>>{})); using SmemLayoutVtransposed = decltype(tile_to_shape( SmemLayoutAtomVtransposed{}, Shape<Int<kHeadDim>, Int<kBlockN>>{})); // Maybe the VtransposeNoSwizzle just needs to have the right shape // And the strides don't matter? using SmemLayoutVtransposedNoSwizzle = decltype(SmemLayoutVtransposed{}.layout_fn()); using SmemLayoutAtomO = decltype( composition(Swizzle<kSwizzle, 3, 3>{}, Layout<Shape<Int<8>, Int<kBlockKSmem>>, Stride<Int<kBlockKSmem>, _1>>{})); using SmemLayoutO = decltype(tile_to_shape( SmemLayoutAtomO{}, Shape<Int<kBlockM>, Int<kHeadDim>>{})); using SmemCopyAtomO = Copy_Atom<DefaultCopy, elem_type>; static constexpr int kSmemQCount = size(SmemLayoutQ{}); static constexpr int kSmemKVCount = size(SmemLayoutKV{}) * 2; static constexpr int kSmemQSize = kSmemQCount * sizeof(Element); static constexpr int kSmemKVSize = kSmemKVCount * sizeof(Element); static constexpr int kSmemSize = Share_Q_K_smem ? std::max(kSmemQSize, kSmemKVSize) : kSmemQSize + kSmemKVSize; static constexpr int kGmemElemsPerLoad = sizeof(cute::uint128_t) / sizeof(Element); static_assert(kHeadDim % kGmemElemsPerLoad == 0, "kHeadDim must be a multiple of kGmemElemsPerLoad"); // Using kBlockKSmem here is 6-10% faster than kBlockKGmem for d=128 because of bank conflicts. // For example, for d=128, smem is split into 2 "pages", each page takes care of columns // 0-63 and 64-127. If we have 16 threads per row for gmem read, when we write to smem, // thread 0 - 7 will write to the first page and thread 8 - 15 will write to the second page, // to the same banks. static constexpr int kGmemThreadsPerRow = kBlockKSmem / kGmemElemsPerLoad; static_assert(kNThreads % kGmemThreadsPerRow == 0, "kNThreads must be a multiple of kGmemThreadsPerRow"); using GmemLayoutAtom = Layout<Shape <Int<kNThreads / kGmemThreadsPerRow>, Int<kGmemThreadsPerRow>>, Stride<Int<kGmemThreadsPerRow>, _1>>; // We use CACHEGLOBAL instead of CACHEALWAYS for both Q and K/V, since we won't be reading // from the same address by the same threadblock. This is slightly faster. using Gmem_copy_struct = std::conditional_t< Has_cp_async, SM80_CP_ASYNC_CACHEGLOBAL<cute::uint128_t>, DefaultCopy >; using GmemTiledCopyQKV = decltype( make_tiled_copy(Copy_Atom<Gmem_copy_struct, elem_type>{}, GmemLayoutAtom{}, Layout<Shape<_1, _8>>{})); // Val layout, 8 vals per read using GmemTiledCopyO = decltype( make_tiled_copy(Copy_Atom<DefaultCopy, elem_type>{}, GmemLayoutAtom{}, Layout<Shape<_1, _8>>{})); // Val layout, 8 vals per store static constexpr int kGmemThreadsPerRowP = kBlockN / kGmemElemsPerLoad; static_assert(kNThreads % kGmemThreadsPerRowP == 0, "kNThreads must be a multiple of kGmemThreadsPerRowP"); using GmemLayoutAtomP = Layout<Shape <Int<kNThreads / kGmemThreadsPerRowP>, Int<kGmemThreadsPerRowP>>, Stride<Int<kGmemThreadsPerRowP>, _1>>; using GmemTiledCopyP = decltype( make_tiled_copy(Copy_Atom<DefaultCopy, elem_type>{}, GmemLayoutAtomP{}, Layout<Shape<_1, _8>>{})); // Val layout, 8 vals per store }; ////////////////////////////////////////////////////////////////////////////////////////////////////
candle/candle-flash-attn/kernels/kernel_traits_sm90.h/0
{ "file_path": "candle/candle-flash-attn/kernels/kernel_traits_sm90.h", "repo_id": "candle", "token_count": 3269 }
42
#include "cuda_utils.cuh" #define BINARY_OP_OUT(TYPENAME, OUT_TYPENAME, FN_NAME, FUNC) \ extern "C" __global__ void FN_NAME( \ const size_t numel, \ const size_t num_dims, \ const size_t *dims_and_strides, \ const TYPENAME *lhs, \ const TYPENAME *rhs, \ OUT_TYPENAME *out \ ) { \ const size_t *dims = dims_and_strides; \ const size_t *lhs_strides = dims_and_strides + 1 * num_dims; \ const size_t *rhs_strides = dims_and_strides + 2 * num_dims; \ bool lhs_cont = dims_and_strides == nullptr || is_contiguous(num_dims, dims, lhs_strides); \ bool rhs_cont = dims_and_strides == nullptr || is_contiguous(num_dims, dims, rhs_strides); \ if (lhs_cont && rhs_cont) { \ for (unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; i < numel; i += blockDim.x * gridDim.x) { \ TYPENAME x = lhs[i]; \ TYPENAME y = rhs[i]; \ out[i] = FUNC; \ } \ } else if (lhs_cont) { \ for (unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; i < numel; i += blockDim.x * gridDim.x) { \ unsigned int tmp_i = i; \ unsigned int rhs_i = 0; \ for (int d = num_dims - 1; d >= 0; d--) { \ unsigned int i_dim = tmp_i % dims[d]; \ rhs_i += i_dim * rhs_strides[d]; \ tmp_i /= dims[d]; \ } \ TYPENAME x = lhs[i]; \ TYPENAME y = rhs[rhs_i]; \ out[i] = FUNC; \ } \ } else if (rhs_cont) { \ for (unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; i < numel; i += blockDim.x * gridDim.x) { \ unsigned int tmp_i = i; \ unsigned int lhs_i = 0; \ for (int d = num_dims - 1; d >= 0; d--) { \ unsigned int i_dim = tmp_i % dims[d]; \ lhs_i += i_dim * lhs_strides[d]; \ tmp_i /= dims[d]; \ } \ TYPENAME x = lhs[lhs_i]; \ TYPENAME y = rhs[i]; \ out[i] = FUNC; \ } \ } else { \ for (unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; i < numel; i += blockDim.x * gridDim.x) { \ unsigned int tmp_i = i; \ unsigned int lhs_i = 0; \ unsigned int rhs_i = 0; \ for (int d = num_dims - 1; d >= 0; d--) { \ unsigned int i_dim = tmp_i % dims[d]; \ lhs_i += i_dim * lhs_strides[d]; \ rhs_i += i_dim * rhs_strides[d]; \ tmp_i /= dims[d]; \ } \ TYPENAME x = lhs[lhs_i]; \ TYPENAME y = rhs[rhs_i]; \ out[i] = FUNC; \ } \ } \ } \ #define BINARY_OP(TYPENAME, FN_NAME, FUNC) \ BINARY_OP_OUT(TYPENAME, TYPENAME, FN_NAME, FUNC)
candle/candle-kernels/src/binary_op_macros.cuh/0
{ "file_path": "candle/candle-kernels/src/binary_op_macros.cuh", "repo_id": "candle", "token_count": 1561 }
43
use anyhow::Result; use candle_metal_kernels::GemmDType; /// This example contains some simple benchmarks so that it's easy to run them in perf etc. use clap::{Parser, Subcommand}; use half::f16; fn run_gemm(f32: bool, n: usize) -> Result<()> { const WARMUP_ITERS: usize = 2; const MIN_DUR: f64 = 4.; let device = metal::Device::system_default().unwrap(); let (b, m, n, k) = (1, n, n, n); let kernels = candle_metal_kernels::Kernels::new(); let command_queue = device.new_command_queue(); let options = metal::MTLResourceOptions::StorageModeManaged; let (lhs, rhs) = if f32 { let lhs: Vec<f32> = (0..b * m * k).map(|f| f as f32).collect(); let rhs: Vec<f32> = (0..b * n * k).map(|f| f as f32).collect(); let lhs = device.new_buffer_with_data( lhs.as_ptr() as *const core::ffi::c_void, std::mem::size_of_val(&lhs) as u64, options, ); let rhs = device.new_buffer_with_data( rhs.as_ptr() as *const core::ffi::c_void, std::mem::size_of_val(&rhs) as u64, options, ); (lhs, rhs) } else { let lhs: Vec<f16> = (0..b * m * k).map(|f| f16::from_f32(f as f32)).collect(); let rhs: Vec<f16> = (0..b * n * k).map(|f| f16::from_f32(f as f32)).collect(); let lhs = device.new_buffer_with_data( lhs.as_ptr() as *const core::ffi::c_void, std::mem::size_of_val(&lhs) as u64, options, ); let rhs = device.new_buffer_with_data( rhs.as_ptr() as *const core::ffi::c_void, std::mem::size_of_val(&rhs) as u64, options, ); (lhs, rhs) }; let (dtype, sizeof) = if f32 { (GemmDType::F32, core::mem::size_of::<f32>()) } else { (GemmDType::F16, core::mem::size_of::<f16>()) }; let output = device.new_buffer((b * m * n * sizeof) as u64, options); let mut sum_dt = 0f64; let mut iters = 0usize; for idx in 0.. { let command_buffer = command_queue.new_command_buffer(); let start_time = std::time::Instant::now(); candle_metal_kernels::call_mlx_gemm( &device, command_buffer, &kernels, dtype, (b, m, n, k), &[m * k, k, 1], 0, &lhs, &[n * k, n, 1], 0, &rhs, &output, )?; command_buffer.commit(); command_buffer.wait_until_completed(); let dt = start_time.elapsed().as_secs_f64(); if idx < WARMUP_ITERS { continue; } sum_dt += dt; iters += 1; if sum_dt > MIN_DUR { break; } } let gflops = (2 * n * n * n * iters) as f64 / (1e9 * sum_dt); println!("{dtype:?}, {n:6} gflops {gflops:.0}"); Ok(()) } #[derive(Subcommand, Debug, Clone)] enum Task { Gemm, } #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] pub struct Args { /// The benchmark to be run. #[command(subcommand)] task: Task, } fn main() -> Result<()> { let args = Args::parse(); match args.task { Task::Gemm => { for f32 in [false, true] { for n in [512, 1024, 2048, 4096] { run_gemm(f32, n)?; } } } } Ok(()) }
candle/candle-metal-kernels/examples/metal_benchmarks.rs/0
{ "file_path": "candle/candle-metal-kernels/examples/metal_benchmarks.rs", "repo_id": "candle", "token_count": 1833 }
44
use crate::utils::{BufferOffset, EncoderProvider}; use crate::{set_params, DType, Kernels, MetalKernelError, Source}; use metal::{Buffer, ComputeCommandEncoderRef, Device, MTLResourceOptions, MTLSize}; #[allow(clippy::too_many_arguments)] pub fn call_arg_sort( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, name: &'static str, nrows: usize, ncols: usize, ncols_pad: usize, src: BufferOffset, dst: &Buffer, ) -> Result<(), crate::MetalKernelError> { let pipeline = kernels.load_pipeline(device, Source::Sort, name)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!(encoder, (&src, dst, ncols as i64, ncols_pad as i64)); let thread_group_count = MTLSize { width: 1, height: nrows as u64, depth: 1, }; let thread_group_size = MTLSize { width: ncols_pad as u64, height: 1, depth: 1, }; encoder.use_resource(src.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(dst, metal::MTLResourceUsage::Write); encoder.set_threadgroup_memory_length(0, (ncols_pad * 4).max(16) as u64); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } fn mlx_dtype_str(dtype: DType) -> &'static str { match dtype { DType::U8 => "uint8", DType::U32 => "uint32", DType::I64 => "int64", DType::F16 => "float16", DType::BF16 => "bfloat16", DType::F32 => "float32", } } #[allow(clippy::too_many_arguments)] pub fn multi_block_sort( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, dtype: DType, bn: usize, tn: usize, nblocks: usize, nrows: usize, ncols: usize, src: BufferOffset, dst: &Buffer, ) -> Result<(), MetalKernelError> { let dtype_str = mlx_dtype_str(dtype); // Do allocations let el_count = nrows * ncols; let bytes_len = (el_count * dtype.size_in_bytes()) as u64; let mut dev_vals_0 = device.new_buffer(bytes_len, MTLResourceOptions::StorageModePrivate); let mut dev_vals_1 = device.new_buffer(bytes_len, MTLResourceOptions::StorageModePrivate); let mut dev_idxs_0 = device.new_buffer(el_count as u64 * 4, MTLResourceOptions::StorageModePrivate); let mut dev_idxs_1 = device.new_buffer(el_count as u64 * 4, MTLResourceOptions::StorageModePrivate); let mut block_partitions = device.new_buffer( (nrows * (nblocks + 1)) as u64 * 4, MTLResourceOptions::StorageModePrivate, ); // Prepare command encoder let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); // Do blockwise sort { let name = format!("sort_mbsort_{dtype_str}_uint32_bn{bn}_tn{tn}"); let pipeline = kernels.load_pipeline(device, Source::MlxSort, name)?; encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, ( &src, &mut dev_vals_0, &mut dev_idxs_0, /* size_sorted_axis */ ncols as i32, /* stride_sorted_axis */ 1i32, /* nc_dim */ 1i32, /* nc_shape */ nrows as i32, /* nc_str */ ncols as i32 ) ); let thread_group_count = MTLSize { width: nblocks as u64, height: nrows as u64, depth: 1, }; let thread_group_size = MTLSize { width: bn as u64, height: 1, depth: 1, }; encoder.dispatch_thread_groups(thread_group_count, thread_group_size); } // Do merges let mut ping = false; let mut merge_tiles = 2; let n_thr_per_group = usize::min(nblocks + 1, 1024); let partition_name = format!("partition_mbsort_{dtype_str}_uint32_bn{bn}_tn{tn}"); let merge_name = format!("merge_mbsort_float32_uint32_bn{bn}_tn{tn}"); while merge_tiles / 2 < nblocks { let (dev_vals_in, dev_vals_out) = if ping { (&mut dev_vals_1, &mut dev_vals_0) } else { (&mut dev_vals_0, &mut dev_vals_1) }; let (dev_idxs_in, dev_idxs_out) = if ping { (&mut dev_idxs_1, &mut dev_idxs_0) } else { (&mut dev_idxs_0, &mut dev_idxs_1) }; ping = !ping; // Do partition { let pipeline = kernels.load_pipeline(device, Source::MlxSort, partition_name.clone())?; encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, ( &mut block_partitions, &mut *dev_vals_in, &mut *dev_idxs_in, /* size_sorted_axis */ ncols as i32, /* merge_tiles */ merge_tiles as i32, /* n_blocks */ nblocks as i32 ) ); let thread_group_count = MTLSize { width: 1, height: nrows as u64, depth: 1, }; let thread_group_size = MTLSize { width: n_thr_per_group as u64, height: 1, depth: 1, }; encoder.dispatch_thread_groups(thread_group_count, thread_group_size); } // Do merge { let pipeline = kernels.load_pipeline(device, Source::MlxSort, merge_name.clone())?; encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, ( &block_partitions, &*dev_vals_in, &*dev_idxs_in, &*dev_vals_out, &*dev_idxs_out, /* size_sorted_axis */ ncols as i32, /* merge_tiles */ merge_tiles as i32, /* n_blocks */ nblocks as i32 ) ); let thread_group_count = MTLSize { width: nblocks as u64, height: nrows as u64, depth: 1, }; let thread_group_size = MTLSize { width: bn as u64, height: 1, depth: 1, }; encoder.dispatch_thread_groups(thread_group_count, thread_group_size); } merge_tiles *= 2; } let dev_idxs_out = if ping { &mut dev_idxs_1 } else { &mut dev_idxs_0 }; // Copy output with appropriate strides let copy_kernel = match dtype { DType::U8 => crate::copy2d::U8, DType::U32 => crate::copy2d::U32, DType::I64 => crate::copy2d::I64, DType::BF16 => crate::copy2d::BFLOAT, DType::F16 => crate::copy2d::HALF, DType::F32 => crate::copy2d::FLOAT, }; crate::call_copy2d( device, encoder, kernels, copy_kernel, dev_idxs_out, dst, /* d1 */ nrows, /* d2 */ ncols, /* src_s */ ncols, /* dst_s */ ncols, /* src_o_in_bytes */ 0, /*dst_o_in_bytes */ 0, )?; Ok(()) } #[allow(clippy::too_many_arguments)] pub fn block_sort( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, dtype: DType, bn: usize, tn: usize, nrows: usize, ncols: usize, src: BufferOffset, dst: &Buffer, ) -> Result<(), MetalKernelError> { let dtype_str = mlx_dtype_str(dtype); let name = format!("carg_block_sort_{dtype_str}_uint32_bn{bn}_tn{tn}"); let pipeline = kernels.load_pipeline(device, Source::MlxSort, name)?; let encoder = ep.encoder(); let encoder: &ComputeCommandEncoderRef = encoder.as_ref(); encoder.set_compute_pipeline_state(&pipeline); set_params!( encoder, ( &src, dst, ncols as i32, 1i32, 1i32, ncols as i32, ncols as i32 ) ); let thread_group_count = MTLSize { width: 1, height: nrows as u64, depth: 1, }; let thread_group_size = MTLSize { width: bn as u64, height: 1, depth: 1, }; encoder.use_resource(src.buffer, metal::MTLResourceUsage::Read); encoder.use_resource(dst, metal::MTLResourceUsage::Write); encoder.dispatch_thread_groups(thread_group_count, thread_group_size); Ok(()) } #[allow(clippy::too_many_arguments)] pub fn call_mlx_arg_sort( device: &Device, ep: impl EncoderProvider, kernels: &Kernels, dtype: DType, nrows: usize, ncols: usize, src: BufferOffset, dst: &Buffer, ) -> Result<(), MetalKernelError> { let tn = 8; let bn = match ncols.div_ceil(tn) { 257.. if dtype.size_in_bytes() <= 4 => 512, 129.. => 256, 0..129 => 128, }; let n_per_block = bn * tn; let n_blocks = ncols.div_ceil(n_per_block); if n_blocks > 1 { multi_block_sort( device, ep, kernels, dtype, bn, tn, n_blocks, nrows, ncols, src, dst, )? } else { block_sort(device, ep, kernels, dtype, bn, tn, nrows, ncols, src, dst)? } Ok(()) }
candle/candle-metal-kernels/src/sort.rs/0
{ "file_path": "candle/candle-metal-kernels/src/sort.rs", "repo_id": "candle", "token_count": 4875 }
45
use crate::benchmarks::{BenchDevice, BenchDeviceHandler}; use candle::{DType, Device, Tensor}; use candle_nn::ops::softmax_last_dim; use criterion::Throughput; use criterion::{black_box, criterion_group, Criterion}; use std::time::Instant; fn run(input: &Tensor) { let _ = softmax_last_dim(&input).unwrap(); } const B: usize = 1; const M: usize = 1024; const K: usize = 1024; fn run_softmax_benchmark(c: &mut Criterion, device: &Device, dtype: DType, name: &str) { let elements = B * M * K; let input = Tensor::rand(-1000.0f32, 1000.0f32, (B, M, K), &device) .unwrap() .to_dtype(dtype) .unwrap(); let flops = elements * dtype.size_in_bytes(); let mut group = c.benchmark_group(device.bench_name(name)); group.throughput(Throughput::Bytes(flops as u64)); group.bench_function("iter", move |b| { b.iter_custom(|iters| { let start = Instant::now(); for _i in 0..iters { run(black_box(&input)); } device.sync().unwrap(); start.elapsed() }) }); group.finish(); } fn criterion_benchmark(c: &mut Criterion) { let device = BenchDeviceHandler::new().unwrap(); for d in device.devices { run_softmax_benchmark(c, &d, DType::F32, "softmax_f32"); run_softmax_benchmark(c, &d, DType::BF16, "softmax_bf16"); run_softmax_benchmark(c, &d, DType::F16, "softmax_f16"); } } criterion_group!(benches, criterion_benchmark);
candle/candle-nn/benches/benchmarks/softmax.rs/0
{ "file_path": "candle/candle-nn/benches/benchmarks/softmax.rs", "repo_id": "candle", "token_count": 662 }
46
//! Tensor ops. //! use candle::{CpuStorage, DType, Layout, Module, Result, Shape, Tensor, D}; use rayon::prelude::*; /// Applies the softmax function to the input tensor, rescaling the element so that elements on /// a slice of fixed index on dimension `dim` are between 0 and 1 and sum to 1. /// /// ```rust /// use candle::{Tensor, Device, test_utils::to_vec2_round}; /// let a = Tensor::new(&[[0f32, 1., 0., 1.], [-2., 2., 3., -3.]], &Device::Cpu)?; /// let a = candle_nn::ops::softmax(&a, 1)?; /// assert_eq!( /// to_vec2_round(&a, 4)?, /// &[ /// [0.1345, 0.3655, 0.1345, 0.3655], /// [0.0049, 0.2671, 0.7262, 0.0018] /// ]); /// # Ok::<(), candle::Error>(()) /// ``` pub fn softmax<D: candle::shape::Dim>(xs: &Tensor, dim: D) -> Result<Tensor> { let dim = dim.to_index(xs.shape(), "softmax")?; let max = xs.max_keepdim(dim)?; let diff = xs.broadcast_sub(&max)?; let num = diff.exp()?; let den = num.sum_keepdim(dim)?; num.broadcast_div(&den) } pub fn log_softmax<D: candle::shape::Dim>(xs: &Tensor, d: D) -> Result<Tensor> { let d = d.to_index(xs.shape(), "log-softmax")?; let max = xs.max_keepdim(d)?; let diff = xs.broadcast_sub(&max)?; let sum_exp = diff.exp()?.sum_keepdim(d)?; let log_sm = diff.broadcast_sub(&sum_exp.log()?)?; Ok(log_sm) } pub fn silu(xs: &Tensor) -> Result<Tensor> { xs.silu() } pub fn swiglu(xs: &Tensor) -> Result<Tensor> { let xs = xs.chunk(2, D::Minus1)?; &xs[0].silu()? * &xs[1] } struct Sigmoid; impl candle::CustomOp1 for Sigmoid { fn name(&self) -> &'static str { "sigmoid" } fn cpu_fwd(&self, storage: &CpuStorage, layout: &Layout) -> Result<(CpuStorage, Shape)> { use candle::backend::BackendStorage; fn fwd<T: num_traits::Float>(v: T) -> T { (v.neg().exp() + T::one()).recip() } // FIXME: using `candle::map_dtype` causes compilation errors. let storage = match storage { CpuStorage::BF16(slice) => { CpuStorage::BF16(candle::cpu_backend::unary_map(slice, layout, fwd)) } CpuStorage::F16(slice) => { CpuStorage::F16(candle::cpu_backend::unary_map(slice, layout, fwd)) } CpuStorage::F32(slice) => { CpuStorage::F32(candle::cpu_backend::unary_map(slice, layout, fwd)) } CpuStorage::F64(slice) => { CpuStorage::F64(candle::cpu_backend::unary_map(slice, layout, fwd)) } _ => Err(candle::Error::UnsupportedDTypeForOp( storage.dtype(), self.name(), ))?, }; Ok((storage, layout.shape().clone())) } #[cfg(feature = "cuda")] fn cuda_fwd( &self, storage: &candle::CudaStorage, layout: &Layout, ) -> Result<(candle::CudaStorage, Shape)> { use candle::backend::BackendStorage; use candle::cuda_backend::cudarc::driver::{ CudaSlice, DeviceRepr, LaunchConfig, PushKernelArg, ValidAsZeroBits, }; use candle::cuda_backend::SlicePtrOrNull; use candle::cuda_backend::{kernel_name, kernels, Map1, WrapErr}; use candle::{CudaDevice, WithDType}; struct S; impl Map1 for S { fn f<T: DeviceRepr + WithDType + ValidAsZeroBits>( &self, src: &CudaSlice<T>, dev: &CudaDevice, layout: &Layout, ) -> Result<CudaSlice<T>> { let shape = layout.shape(); let dims = shape.dims(); let el_count = shape.elem_count(); let cfg = LaunchConfig::for_num_elems(el_count as u32); let ds = SlicePtrOrNull::params_from_layout(dev, layout)?; let src = &src.slice(layout.start_offset()..); let func = dev.get_or_load_func(&kernel_name::<T>("usigmoid"), &kernels::UNARY)?; // SAFETY: Set later by running the kernel. let out = unsafe { dev.alloc::<T>(el_count)? }; let mut builder = func.builder(); candle::builder_arg!(builder, el_count, dims.len()); ds.builder_arg(&mut builder); builder.arg(src); builder.arg(&out); // SAFETY: ffi. unsafe { builder.launch(cfg) }.w()?; Ok(out) } } let dev = storage.device(); let slice = S.map(&storage.slice, dev, layout)?; let dst = candle::CudaStorage { slice, device: dev.clone(), }; Ok((dst, layout.shape().clone())) } #[cfg(feature = "metal")] fn metal_fwd( &self, storage: &candle::MetalStorage, layout: &Layout, ) -> Result<(candle::MetalStorage, Shape)> { use candle::backend::BackendStorage; use candle::MetalError; let device = storage.device(); let dtype = storage.dtype(); let shape = layout.shape(); let el_count = shape.elem_count(); let buffer = device.new_buffer(el_count, dtype, "sigmoid")?; let command_buffer = device.command_buffer()?; command_buffer.set_label("sigmoid"); let src = candle_metal_kernels::BufferOffset { buffer: storage.buffer(), offset_in_bytes: layout.start_offset() * storage.dtype().size_in_bytes(), }; match (el_count % 2, dtype, layout.is_contiguous()) { (0, DType::BF16 | DType::F16, true) => { use candle_metal_kernels::unary::contiguous_tiled; let kernel_name = match dtype { DType::F16 => contiguous_tiled::sigmoid::HALF, DType::F32 => contiguous_tiled::sigmoid::FLOAT, DType::BF16 => contiguous_tiled::sigmoid::BFLOAT, dtype => { candle::bail!( "Metal contiguous_tiled unary sigmoid {dtype:?} not implemented" ) } }; candle_metal_kernels::call_unary_contiguous_tiled( device.metal_device(), &command_buffer, device.kernels(), kernel_name, el_count, src, &buffer, ) .map_err(MetalError::from)?; } (_, _, true) => { use candle_metal_kernels::unary::contiguous; let kernel_name = match dtype { DType::F16 => contiguous::sigmoid::HALF, DType::F32 => contiguous::sigmoid::FLOAT, DType::BF16 => contiguous::sigmoid::BFLOAT, dtype => { candle::bail!("Metal contiguous unary sigmoid {dtype:?} not implemented") } }; candle_metal_kernels::call_unary_contiguous( device.metal_device(), &command_buffer, device.kernels(), kernel_name, el_count, src, &buffer, ) .map_err(MetalError::from)?; } (_, _, false) => { use candle_metal_kernels::unary::strided; let kernel_name = match dtype { DType::F16 => strided::sigmoid::HALF, DType::F32 => strided::sigmoid::FLOAT, DType::BF16 => strided::sigmoid::BFLOAT, dtype => { candle::bail!("Metal strided unary sigmoid {dtype:?} not implemented") } }; let dst = candle_metal_kernels::BufferOffset::zero_offset(&buffer); candle_metal_kernels::call_unary_strided( device.metal_device(), &command_buffer, device.kernels(), kernel_name, layout.dims(), src, layout.stride(), dst, ) .map_err(MetalError::from)?; } } let new_storage = candle::MetalStorage::new(buffer, device.clone(), el_count, dtype); Ok((new_storage, layout.shape().clone())) } fn bwd(&self, _arg: &Tensor, res: &Tensor, grad_res: &Tensor) -> Result<Option<Tensor>> { // d/dx sigmoid(x) = (1 - sigmoid(x)) * sigmoid(x) let d_dx_sigmoid = res.ones_like()?.sub(res)?.mul(res)?; Ok(Some(grad_res.mul(&d_dx_sigmoid)?)) } } pub fn sigmoid(xs: &Tensor) -> Result<Tensor> { xs.apply_op1(Sigmoid) } pub fn hard_sigmoid(xs: &Tensor) -> Result<Tensor> { // TODO: Should we have a specialized op for this? ((xs + 3.0)? / 6.0)?.clamp(0f32, 1f32) } pub fn leaky_relu(xs: &Tensor, negative_slope: f64) -> Result<Tensor> { let zeros = xs.zeros_like()?; xs.maximum(&zeros)? + xs.minimum(&zeros)? * negative_slope } pub fn selu(xs: &Tensor, alpha: f32, gamma: f32) -> Result<Tensor> { let is_pos = xs.gt(0f32)?; let alpha_t = Tensor::full(alpha, xs.dims(), xs.device())?; let neg = xs.exp()?.mul(&alpha_t)?.sub(&alpha_t)?; let selu = is_pos.where_cond(xs, &neg)?; let gamma_t = Tensor::full(gamma, xs.dims(), xs.device())?; selu.broadcast_mul(&gamma_t) } pub fn dropout(xs: &Tensor, drop_p: f32) -> Result<Tensor> { // This implementation is inefficient as it stores the full mask for the backward pass. // Instead we could just store the seed and have a specialized kernel that would both // generate the random mask and apply it. // Another easier optimization would be to be able to generate boolean mask using just a bit of // entropy per element rather than generating a full float per element. if !(0. ..1.).contains(&drop_p) { candle::bail!("dropout probability has to be in [0, 1), got {drop_p}") } let rand = Tensor::rand(0f32, 1f32, xs.shape(), xs.device())?; let scale = 1.0 / (1.0 - drop_p as f64); let drop_p = Tensor::new(drop_p, xs.device())?.broadcast_as(xs.shape())?; let mask = (rand.ge(&drop_p)?.to_dtype(xs.dtype())? * scale)?; xs * mask } #[derive(Clone, Debug)] pub struct Dropout { drop_p: f32, } impl Dropout { pub fn new(drop_p: f32) -> Dropout { Self { drop_p } } pub fn forward(&self, xs: &Tensor, train: bool) -> Result<Tensor> { if train { dropout(xs, self.drop_p) } else { Ok(xs.clone()) } } } impl candle::ModuleT for Dropout { fn forward_t(&self, xs: &Tensor, train: bool) -> Result<Tensor> { self.forward(xs, train) } } struct SoftmaxLastDim; impl candle::CustomOp1 for SoftmaxLastDim { fn name(&self) -> &'static str { "softmax-last-dim" } fn cpu_fwd(&self, storage: &CpuStorage, layout: &Layout) -> Result<(CpuStorage, Shape)> { fn softmax<T: candle::WithDType + num_traits::Float>( src: &[T], layout: &Layout, ) -> Result<(CpuStorage, Shape)> { let src = match layout.contiguous_offsets() { None => candle::bail!("input has to be contiguous"), Some((o1, o2)) => &src[o1..o2], }; let el_count = layout.shape().elem_count(); let dims = layout.shape().dims(); let dim_m1 = dims[dims.len() - 1]; let mut dst = vec![T::zero(); el_count]; src.par_chunks(dim_m1) .zip(dst.par_chunks_mut(dim_m1)) .for_each(|(src, dst)| { let mut max = T::neg_infinity(); unsafe { T::vec_reduce_max(src.as_ptr(), &mut max, dim_m1) }; for (s, d) in src.iter().zip(dst.iter_mut()) { *d = (*s - max).exp(); } let mut sum_exp = T::zero(); unsafe { T::vec_reduce_sum(dst.as_ptr(), &mut sum_exp, dim_m1) }; for d in dst.iter_mut() { *d /= sum_exp } }); let storage = candle::WithDType::to_cpu_storage_owned(dst); Ok((storage, Shape::from_dims(dims))) } match storage { CpuStorage::BF16(slice) => softmax::<half::bf16>(slice, layout), CpuStorage::F16(slice) => softmax::<half::f16>(slice, layout), CpuStorage::F32(slice) => softmax::<f32>(slice, layout), CpuStorage::F64(slice) => softmax::<f64>(slice, layout), _ => candle::bail!("unsupported dtype for softmax {:?}", storage), } } #[cfg(feature = "cuda")] fn cuda_fwd( &self, storage: &candle::CudaStorage, layout: &Layout, ) -> Result<(candle::CudaStorage, Shape)> { use candle::cuda_backend::cudarc::driver::{ CudaSlice, DeviceRepr, LaunchConfig, PushKernelArg, }; use candle::cuda_backend::{kernel_name, kernels, Map1, WrapErr}; use candle::{CudaDevice, WithDType}; struct S; impl Map1 for S { fn f<T: DeviceRepr + WithDType>( &self, src: &CudaSlice<T>, dev: &CudaDevice, layout: &Layout, ) -> Result<CudaSlice<T>> { let src = match layout.contiguous_offsets() { None => candle::bail!("input has to be contiguous"), Some((o1, o2)) => src.slice(o1..o2), }; let el = layout.shape().elem_count(); let dims = layout.shape().dims(); let dim_m1 = dims[dims.len() - 1]; let (n_rows, n_cols) = (el / dim_m1, dim_m1); let cfg = LaunchConfig { grid_dim: (n_rows as u32, 1, 1), block_dim: (1, 32, 1), shared_mem_bytes: 0, }; let func = dev.get_or_load_func(&kernel_name::<T>("softmax"), &kernels::REDUCE)?; // SAFETY: Set later by running the kernel. let dst = unsafe { dev.alloc::<T>(el)? }; let mut builder = func.builder(); builder.arg(&src); builder.arg(&dst); candle::builder_arg!(builder, n_cols as i32); // SAFETY: ffi. unsafe { builder.launch(cfg) }.w()?; Ok(dst) } } use candle::backend::BackendStorage; let dev = storage.device(); let slice = S.map(&storage.slice, dev, layout)?; let dst = candle::cuda_backend::CudaStorage { slice, device: dev.clone(), }; Ok((dst, layout.shape().clone())) } #[cfg(feature = "metal")] fn metal_fwd( &self, storage: &candle::MetalStorage, layout: &Layout, ) -> Result<(candle::MetalStorage, Shape)> { use candle::backend::BackendStorage; let device = storage.device(); let command_buffer = device.command_buffer()?; let kernels = device.kernels(); let name = match storage.dtype() { DType::F32 => "softmax_f32", DType::F16 => "softmax_f16", DType::BF16 => "softmax_bf16", dtype => candle::bail!("softmax-last-dim is not implemented for {dtype:?}"), }; let n = layout.stride().len(); if !(layout.is_contiguous() && layout.stride()[n - 1] == 1) { candle::bail!("Non contiguous softmax-last-dim is not implemented"); } let last_dim = layout.dims()[layout.shape().rank() - 1]; let elem_count = layout.shape().elem_count(); let output = device.new_buffer(elem_count, storage.dtype(), "softmax")?; candle_metal_kernels::call_last_softmax( device.metal_device(), &command_buffer, kernels, name, elem_count, last_dim, storage.buffer(), layout.start_offset() * storage.dtype().size_in_bytes(), &output, ) .map_err(candle::Error::wrap)?; let newstorage = candle::MetalStorage::new(output, device.clone(), elem_count, storage.dtype()); Ok((newstorage, layout.shape().clone())) } } pub fn softmax_last_dim(xs: &Tensor) -> Result<Tensor> { xs.apply_op1_no_bwd(&SoftmaxLastDim) } #[derive(Debug, Clone)] struct RmsNorm { eps: f32, } impl candle::CustomOp2 for RmsNorm { fn name(&self) -> &'static str { "rms-norm" } fn cpu_fwd( &self, s1: &CpuStorage, l1: &Layout, s2: &CpuStorage, l2: &Layout, ) -> Result<(CpuStorage, Shape)> { use candle::backend::BackendStorage; let eps = self.eps; fn inner< T: candle::WithDType + num_traits::Float + num_traits::AsPrimitive<f32> + num_traits::FromPrimitive, >( src: &[T], layout: &Layout, alpha: &[T], alpha_layout: &Layout, eps: f32, ) -> Result<(CpuStorage, Shape)> { let src = match layout.contiguous_offsets() { None => candle::bail!("input has to be contiguous"), Some((o1, o2)) => &src[o1..o2], }; let alpha = match alpha_layout.contiguous_offsets() { None => candle::bail!("alpha has to be contiguous"), Some((o1, o2)) => &alpha[o1..o2], }; let el_count = layout.shape().elem_count(); let dims = layout.shape().dims(); let dim_m1 = dims[dims.len() - 1]; let mut dst = vec![T::zero(); el_count]; src.par_chunks(dim_m1) .zip(dst.par_chunks_mut(dim_m1)) .for_each(|(src, dst)| { let sum2 = src .iter() .map(|&v| { let v = v.as_(); v * v }) .sum::<f32>(); let m = (sum2 / dim_m1 as f32 + eps).sqrt(); let m = T::from_f32(m).unwrap_or_else(T::nan); for ((d, s), alpha) in dst.iter_mut().zip(src.iter()).zip(alpha) { *d = *s / m * *alpha } }); let storage = candle::WithDType::to_cpu_storage_owned(dst); Ok((storage, Shape::from_dims(dims))) } use CpuStorage as C; match (s1, s2) { (C::BF16(s1), C::BF16(s2)) => inner::<half::bf16>(s1, l1, s2, l2, eps), (C::F16(s1), C::F16(s2)) => inner::<half::f16>(s1, l1, s2, l2, eps), (C::F32(s1), C::F32(s2)) => inner::<f32>(s1, l1, s2, l2, eps), _ => candle::bail!("unsupported dtype for rmsnorm {:?}", s1.dtype()), } } #[cfg(feature = "cuda")] fn cuda_fwd( &self, s1: &candle::CudaStorage, l1: &Layout, s2: &candle::CudaStorage, l2: &Layout, ) -> Result<(candle::CudaStorage, Shape)> { use candle::cuda_backend::cudarc::driver::{ CudaSlice, DeviceRepr, LaunchConfig, PushKernelArg, }; use candle::cuda_backend::{kernel_name, kernels, Map2, WrapErr}; use candle::{CudaDevice, WithDType}; struct S { eps: f32, } impl Map2 for S { fn f<T: DeviceRepr + WithDType>( &self, src: &CudaSlice<T>, layout: &Layout, alpha: &CudaSlice<T>, alpha_layout: &Layout, dev: &CudaDevice, ) -> Result<CudaSlice<T>> { let src = match layout.contiguous_offsets() { None => candle::bail!("input has to be contiguous"), Some((o1, o2)) => src.slice(o1..o2), }; let alpha = match alpha_layout.contiguous_offsets() { None => candle::bail!("alpha has to be contiguous"), Some((o1, o2)) => alpha.slice(o1..o2), }; let el = layout.shape().elem_count(); let dims = layout.shape().dims(); let dim_m1 = dims[dims.len() - 1]; let (n_rows, n_cols) = (el / dim_m1, dim_m1); let block_size = if n_cols < 1024 { 32 } else { 1024 }; let cfg = LaunchConfig { grid_dim: (n_rows as u32, 1, 1), block_dim: (block_size, 1, 1), shared_mem_bytes: 0, }; let func = dev.get_or_load_func(&kernel_name::<T>("rmsnorm"), &kernels::REDUCE)?; // SAFETY: Set later by running the kernel. let dst = unsafe { dev.alloc::<T>(el)? }; let mut builder = func.builder(); builder.arg(&src); builder.arg(&dst); builder.arg(&alpha); candle::builder_arg!(builder, n_cols as i32, block_size as i32, self.eps); // SAFETY: ffi. unsafe { builder.launch(cfg) }.w()?; Ok(dst) } } use candle::backend::BackendStorage; let dev = s1.device(); let slice = S { eps: self.eps }.map(&s1.slice, l1, &s2.slice, l2, dev)?; let dst = candle::cuda_backend::CudaStorage { slice, device: dev.clone(), }; Ok((dst, l1.shape().clone())) } #[cfg(feature = "metal")] fn metal_fwd( &self, s1: &candle::MetalStorage, l1: &Layout, s2: &candle::MetalStorage, l2: &Layout, ) -> Result<(candle::MetalStorage, Shape)> { use candle::backend::BackendStorage; let device = s1.device(); let command_buffer = device.command_buffer()?; let kernels = device.kernels(); let name = match (s1.dtype(), s2.dtype()) { (DType::F32, DType::F32) => "rmsnorm_f32", (DType::F16, DType::F16) => "rmsnorm_f16", (DType::BF16, DType::BF16) => "rmsnorm_bf16", (dt1, dt2) => candle::bail!("rmsnorm is not implemented for {dt1:?} {dt2:?}"), }; if !(l1.is_contiguous() && l2.is_contiguous()) { candle::bail!("Non contiguous rmsnorm is not implemented"); } let last_dim = l1.dims()[l1.shape().rank() - 1]; let elem_count = l1.shape().elem_count(); let output = device.new_buffer(elem_count, s1.dtype(), "rmsnorm")?; candle_metal_kernels::call_rms_norm( device.metal_device(), &command_buffer, kernels, name, elem_count, last_dim, self.eps, s1.buffer(), l1.start_offset() * s1.dtype().size_in_bytes(), s2.buffer(), l2.start_offset() * s2.dtype().size_in_bytes(), &output, ) .map_err(candle::Error::wrap)?; let newstorage = candle::MetalStorage::new(output, device.clone(), elem_count, s1.dtype()); Ok((newstorage, l1.shape().clone())) } } pub fn rms_norm_slow(x: &Tensor, alpha: &Tensor, eps: f32) -> Result<Tensor> { let x_dtype = x.dtype(); let internal_dtype = match x_dtype { DType::F16 | DType::BF16 => DType::F32, d => d, }; let hidden_size = x.dim(D::Minus1)?; let x = x.to_dtype(internal_dtype)?; let norm_x = (x.sqr()?.sum_keepdim(D::Minus1)? / hidden_size as f64)?; let x_normed = x.broadcast_div(&(norm_x + eps as f64)?.sqrt()?)?; x_normed.to_dtype(x_dtype)?.broadcast_mul(alpha) } pub fn rms_norm(xs: &Tensor, alpha: &Tensor, eps: f32) -> Result<Tensor> { let hidden_size_xs = xs.dim(D::Minus1)?; let hidden_size_alpha = alpha.dims1()?; if hidden_size_xs != hidden_size_alpha { candle::bail!( "shape mismatch in rms-norm {:?} {:?}", xs.shape(), alpha.shape() ) } xs.apply_op2_no_bwd(alpha, &RmsNorm { eps }) } #[derive(Debug, Clone)] struct LayerNorm { eps: f32, } impl candle::CustomOp3 for LayerNorm { fn name(&self) -> &'static str { "layer-norm" } fn cpu_fwd( &self, s1: &CpuStorage, l1: &Layout, s2: &CpuStorage, l2: &Layout, s3: &CpuStorage, l3: &Layout, ) -> Result<(CpuStorage, Shape)> { use candle::backend::BackendStorage; let eps = self.eps; fn inner< T: candle::WithDType + num_traits::Float + num_traits::AsPrimitive<f32> + num_traits::FromPrimitive, >( src: &[T], layout: &Layout, alpha: &[T], alpha_layout: &Layout, beta: &[T], beta_layout: &Layout, eps: f32, ) -> Result<(CpuStorage, Shape)> { let src = match layout.contiguous_offsets() { None => candle::bail!("input has to be contiguous"), Some((o1, o2)) => &src[o1..o2], }; let alpha = match alpha_layout.contiguous_offsets() { None => candle::bail!("alpha has to be contiguous"), Some((o1, o2)) => &alpha[o1..o2], }; let beta = match beta_layout.contiguous_offsets() { None => candle::bail!("beta has to be contiguous"), Some((o1, o2)) => &beta[o1..o2], }; let el_count = layout.shape().elem_count(); let dims = layout.shape().dims(); let dim_m1 = dims[dims.len() - 1]; let mut dst = vec![T::zero(); el_count]; src.par_chunks(dim_m1) .zip(dst.par_chunks_mut(dim_m1)) .for_each(|(src, dst)| { let mut sum = 0f32; let mut sum2 = 0f32; for v in src { let v = v.as_(); sum += v; sum2 += v * v; } let mean = sum / dim_m1 as f32; let var = sum2 / dim_m1 as f32 - mean * mean; let inv_std = (var + eps).sqrt().recip(); for ((d, s), (alpha, beta)) in dst.iter_mut().zip(src.iter()).zip(alpha.iter().zip(beta)) { let alpha = alpha.as_(); let beta = beta.as_(); let d_ = (s.as_() - mean) * inv_std * alpha + beta; *d = T::from_f32(d_).unwrap_or_else(T::nan); } }); let storage = candle::WithDType::to_cpu_storage_owned(dst); Ok((storage, Shape::from_dims(dims))) } use CpuStorage as C; match (s1, s2, s3) { (C::BF16(s1), C::BF16(s2), C::BF16(s3)) => { inner::<half::bf16>(s1, l1, s2, l2, s3, l3, eps) } (C::F16(s1), C::F16(s2), C::F16(s3)) => inner::<half::f16>(s1, l1, s2, l2, s3, l3, eps), (C::F32(s1), C::F32(s2), C::F32(s3)) => inner::<f32>(s1, l1, s2, l2, s3, l3, eps), _ => candle::bail!("unsupported dtype for rmsnorm {:?}", s1.dtype()), } } #[cfg(feature = "cuda")] fn cuda_fwd( &self, s1: &candle::CudaStorage, l1: &Layout, s2: &candle::CudaStorage, l2: &Layout, s3: &candle::CudaStorage, l3: &Layout, ) -> Result<(candle::CudaStorage, Shape)> { use candle::cuda_backend::cudarc::driver::{ CudaSlice, DeviceRepr, LaunchConfig, PushKernelArg, }; use candle::cuda_backend::{kernel_name, kernels, Map3, WrapErr}; use candle::{CudaDevice, WithDType}; struct S { eps: f32, } impl Map3 for S { fn f<T: DeviceRepr + WithDType>( &self, src: &CudaSlice<T>, layout: &Layout, alpha: &CudaSlice<T>, alpha_layout: &Layout, beta: &CudaSlice<T>, beta_layout: &Layout, dev: &CudaDevice, ) -> Result<CudaSlice<T>> { let src = match layout.contiguous_offsets() { None => candle::bail!("input has to be contiguous"), Some((o1, o2)) => src.slice(o1..o2), }; let alpha = match alpha_layout.contiguous_offsets() { None => candle::bail!("alpha has to be contiguous"), Some((o1, o2)) => alpha.slice(o1..o2), }; let beta = match beta_layout.contiguous_offsets() { None => candle::bail!("beta has to be contiguous"), Some((o1, o2)) => beta.slice(o1..o2), }; let el = layout.shape().elem_count(); let dims = layout.shape().dims(); let dim_m1 = dims[dims.len() - 1]; let (n_rows, n_cols) = (el / dim_m1, dim_m1); let block_size = if n_cols < 1024 { 32 } else { 1024 }; let cfg = LaunchConfig { grid_dim: (n_rows as u32, 1, 1), block_dim: (block_size, 1, 1), shared_mem_bytes: 0, }; let func = dev.get_or_load_func(&kernel_name::<T>("layernorm"), &kernels::REDUCE)?; // SAFETY: Set later by running the kernel. let dst = unsafe { dev.alloc::<T>(el)? }; let mut builder = func.builder(); builder.arg(&src); builder.arg(&dst); builder.arg(&alpha); builder.arg(&beta); candle::builder_arg!(builder, n_cols as i32, block_size as i32, self.eps); // SAFETY: ffi. unsafe { builder.launch(cfg) }.w()?; Ok(dst) } } use candle::backend::BackendStorage; let dev = s1.device(); let slice = S { eps: self.eps }.map(&s1.slice, l1, &s2.slice, l2, &s3.slice, l3, dev)?; let dst = candle::cuda_backend::CudaStorage { slice, device: dev.clone(), }; Ok((dst, l1.shape().clone())) } #[cfg(feature = "metal")] fn metal_fwd( &self, s1: &candle::MetalStorage, l1: &Layout, s2: &candle::MetalStorage, l2: &Layout, s3: &candle::MetalStorage, l3: &Layout, ) -> Result<(candle::MetalStorage, Shape)> { use candle::backend::BackendStorage; let device = s1.device(); let command_buffer = device.command_buffer()?; let kernels = device.kernels(); let name = match (s1.dtype(), s2.dtype(), s3.dtype()) { (DType::F32, DType::F32, DType::F32) => "layernorm_f32", (DType::F16, DType::F16, DType::F16) => "layernorm_f16", (DType::BF16, DType::BF16, DType::BF16) => "layernorm_bf16", (dt1, dt2, dt3) => { candle::bail!("layernorm is not implemented for {dt1:?} {dt2:?} {dt3:?}") } }; if !(l1.is_contiguous() && l2.is_contiguous() && l3.is_contiguous()) { candle::bail!("Non contiguous layernorm is not implemented"); } let last_dim = l1.dims()[l1.shape().rank() - 1]; let elem_count = l1.shape().elem_count(); let output = device.new_buffer(elem_count, s1.dtype(), "layernorm")?; candle_metal_kernels::call_layer_norm( device.metal_device(), &command_buffer, kernels, name, elem_count, last_dim, self.eps, s1.buffer(), l1.start_offset() * s1.dtype().size_in_bytes(), s2.buffer(), l2.start_offset() * s2.dtype().size_in_bytes(), s3.buffer(), l3.start_offset() * s3.dtype().size_in_bytes(), &output, ) .map_err(candle::Error::wrap)?; let newstorage = candle::MetalStorage::new(output, device.clone(), elem_count, s1.dtype()); Ok((newstorage, l1.shape().clone())) } } pub fn layer_norm_slow(x: &Tensor, alpha: &Tensor, beta: &Tensor, eps: f32) -> Result<Tensor> { let x_dtype = x.dtype(); let internal_dtype = match x_dtype { DType::F16 | DType::BF16 => DType::F32, d => d, }; let hidden_size = x.dim(D::Minus1)?; let x = x.to_dtype(internal_dtype)?; let x = { let mean_x = (x.sum_keepdim(D::Minus1)? / hidden_size as f64)?; x.broadcast_sub(&mean_x)? }; let norm_x = (x.sqr()?.sum_keepdim(D::Minus1)? / hidden_size as f64)?; let x_normed = x.broadcast_div(&(norm_x + eps as f64)?.sqrt()?)?; x_normed .to_dtype(x_dtype)? .broadcast_mul(alpha)? .broadcast_add(beta) } pub fn layer_norm(xs: &Tensor, alpha: &Tensor, beta: &Tensor, eps: f32) -> Result<Tensor> { let hidden_size_xs = xs.dim(D::Minus1)?; let hidden_size_alpha = alpha.dims1()?; let hidden_size_beta = beta.dims1()?; if hidden_size_xs != hidden_size_alpha || hidden_size_xs != hidden_size_beta { candle::bail!( "shape mismatch in layer-norm src: {:?} alpha: {:?} beta: {:?}", xs.shape(), alpha.shape(), beta.shape() ) } xs.apply_op3_no_bwd(alpha, beta, &LayerNorm { eps }) } // https://pytorch.org/docs/stable/generated/torch.nn.PixelShuffle.html pub fn pixel_shuffle(xs: &Tensor, upscale_factor: usize) -> Result<Tensor> { let (b_size, c, h, w) = xs.dims4()?; let out_c = c / upscale_factor / upscale_factor; xs.reshape((b_size, out_c, upscale_factor, upscale_factor, h, w))? .permute((0, 1, 4, 2, 5, 3))? .reshape((b_size, out_c, h * upscale_factor, w * upscale_factor)) } pub fn pixel_unshuffle(xs: &Tensor, downscale_factor: usize) -> Result<Tensor> { let (b_size, c, h, w) = xs.dims4()?; let out_c = c * downscale_factor * downscale_factor; xs.reshape(( b_size, c, h / downscale_factor, downscale_factor, w / downscale_factor, downscale_factor, ))? .permute((0, 1, 3, 5, 2, 4))? .reshape((b_size, out_c, h / downscale_factor, w / downscale_factor)) } // https://pytorch.org/docs/stable/generated/torch.nn.ReplicationPad2d.html pub fn replication_pad2d(xs: &Tensor, pad: usize) -> Result<Tensor> { match pad { 0 => Ok(xs.clone()), 1 => { let (_b_size, _c, h, w) = xs.dims4()?; let (first, last) = (xs.narrow(3, 0, 1)?, xs.narrow(3, w - 1, 1)?); let xs = Tensor::cat(&[&first, xs, &last], 3)?; let (first, last) = (xs.narrow(2, 0, 1)?, xs.narrow(2, h - 1, 1)?); Tensor::cat(&[&first, &xs, &last], 2) } n => candle::bail!("replication-pad with a size of {n} is not supported"), } } #[derive(Clone, Debug)] pub struct Identity; impl Identity { pub fn new() -> Identity { Self } } impl Default for Identity { fn default() -> Self { Self } } impl Module for Identity { fn forward(&self, xs: &Tensor) -> Result<Tensor> { Ok(xs.clone()) } } #[allow(dead_code)] struct Sdpa { scale: f32, softcapping: f32, } impl candle::CustomOp3 for Sdpa { fn name(&self) -> &'static str { "metal-sdpa" } fn cpu_fwd( &self, _s1: &CpuStorage, _l1: &Layout, _s2: &CpuStorage, _l2: &Layout, _s3: &CpuStorage, _l3: &Layout, ) -> Result<(CpuStorage, Shape)> { candle::bail!("SDPA has no cpu impl") } #[cfg(feature = "metal")] fn metal_fwd( &self, q: &candle::MetalStorage, q_l: &Layout, k: &candle::MetalStorage, k_l: &Layout, v: &candle::MetalStorage, v_l: &Layout, ) -> Result<(candle::MetalStorage, Shape)> { use candle::backend::BackendStorage; use candle_metal_kernels::SdpaDType; let device = q.device(); let out_dims = vec![q_l.dim(0)?, q_l.dim(1)?, q_l.dim(2)?, v_l.dim(3)?]; let elem_count: usize = out_dims.iter().product(); let output = device.new_buffer(elem_count, q.dtype(), "sdpa_o")?; // q,k must have matching emb dim if q_l.dim(D::Minus1)? != k_l.dim(D::Minus1)? { candle::bail!("`q` and `k` last dims must match"); } // k,v must have matching n kv heads if v_l.dim(D::Minus(3))? != k_l.dim(D::Minus(3))? { candle::bail!("`k` and `v` head dims must match"); } // n_heads % n_kv_heads == 0; n_heads >= 1, n_kv_heads >= 1. if q_l.dim(D::Minus(3))? % k_l.dim(D::Minus(3))? != 0 { candle::bail!("query `n_heads` must be a multiple of `n_kv_heads`"); } let k_head = k_l.dim(D::Minus1)?; let q_head = q_l.dim(D::Minus1)?; let q_seq = q_l.dim(2)?; let mut implementation_supports_use_case = q_head == k_head; let supported_head_dim = q_head == 32 || q_head == 64 || q_head == 96 || q_head == 128 || q_head == 256; const SDPA_FULL_THRESHOLD: usize = 2; let supports_sdpa_full = q_seq >= SDPA_FULL_THRESHOLD && supported_head_dim && q_head == k_head; let supports_sdpa_vector = q_seq == 1 && supported_head_dim; implementation_supports_use_case &= supports_sdpa_full || supports_sdpa_vector; if !supported_head_dim { candle::bail!( "Meta SDPA does not support q head dim {q_head}: q dims {:?}, k dims {:?}, v dims {:?}.", q_l.dims(), k_l.dims(), v_l.dims() ); } if !implementation_supports_use_case { candle::bail!( "Meta SDPA does not support q dims {:?}, k dims {:?}, v dims {:?}.", q_l.dims(), k_l.dims(), v_l.dims() ); } for t in [k.dtype(), v.dtype()] { if q.dtype() != t { candle::bail!("all q, k, v dtypes must match."); } } let itype = match q.dtype() { DType::BF16 => SdpaDType::BF16, DType::F16 => SdpaDType::F16, DType::F32 => SdpaDType::F32, other => candle::bail!("unsupported sdpa type {other:?}"), }; let command_buffer = q.device().command_buffer()?; if supports_sdpa_vector { // Route to the 2 pass fused attention if the k seqlen is large. // https://github.com/ml-explore/mlx/pull/1597 const TWO_PASS_K_THRESHOLD: usize = 1024; if k_l.dim(2)? >= TWO_PASS_K_THRESHOLD { let mut intermediate_shape = [ &out_dims[0..out_dims.len() - 2], &[candle_metal_kernels::SDPA_2PASS_BLOCKS], &[out_dims[out_dims.len() - 1]], ] .concat(); let intermediate = device.new_buffer( intermediate_shape.iter().product::<usize>(), DType::F32, "sdpa_2pass_intermediate", )?; let _ = intermediate_shape.pop().unwrap(); let sums = device.new_buffer( intermediate_shape.iter().product::<usize>(), DType::F32, "sdpa_2pass_sums", )?; let maxs = device.new_buffer( intermediate_shape.iter().product::<usize>(), DType::F32, "sdpa_2pass_maxs", )?; command_buffer.set_label("vector_attention"); candle_metal_kernels::call_sdpa_vector_2pass( q.device().device(), &command_buffer, q.device().kernels(), q_l.start_offset(), q_l.dims(), q.buffer(), k_l.start_offset(), k_l.dims(), k_l.stride(), k.buffer(), v_l.start_offset(), v_l.stride(), v.buffer(), &output, &intermediate, &sums, &maxs, self.scale, self.softcapping, itype, ) .map_err(candle::Error::wrap)?; } else { command_buffer.set_label("vector_attention"); candle_metal_kernels::call_sdpa_vector( q.device().device(), &command_buffer, q.device().kernels(), q_l.start_offset(), q_l.dims(), q.buffer(), k_l.start_offset(), k_l.dims(), k_l.stride(), k.buffer(), v_l.start_offset(), v_l.stride(), v.buffer(), &output, self.scale, self.softcapping, itype, ) .map_err(candle::Error::wrap)?; } } else if supports_sdpa_full { if q_l.dim(2)? != k_l.dim(2)? { candle::bail!( "query and key sequence length must be equal if using full metal sdpa" ) } command_buffer.set_label("full_attention"); candle_metal_kernels::call_sdpa_full( q.device().device(), &command_buffer, q.device().kernels(), q_l.start_offset(), q_l.dims(), q.buffer(), k_l.start_offset(), k.buffer(), v_l.start_offset(), v.buffer(), &output, self.scale, self.softcapping, itype, ) .map_err(candle::Error::wrap)?; } else { candle::bail!("must be vector or full sdpa kernel"); } let newstorage = candle::MetalStorage::new(output, device.clone(), elem_count, q.dtype()); Ok((newstorage, Shape::from_dims(&out_dims))) } } /// Scaled dot product attention with a fused kernel. /// /// Computes softmax(qk^T*scale)v. /// /// **Inputs shapes:** /// - `q`: (bs, qhead, seq, hidden) /// - `k`: (bs, kv_head, kv_seq, hidden) /// - `k`: (bs, kv_head, kv_seq, v_hidden) /// - `scale` is applied before softmax. /// - If `softcapping` != 1.0: /// - Computation is: softmax(tanh(qk^T*scale/cap)*cap)v /// /// **Output shape:** (bs, qhead, seq, v_hidden) /// /// **Supported head dims:** 32, 64, 96, 128, 256. /// /// ## On Metal: /// - If `seq` == 1: /// - Use a vectorized kernel /// - Supports `seq` != `kv_seq` (cross attn. support) /// - Supports GQA when `qhead` is a multiple of `kv_head` /// - Otherwise: /// - Use an alternate kernel /// - Requires `seq` == `kv_seq` /// - GQA is not supported (requires `qhead` == `kv_head`) pub fn sdpa(q: &Tensor, k: &Tensor, v: &Tensor, scale: f32, softcapping: f32) -> Result<Tensor> { q.apply_op3_no_bwd(k, v, &Sdpa { scale, softcapping }) }
candle/candle-nn/src/ops.rs/0
{ "file_path": "candle/candle-nn/src/ops.rs", "repo_id": "candle", "token_count": 24239 }
47
#[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; use candle::{test_utils::to_vec2_round, DType, Device, Result, Tensor}; use candle_nn::RNN; /* The following test can be verified against PyTorch using the following snippet. import torch from torch import nn lstm = nn.LSTM(2, 3, 1) lstm.weight_ih_l0 = torch.nn.Parameter(torch.arange(0., 24.).reshape(12, 2).cos()) lstm.weight_hh_l0 = torch.nn.Parameter(torch.arange(0., 36.).reshape(12, 3).sin()) lstm.bias_ih_l0 = torch.nn.Parameter(torch.tensor([-1., 1., -0.5, 2, -1, 1, -0.5, 2, -1, 1, -0.5, 2])) lstm.bias_hh_l0 = torch.nn.Parameter(torch.tensor([-1., 1., -0.5, 2, -1, 1, -0.5, 2, -1, 1, -0.5, 2]).cos()) state = torch.zeros((1, 3)), torch.zeros((1, 3)) for inp in [3., 1., 4., 1., 5., 9., 2.]: inp = torch.tensor([[inp, inp * 0.5]]) _out, state = lstm(inp, state) print(state) # (tensor([[ 0.9919, 0.1738, -0.1451]], grad_fn=...), tensor([[ 5.7250, 0.4458, -0.2908]], grad_fn=...)) */ #[test] fn lstm() -> Result<()> { let cpu = &Device::Cpu; let w_ih = Tensor::arange(0f32, 24f32, cpu)?.reshape((12, 2))?; let w_ih = w_ih.cos()?; let w_hh = Tensor::arange(0f32, 36f32, cpu)?.reshape((12, 3))?; let w_hh = w_hh.sin()?; let b_ih = Tensor::new( &[-1f32, 1., -0.5, 2., -1., 1., -0.5, 2., -1., 1., -0.5, 2.], cpu, )?; let b_hh = b_ih.cos()?; let tensors: std::collections::HashMap<_, _> = [ ("weight_ih_l0".to_string(), w_ih), ("weight_hh_l0".to_string(), w_hh), ("bias_ih_l0".to_string(), b_ih), ("bias_hh_l0".to_string(), b_hh), ] .into_iter() .collect(); let vb = candle_nn::VarBuilder::from_tensors(tensors, DType::F32, cpu); let lstm = candle_nn::lstm(2, 3, Default::default(), vb)?; let mut state = lstm.zero_state(1)?; for inp in [3f32, 1., 4., 1., 5., 9., 2.] { let inp = Tensor::new(&[[inp, inp * 0.5]], cpu)?; state = lstm.step(&inp, &state)? } let h = state.h(); let c = state.c(); assert_eq!(to_vec2_round(h, 4)?, &[[0.9919, 0.1738, -0.1451]]); assert_eq!(to_vec2_round(c, 4)?, &[[5.725, 0.4458, -0.2908]]); Ok(()) } /* The following test can be verified against PyTorch using the following snippet. import torch from torch import nn gru = nn.GRU(2, 3, 1) gru.weight_ih_l0 = torch.nn.Parameter(torch.arange(0., 18.).reshape(9, 2).cos()) gru.weight_hh_l0 = torch.nn.Parameter(torch.arange(0., 27.).reshape(9, 3).sin()) gru.bias_ih_l0 = torch.nn.Parameter(torch.tensor([-1., 1., -0.5, 2, -1, 1, -0.5, 2, -1])) gru.bias_hh_l0 = torch.nn.Parameter(torch.tensor([-1., 1., -0.5, 2, -1, 1, -0.5, 2, -1]).cos()) state = torch.zeros((1, 3)) for inp in [3., 1., 4., 1., 5., 9., 2.]: inp = torch.tensor([[inp, inp * 0.5]]) _out, state = gru(inp, state) print(state) # tensor([[ 0.0579, 0.8836, -0.9991]], grad_fn=<SqueezeBackward1>) */ #[test] fn gru() -> Result<()> { let cpu = &Device::Cpu; let w_ih = Tensor::arange(0f32, 18f32, cpu)?.reshape((9, 2))?; let w_ih = w_ih.cos()?; let w_hh = Tensor::arange(0f32, 27f32, cpu)?.reshape((9, 3))?; let w_hh = w_hh.sin()?; let b_ih = Tensor::new(&[-1f32, 1., -0.5, 2., -1., 1., -0.5, 2., -1.], cpu)?; let b_hh = b_ih.cos()?; let tensors: std::collections::HashMap<_, _> = [ ("weight_ih_l0".to_string(), w_ih), ("weight_hh_l0".to_string(), w_hh), ("bias_ih_l0".to_string(), b_ih), ("bias_hh_l0".to_string(), b_hh), ] .into_iter() .collect(); let vb = candle_nn::VarBuilder::from_tensors(tensors, DType::F32, cpu); let gru = candle_nn::gru(2, 3, Default::default(), vb)?; let mut state = gru.zero_state(1)?; for inp in [3f32, 1., 4., 1., 5., 9., 2.] { let inp = Tensor::new(&[[inp, inp * 0.5]], cpu)?; state = gru.step(&inp, &state)? } let h = state.h(); assert_eq!(to_vec2_round(h, 4)?, &[[0.0579, 0.8836, -0.9991]]); Ok(()) }
candle/candle-nn/tests/rnn.rs/0
{ "file_path": "candle/candle-nn/tests/rnn.rs", "repo_id": "candle", "token_count": 2010 }
48
import logging try: from .candle import * except ImportError as e: # If we are in development mode, or we did not bundle the DLLs, we try to locate them here # PyO3 wont give us any information about what DLLs are missing, so we can only try to load # the DLLs and re-import the module logging.warning("DLLs were not bundled with this package. Trying to locate them...") import os import platform def locate_cuda_dlls(): logging.warning("Locating CUDA DLLs...") # Try to locate CUDA_PATH environment variable cuda_path = os.environ.get("CUDA_PATH", None) if cuda_path: logging.warning(f"Found CUDA_PATH environment variable: {cuda_path}") if platform.system() == "Windows": cuda_path = os.path.join(cuda_path, "bin") else: cuda_path = os.path.join(cuda_path, "lib64") logging.warning(f"Adding {cuda_path} to DLL search path...") os.add_dll_directory(cuda_path) else: logging.warning("CUDA_PATH environment variable not found!") def locate_mkl_dlls(): # Try to locate ONEAPI_ROOT environment variable oneapi_root = os.environ.get("ONEAPI_ROOT", None) if oneapi_root: if platform.system() == "Windows": mkl_path = os.path.join( oneapi_root, "compiler", "latest", "windows", "redist", "intel64_win", "compiler" ) else: mkl_path = os.path.join(oneapi_root, "mkl", "latest", "lib", "intel64") logging.warning(f"Adding {mkl_path} to DLL search path...") os.add_dll_directory(mkl_path) else: logging.warning("ONEAPI_ROOT environment variable not found!") locate_cuda_dlls() locate_mkl_dlls() try: from .candle import * except ImportError as inner_e: raise ImportError("Could not locate DLLs. Please check the documentation for more information.") __doc__ = candle.__doc__ if hasattr(candle, "__all__"): __all__ = candle.__all__
candle/candle-pyo3/py_src/candle/__init__.py/0
{ "file_path": "candle/candle-pyo3/py_src/candle/__init__.py", "repo_id": "candle", "token_count": 919 }
49
from typing import TypeVar, Union, Sequence _T = TypeVar("_T") _ArrayLike = Union[ _T, Sequence[_T], Sequence[Sequence[_T]], Sequence[Sequence[Sequence[_T]]], Sequence[Sequence[Sequence[Sequence[_T]]]], ] CPU: str = "cpu" CUDA: str = "cuda" Device = TypeVar("Device", CPU, CUDA) Scalar = Union[int, float] Index = Union[int, slice, None, "Ellipsis"] Shape = Union[int, Sequence[int]]
candle/candle-pyo3/py_src/candle/typing/__init__.py/0
{ "file_path": "candle/candle-pyo3/py_src/candle/typing/__init__.py", "repo_id": "candle", "token_count": 166 }
50
from candle import Tensor from candle import rand import pytest def test_absolute_shapes_are_valid(): a = rand((10, 20)) assert a.shape == (10, 20) b = rand(10, 20) assert b.shape == (10, 20) pytest.raises(OverflowError, lambda: rand((10, 20, -1))) pytest.raises(OverflowError, lambda: rand(-1, 20)) pytest.raises(TypeError, lambda: rand("foo", True)) def test_relative_shapes_are_valid(): a = rand(10, 20) a = a.reshape((1, -1)) assert a.shape == (1, 200) b = rand(10, 20) b = b.reshape(-1, 1) assert b.shape == (200, 1) c = rand(10, 20) pytest.raises(TypeError, lambda: c.reshape(1, "foo")) pytest.raises(ValueError, lambda: c.reshape(1, -2)) pytest.raises(ValueError, lambda: c.reshape((-2, 1))) pytest.raises(ValueError, lambda: c.reshape((0, 1))) pytest.raises(ValueError, lambda: c.reshape((1, -1, -1)))
candle/candle-pyo3/tests/native/test_shape.py/0
{ "file_path": "candle/candle-pyo3/tests/native/test_shape.py", "repo_id": "candle", "token_count": 385 }
51
//! Chinese contrastive Language-Image Pre-Training //! //! Chinese contrastive Language-Image Pre-Training (CLIP) is an architecture trained on //! pairs of images with related texts. //! //! - 💻 [Chinese-CLIP](https://github.com/OFA-Sys/Chinese-CLIP) //! - 💻 [GH](https://github.com/huggingface/transformers/blob/5af7d41e49bbfc8319f462eb45253dcb3863dfb7/src/transformers/models/chinese_clip/modeling_chinese_clip.py_ use candle::{Context, DType, IndexOp, Module, Result, Shape, Tensor, D}; use candle_nn as nn; use super::{Activation, EncoderConfig}; #[derive(Clone, Debug)] pub struct ChineseClipVisionConfig { pub hidden_size: usize, pub intermediate_size: usize, pub projection_dim: usize, pub num_hidden_layers: usize, pub num_attention_heads: usize, pub num_channels: usize, pub image_size: usize, pub patch_size: usize, pub hidden_act: Activation, pub layer_norm_eps: f64, pub attention_dropout: f32, pub initializer_range: f32, pub initializer_factor: f32, } impl Default for ChineseClipVisionConfig { fn default() -> Self { ChineseClipVisionConfig { hidden_size: 768, intermediate_size: 3072, projection_dim: 512, num_hidden_layers: 12, num_attention_heads: 12, num_channels: 3, image_size: 224, patch_size: 32, hidden_act: Activation::QuickGelu, layer_norm_eps: 1e-5, attention_dropout: 0.0, initializer_range: 0.02, initializer_factor: 1.0, } } } impl ChineseClipVisionConfig { /// [referer](https://huggingface.co/OFA-Sys/chinese-clip-vit-base-patch16/blob/main/config.json) pub fn clip_vit_base_patch16() -> Self { Self { hidden_size: 768, intermediate_size: 3072, projection_dim: 512, num_hidden_layers: 12, num_attention_heads: 12, num_channels: 3, image_size: 224, patch_size: 16, hidden_act: Activation::QuickGelu, layer_norm_eps: 1e-5, attention_dropout: 0.0, initializer_range: 0.02, initializer_factor: 1.0, } } } #[derive(Clone, Debug)] pub struct ChineseClipVisionEmbeddings { patch_embedding: nn::Conv2d, position_ids: Tensor, class_embedding: Tensor, position_embedding: nn::Embedding, } impl ChineseClipVisionEmbeddings { pub fn new(var: nn::VarBuilder, config: &ChineseClipVisionConfig) -> Result<Self> { let embed_dim = config.hidden_size; // originally nn.Parameter let class_embedding = if var.contains_tensor("class_embedding") { var.get(embed_dim, "class_embedding")? } else { Tensor::randn(0f32, 1f32, embed_dim, var.device())? }; let num_patches = (config.image_size / config.patch_size).pow(2); let num_positions = num_patches + 1; let position_ids = Tensor::arange(0, num_positions as i64, var.device())?; let conv2dconfig = nn::Conv2dConfig { stride: config.patch_size, ..Default::default() }; let position_embedding = nn::embedding(num_positions, embed_dim, var.pp("position_embedding"))?; let patch_embedding = nn::conv2d_no_bias( config.num_channels, embed_dim, config.patch_size, conv2dconfig, var.pp("patch_embedding"), )?; Ok(Self { patch_embedding, position_ids, class_embedding, position_embedding, }) } } impl Module for ChineseClipVisionEmbeddings { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let batch_size = xs.shape().dims(); let patch_embeds = self .patch_embedding .forward(xs)? .flatten_from(2)? .transpose(1, 2)?; let shape = Shape::from((batch_size[0], 1, self.class_embedding.dim(D::Minus1)?)); let class_embeds = self.class_embedding.expand(shape)?; let embeddings = Tensor::cat(&[class_embeds, patch_embeds], 1)?; let position_embedding = self.position_embedding.forward(&self.position_ids)?; embeddings.broadcast_add(&position_embedding) } } #[derive(Clone, Debug)] struct ChineseClipVisionAttention { k_proj: nn::Linear, v_proj: nn::Linear, q_proj: nn::Linear, out_proj: nn::Linear, head_dim: usize, scale: f64, num_attention_heads: usize, } impl ChineseClipVisionAttention { fn new(var: nn::VarBuilder, config: &EncoderConfig) -> Result<Self> { let embed_dim = config.embed_dim(); let num_attention_heads = config.num_attention_heads(); let k_proj = nn::linear(embed_dim, embed_dim, var.pp("k_proj"))?; let v_proj = nn::linear(embed_dim, embed_dim, var.pp("v_proj"))?; let q_proj = nn::linear(embed_dim, embed_dim, var.pp("q_proj"))?; let out_proj = nn::linear(embed_dim, embed_dim, var.pp("out_proj"))?; let head_dim = embed_dim / num_attention_heads; let scale = (head_dim as f64).powf(-0.5); Ok(ChineseClipVisionAttention { k_proj, v_proj, q_proj, out_proj, head_dim, scale, num_attention_heads, }) } fn shape(&self, xs: &Tensor, seq_len: usize, bsz: usize) -> Result<Tensor> { xs.reshape((bsz, seq_len, self.num_attention_heads, self.head_dim))? .transpose(1, 2)? .contiguous() } fn forward(&self, xs: &Tensor, causal_attention_mask: Option<&Tensor>) -> Result<Tensor> { let in_dtype = xs.dtype(); let (bsz, seq_len, embed_dim) = xs.dims3()?; let proj_shape = (bsz * self.num_attention_heads, seq_len, self.head_dim); let query_states = self .shape(&(self.q_proj.forward(xs)? * self.scale)?, seq_len, bsz)? .reshape(proj_shape)? .to_dtype(DType::F32)?; let key_states = self .shape(&self.k_proj.forward(xs)?, seq_len, bsz)? .reshape(proj_shape)? .to_dtype(DType::F32)?; let value_states = self .shape(&self.v_proj.forward(xs)?, seq_len, bsz)? .reshape(proj_shape)? .to_dtype(DType::F32)?; let attn_weights = query_states.matmul(&key_states.transpose(1, 2)?)?; let src_len = key_states.dim(1)?; let attn_weights = if let Some(causal_attention_mask) = causal_attention_mask { attn_weights .reshape((bsz, self.num_attention_heads, seq_len, src_len))? .broadcast_add(causal_attention_mask)? .reshape((bsz * self.num_attention_heads, seq_len, src_len))? } else { attn_weights }; let attn_weights = nn::ops::softmax(&attn_weights, D::Minus1)?; let attn_output = attn_weights.matmul(&value_states)?.to_dtype(in_dtype)?; let attn_output = attn_output .reshape((bsz, self.num_attention_heads, seq_len, self.head_dim))? .transpose(1, 2)? .reshape((bsz, seq_len, embed_dim))?; self.out_proj.forward(&attn_output) } } #[derive(Clone, Debug)] struct ChineseClipVisionMlp { fc1: nn::Linear, fc2: nn::Linear, activation: Activation, } impl ChineseClipVisionMlp { fn new(var: nn::VarBuilder, config: &EncoderConfig) -> Result<Self> { let fc1 = nn::linear( config.embed_dim(), config.intermediate_size(), var.pp("fc1"), )?; let fc2 = nn::linear( config.intermediate_size(), config.embed_dim(), var.pp("fc2"), )?; Ok(ChineseClipVisionMlp { fc1, fc2, activation: config.activation(), }) } } impl ChineseClipVisionMlp { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let xs = self.fc1.forward(xs)?; self.fc2.forward(&self.activation.forward(&xs)?) } } #[derive(Clone, Debug)] struct ChineseClipVisionEncoderLayer { self_attn: ChineseClipVisionAttention, layer_norm1: nn::LayerNorm, mlp: ChineseClipVisionMlp, layer_norm2: nn::LayerNorm, } impl ChineseClipVisionEncoderLayer { fn new(var: nn::VarBuilder, config: &EncoderConfig) -> Result<Self> { let self_attn = ChineseClipVisionAttention::new(var.pp("self_attn"), config)?; let layer_norm1 = nn::layer_norm( config.embed_dim(), config.layer_norm_eps(), var.pp("layer_norm1"), )?; let mlp = ChineseClipVisionMlp::new(var.pp("mlp"), config)?; let layer_norm2 = nn::layer_norm( config.embed_dim(), config.layer_norm_eps(), var.pp("layer_norm2"), )?; Ok(ChineseClipVisionEncoderLayer { self_attn, layer_norm1, mlp, layer_norm2, }) } fn forward(&self, xs: &Tensor, causal_attention_mask: Option<&Tensor>) -> Result<Tensor> { let residual = xs; let xs = self.layer_norm1.forward(xs)?; let xs = self.self_attn.forward(&xs, causal_attention_mask)?; let xs = (xs + residual)?; let residual = &xs; let xs = self.layer_norm2.forward(&xs)?; let xs = self.mlp.forward(&xs)?; xs + residual } } #[derive(Clone, Debug)] pub struct ChineseClipVisionEncoder { layers: Vec<ChineseClipVisionEncoderLayer>, } impl ChineseClipVisionEncoder { pub fn new(var: nn::VarBuilder, config: &EncoderConfig) -> Result<Self> { let vs = var.pp("layers"); let mut layers: Vec<ChineseClipVisionEncoderLayer> = Vec::new(); for index in 0..config.num_hidden_layers() { let layer = ChineseClipVisionEncoderLayer::new(vs.pp(index.to_string()), config)?; layers.push(layer) } Ok(ChineseClipVisionEncoder { layers }) } pub fn forward(&self, xs: &Tensor, causal_attention_mask: Option<&Tensor>) -> Result<Tensor> { let mut xs = xs.clone(); for layer in self.layers.iter() { xs = layer.forward(&xs, causal_attention_mask)?; } Ok(xs) } // required by LLaVA pub fn output_hidden_states( &self, xs: &Tensor, causal_attention_mask: Option<&Tensor>, ) -> Result<Vec<Tensor>> { let mut xs = xs.clone(); let mut hidden_states = Vec::new(); for layer in self.layers.iter() { xs = layer.forward(&xs, causal_attention_mask)?; hidden_states.push(xs.clone()); } Ok(hidden_states) } } #[derive(Clone, Debug)] pub struct ChineseClipVisionTransformer { embeddings: ChineseClipVisionEmbeddings, encoder: ChineseClipVisionEncoder, pre_layer_norm: nn::LayerNorm, final_layer_norm: nn::LayerNorm, } impl ChineseClipVisionTransformer { pub fn new(var: nn::VarBuilder, config: &ChineseClipVisionConfig) -> Result<Self> { let embed_dim = config.hidden_size; let embeddings = ChineseClipVisionEmbeddings::new(var.pp("embeddings"), config)?; let pre_layer_norm = nn::layer_norm(embed_dim, config.layer_norm_eps, var.pp("pre_layrnorm"))?; let encoder = ChineseClipVisionEncoder::new( var.pp("encoder"), &EncoderConfig::Vision(config.clone()), )?; let final_layer_norm = nn::layer_norm(embed_dim, config.layer_norm_eps, var.pp("post_layernorm"))?; Ok(Self { embeddings, encoder, final_layer_norm, pre_layer_norm, }) } // required by LLaVA pub fn output_hidden_states(&self, pixel_values: &Tensor) -> Result<Vec<Tensor>> { let hidden_states = pixel_values .apply(&self.embeddings)? .apply(&self.pre_layer_norm)?; let mut result = self.encoder.output_hidden_states(&hidden_states, None)?; let encoder_outputs = result.last().context("no last")?; let pooled_output = encoder_outputs.i((.., 0, ..))?; result.push(self.final_layer_norm.forward(&pooled_output)?.clone()); Ok(result) } } impl Module for ChineseClipVisionTransformer { fn forward(&self, pixel_values: &Tensor) -> Result<Tensor> { let hidden_states = pixel_values .apply(&self.embeddings)? .apply(&self.pre_layer_norm)?; let encoder_outputs = self.encoder.forward(&hidden_states, None)?; // referer: https://github.com/huggingface/transformers/blob/f6fa0f0bf0796ac66f201f23bdb8585de1609add/src/transformers/models/clip/modeling_clip.py#L787 let pooled_output = encoder_outputs.i((.., 0, ..))?; self.final_layer_norm.forward(&pooled_output) } }
candle/candle-transformers/src/models/chinese_clip/vision_model.rs/0
{ "file_path": "candle/candle-transformers/src/models/chinese_clip/vision_model.rs", "repo_id": "candle", "token_count": 6262 }
52
//! Implementation of EfficientBert, an efficient variant of BERT for computer vision tasks. //! //! See: //! - ["EfficientBERT: Progressively Searching Multilayer Perceptron Architectures for BERT"](https://arxiv.org/abs/2201.00462) //! use candle::{Context, Result, Tensor, D}; use candle_nn as nn; use nn::{Module, VarBuilder}; // Based on the Python version from torchvision. // https://github.com/pytorch/vision/blob/0d75d9e5516f446c9c0ef93bd4ed9fea13992d06/torchvision/models/efficientnet.py#L47 #[derive(Debug, Clone, Copy)] pub struct MBConvConfig { expand_ratio: f64, kernel: usize, stride: usize, input_channels: usize, out_channels: usize, num_layers: usize, } fn make_divisible(v: f64, divisor: usize) -> usize { let min_value = divisor; let new_v = usize::max( min_value, (v + divisor as f64 * 0.5) as usize / divisor * divisor, ); if (new_v as f64) < 0.9 * v { new_v + divisor } else { new_v } } fn bneck_confs(width_mult: f64, depth_mult: f64) -> Vec<MBConvConfig> { let bneck_conf = |e, k, s, i, o, n| { let input_channels = make_divisible(i as f64 * width_mult, 8); let out_channels = make_divisible(o as f64 * width_mult, 8); let num_layers = (n as f64 * depth_mult).ceil() as usize; MBConvConfig { expand_ratio: e, kernel: k, stride: s, input_channels, out_channels, num_layers, } }; vec![ bneck_conf(1., 3, 1, 32, 16, 1), bneck_conf(6., 3, 2, 16, 24, 2), bneck_conf(6., 5, 2, 24, 40, 2), bneck_conf(6., 3, 2, 40, 80, 3), bneck_conf(6., 5, 1, 80, 112, 3), bneck_conf(6., 5, 2, 112, 192, 4), bneck_conf(6., 3, 1, 192, 320, 1), ] } impl MBConvConfig { pub fn b0() -> Vec<Self> { bneck_confs(1.0, 1.0) } pub fn b1() -> Vec<Self> { bneck_confs(1.0, 1.1) } pub fn b2() -> Vec<Self> { bneck_confs(1.1, 1.2) } pub fn b3() -> Vec<Self> { bneck_confs(1.2, 1.4) } pub fn b4() -> Vec<Self> { bneck_confs(1.4, 1.8) } pub fn b5() -> Vec<Self> { bneck_confs(1.6, 2.2) } pub fn b6() -> Vec<Self> { bneck_confs(1.8, 2.6) } pub fn b7() -> Vec<Self> { bneck_confs(2.0, 3.1) } } /// Conv2D with same padding. #[derive(Debug)] struct Conv2DSame { conv2d: nn::Conv2d, s: usize, k: usize, } impl Conv2DSame { fn new( vb: VarBuilder, i: usize, o: usize, k: usize, stride: usize, groups: usize, bias: bool, ) -> Result<Self> { let conv_config = nn::Conv2dConfig { stride, groups, ..Default::default() }; let conv2d = if bias { nn::conv2d(i, o, k, conv_config, vb)? } else { nn::conv2d_no_bias(i, o, k, conv_config, vb)? }; Ok(Self { conv2d, s: stride, k, }) } } impl Module for Conv2DSame { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let s = self.s; let k = self.k; let (_, _, ih, iw) = xs.dims4()?; let oh = ih.div_ceil(s); let ow = iw.div_ceil(s); let pad_h = usize::max((oh - 1) * s + k - ih, 0); let pad_w = usize::max((ow - 1) * s + k - iw, 0); if pad_h > 0 || pad_w > 0 { let xs = xs.pad_with_zeros(2, pad_h / 2, pad_h - pad_h / 2)?; let xs = xs.pad_with_zeros(3, pad_w / 2, pad_w - pad_w / 2)?; self.conv2d.forward(&xs) } else { self.conv2d.forward(xs) } } } #[derive(Debug)] struct ConvNormActivation { conv2d: Conv2DSame, bn2d: nn::BatchNorm, activation: bool, } impl ConvNormActivation { fn new( vb: VarBuilder, i: usize, o: usize, k: usize, stride: usize, groups: usize, ) -> Result<Self> { let conv2d = Conv2DSame::new(vb.pp("0"), i, o, k, stride, groups, false)?; let bn2d = nn::batch_norm(o, 1e-3, vb.pp("1"))?; Ok(Self { conv2d, bn2d, activation: true, }) } fn no_activation(self) -> Self { Self { activation: false, ..self } } } impl Module for ConvNormActivation { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let xs = self.conv2d.forward(xs)?.apply_t(&self.bn2d, false)?; if self.activation { swish(&xs) } else { Ok(xs) } } } #[derive(Debug)] struct SqueezeExcitation { fc1: Conv2DSame, fc2: Conv2DSame, } impl SqueezeExcitation { fn new(vb: VarBuilder, in_channels: usize, squeeze_channels: usize) -> Result<Self> { let fc1 = Conv2DSame::new(vb.pp("fc1"), in_channels, squeeze_channels, 1, 1, 1, true)?; let fc2 = Conv2DSame::new(vb.pp("fc2"), squeeze_channels, in_channels, 1, 1, 1, true)?; Ok(Self { fc1, fc2 }) } } impl Module for SqueezeExcitation { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let residual = xs; // equivalent to adaptive_avg_pool2d([1, 1]) let xs = xs.mean_keepdim(D::Minus2)?.mean_keepdim(D::Minus1)?; let xs = self.fc1.forward(&xs)?; let xs = swish(&xs)?; let xs = self.fc2.forward(&xs)?; let xs = nn::ops::sigmoid(&xs)?; residual.broadcast_mul(&xs) } } #[derive(Debug)] struct MBConv { expand_cna: Option<ConvNormActivation>, depthwise_cna: ConvNormActivation, squeeze_excitation: SqueezeExcitation, project_cna: ConvNormActivation, config: MBConvConfig, } impl MBConv { fn new(vb: VarBuilder, c: MBConvConfig) -> Result<Self> { let vb = vb.pp("block"); let exp = make_divisible(c.input_channels as f64 * c.expand_ratio, 8); let expand_cna = if exp != c.input_channels { Some(ConvNormActivation::new( vb.pp("0"), c.input_channels, exp, 1, 1, 1, )?) } else { None }; let start_index = if expand_cna.is_some() { 1 } else { 0 }; let depthwise_cna = ConvNormActivation::new(vb.pp(start_index), exp, exp, c.kernel, c.stride, exp)?; let squeeze_channels = usize::max(1, c.input_channels / 4); let squeeze_excitation = SqueezeExcitation::new(vb.pp(start_index + 1), exp, squeeze_channels)?; let project_cna = ConvNormActivation::new(vb.pp(start_index + 2), exp, c.out_channels, 1, 1, 1)? .no_activation(); Ok(Self { expand_cna, depthwise_cna, squeeze_excitation, project_cna, config: c, }) } } impl Module for MBConv { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let use_res_connect = self.config.stride == 1 && self.config.input_channels == self.config.out_channels; let ys = match &self.expand_cna { Some(expand_cna) => expand_cna.forward(xs)?, None => xs.clone(), }; let ys = self.depthwise_cna.forward(&ys)?; let ys = self.squeeze_excitation.forward(&ys)?; let ys = self.project_cna.forward(&ys)?; if use_res_connect { ys + xs } else { Ok(ys) } } } fn swish(s: &Tensor) -> Result<Tensor> { s * nn::ops::sigmoid(s)? } #[derive(Debug)] pub struct EfficientNet { init_cna: ConvNormActivation, blocks: Vec<MBConv>, final_cna: ConvNormActivation, classifier: nn::Linear, } impl EfficientNet { pub fn new(p: VarBuilder, configs: Vec<MBConvConfig>, nclasses: usize) -> Result<Self> { let f_p = p.pp("features"); let first_in_c = configs[0].input_channels; let last_out_c = configs.last().context("no last")?.out_channels; let final_out_c = 4 * last_out_c; let init_cna = ConvNormActivation::new(f_p.pp(0), 3, first_in_c, 3, 2, 1)?; let nconfigs = configs.len(); let mut blocks = vec![]; for (index, cnf) in configs.into_iter().enumerate() { let f_p = f_p.pp(index + 1); for r_index in 0..cnf.num_layers { let cnf = if r_index == 0 { cnf } else { MBConvConfig { input_channels: cnf.out_channels, stride: 1, ..cnf } }; blocks.push(MBConv::new(f_p.pp(r_index), cnf)?) } } let final_cna = ConvNormActivation::new(f_p.pp(nconfigs + 1), last_out_c, final_out_c, 1, 1, 1)?; let classifier = nn::linear(final_out_c, nclasses, p.pp("classifier.1"))?; Ok(Self { init_cna, blocks, final_cna, classifier, }) } } impl Module for EfficientNet { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let mut xs = self.init_cna.forward(xs)?; for block in self.blocks.iter() { xs = block.forward(&xs)? } let xs = self.final_cna.forward(&xs)?; // Equivalent to adaptive_avg_pool2d([1, 1]) -> squeeze(-1) -> squeeze(-1) let xs = xs.mean(D::Minus1)?.mean(D::Minus1)?; self.classifier.forward(&xs) } }
candle/candle-transformers/src/models/efficientnet.rs/0
{ "file_path": "candle/candle-transformers/src/models/efficientnet.rs", "repo_id": "candle", "token_count": 5204 }
53
//! Granite is a Long Context Transformer Language Model. //! //! A high performance transformer model optimized for efficient processing //! of very long context sequences //! //! Based on implementation from [Nod.ai](https://github.com/nod-ai/granite) use super::with_tracing::{linear_no_bias as linear, Linear, RmsNorm}; use candle::{DType, Device, IndexOp, Result, Tensor, D}; use candle_nn::{embedding, Embedding, Module, VarBuilder}; use std::{collections::HashMap, f32::consts::PI}; pub const DEFAULT_MAX_SEQ_LEN: usize = 4096; #[derive(Debug, Clone, serde::Deserialize, Default)] pub enum GraniteRopeType { #[serde(rename = "granite")] Granite, #[default] #[serde(rename = "default")] Default, } #[derive(Debug, Clone, serde::Deserialize, Default)] pub struct GraniteRopeConfig { pub factor: f32, pub low_freq_factor: f32, pub high_freq_factor: f32, pub original_max_position_embeddings: usize, pub rope_type: GraniteRopeType, } #[derive(Debug, Clone, serde::Deserialize)] #[serde(untagged)] pub enum GraniteEosToks { Single(u32), Multiple(Vec<u32>), } #[derive(Debug, Clone, serde::Deserialize)] pub struct GraniteConfig { pub hidden_size: usize, pub intermediate_size: usize, pub vocab_size: usize, pub num_hidden_layers: usize, pub num_attention_heads: usize, pub num_key_value_heads: Option<usize>, pub rms_norm_eps: f64, #[serde(default = "default_rope")] pub rope_theta: f32, pub bos_token_id: Option<u32>, pub eos_token_id: Option<GraniteEosToks>, pub rope_scaling: Option<GraniteRopeConfig>, pub max_position_embeddings: usize, } impl GraniteConfig { pub fn num_key_value_heads(&self) -> usize { self.num_key_value_heads.unwrap_or(self.num_attention_heads) } } fn default_rope() -> f32 { 10_000.0 } impl GraniteConfig { pub fn into_config(self, use_flash_attn: bool) -> Config { Config { hidden_size: self.hidden_size, intermediate_size: self.intermediate_size, vocab_size: self.vocab_size, num_hidden_layers: self.num_hidden_layers, num_attention_heads: self.num_attention_heads, num_key_value_heads: self.num_key_value_heads(), rms_norm_eps: self.rms_norm_eps, rope_theta: self.rope_theta, use_flash_attn, bos_token_id: self.bos_token_id, eos_token_id: self.eos_token_id, rope_scaling: self.rope_scaling, max_position_embeddings: self.max_position_embeddings, } } } #[derive(Debug, Clone)] pub struct Config { pub hidden_size: usize, pub intermediate_size: usize, pub vocab_size: usize, pub num_hidden_layers: usize, pub num_attention_heads: usize, pub num_key_value_heads: usize, pub use_flash_attn: bool, pub rms_norm_eps: f64, pub rope_theta: f32, pub bos_token_id: Option<u32>, pub eos_token_id: Option<GraniteEosToks>, pub rope_scaling: Option<GraniteRopeConfig>, pub max_position_embeddings: usize, } #[derive(Debug, Clone)] pub struct Cache { masks: HashMap<usize, Tensor>, pub use_kv_cache: bool, kvs: Vec<Option<(Tensor, Tensor)>>, cos: Tensor, sin: Tensor, device: Device, } fn calculate_default_inv_freq(cfg: &Config) -> Vec<f32> { let head_dim = cfg.hidden_size / cfg.num_attention_heads; (0..head_dim) .step_by(2) .map(|i| 1f32 / cfg.rope_theta.powf(i as f32 / head_dim as f32)) .collect() } impl Cache { pub fn new(use_kv_cache: bool, dtype: DType, config: &Config, device: &Device) -> Result<Self> { // precompute freqs_cis let theta = match &config.rope_scaling { None | Some(GraniteRopeConfig { rope_type: GraniteRopeType::Default, .. }) => calculate_default_inv_freq(config), Some(rope_scaling) => { let low_freq_wavelen = rope_scaling.original_max_position_embeddings as f32 / rope_scaling.low_freq_factor; let high_freq_wavelen = rope_scaling.original_max_position_embeddings as f32 / rope_scaling.high_freq_factor; calculate_default_inv_freq(config) .into_iter() .map(|freq| { let wavelen = 2. * PI / freq; if wavelen < high_freq_wavelen { freq } else if wavelen > low_freq_wavelen { freq / rope_scaling.factor } else { let smooth = (rope_scaling.original_max_position_embeddings as f32 / wavelen - rope_scaling.low_freq_factor) / (rope_scaling.high_freq_factor - rope_scaling.low_freq_factor); (1. - smooth) * freq / rope_scaling.factor + smooth * freq } }) .collect::<Vec<_>>() } }; let theta = Tensor::new(theta, device)?; let idx_theta = Tensor::arange(0, config.max_position_embeddings as u32, device)? .to_dtype(DType::F32)? .reshape((config.max_position_embeddings, 1))? .matmul(&theta.reshape((1, theta.elem_count()))?)?; let cos = idx_theta.cos()?.to_dtype(dtype)?; let sin = idx_theta.sin()?.to_dtype(dtype)?; Ok(Self { masks: HashMap::new(), use_kv_cache, kvs: vec![None; config.num_hidden_layers], device: device.clone(), cos, sin, }) } fn mask(&mut self, t: usize) -> Result<Tensor> { if let Some(mask) = self.masks.get(&t) { Ok(mask.clone()) } else { let mask: Vec<_> = (0..t) .flat_map(|i| (0..t).map(move |j| u8::from(j > i))) .collect(); let mask = Tensor::from_slice(&mask, (t, t), &self.device)?; self.masks.insert(t, mask.clone()); Ok(mask) } } } #[derive(Debug, Clone)] struct CausalSelfAttention { q_proj: Linear, k_proj: Linear, v_proj: Linear, o_proj: Linear, num_attention_heads: usize, num_key_value_heads: usize, head_dim: usize, use_flash_attn: bool, span: tracing::Span, span_rot: tracing::Span, max_position_embeddings: usize, } #[cfg(feature = "flash-attn")] fn flash_attn( q: &Tensor, k: &Tensor, v: &Tensor, softmax_scale: f32, causal: bool, ) -> Result<Tensor> { candle_flash_attn::flash_attn(q, k, v, softmax_scale, causal) } #[cfg(not(feature = "flash-attn"))] fn flash_attn(_: &Tensor, _: &Tensor, _: &Tensor, _: f32, _: bool) -> Result<Tensor> { unimplemented!("compile with '--features flash-attn'") } impl CausalSelfAttention { fn apply_rotary_emb(&self, x: &Tensor, index_pos: usize, cache: &Cache) -> Result<Tensor> { let _enter = self.span_rot.enter(); let (_b_sz, _, seq_len, _hidden_size) = x.dims4()?; let cos = cache.cos.narrow(0, index_pos, seq_len)?; let sin = cache.sin.narrow(0, index_pos, seq_len)?; candle_nn::rotary_emb::rope(x, &cos, &sin) } fn forward( &self, x: &Tensor, index_pos: usize, block_idx: usize, cache: &mut Cache, ) -> Result<Tensor> { let _enter = self.span.enter(); let (b_sz, seq_len, hidden_size) = x.dims3()?; let q = self.q_proj.forward(x)?; let k = self.k_proj.forward(x)?; let v = self.v_proj.forward(x)?; let q = q .reshape((b_sz, seq_len, self.num_attention_heads, self.head_dim))? .transpose(1, 2)? .contiguous()?; let k = k .reshape((b_sz, seq_len, self.num_key_value_heads, self.head_dim))? .transpose(1, 2)? .contiguous()?; let mut v = v .reshape((b_sz, seq_len, self.num_key_value_heads, self.head_dim))? .transpose(1, 2)?; let q = self.apply_rotary_emb(&q, index_pos, cache)?; let mut k = self.apply_rotary_emb(&k, index_pos, cache)?; if cache.use_kv_cache { if let Some((cache_k, cache_v)) = &cache.kvs[block_idx] { k = Tensor::cat(&[cache_k, &k], 2)?.contiguous()?; v = Tensor::cat(&[cache_v, &v], 2)?.contiguous()?; let k_seq_len = k.dims()[1]; if k_seq_len > self.max_position_embeddings { k = k .narrow( D::Minus1, k_seq_len - self.max_position_embeddings, self.max_position_embeddings, )? .contiguous()? } let v_seq_len = v.dims()[1]; if v_seq_len > 2 * self.max_position_embeddings { v = v .narrow( D::Minus1, v_seq_len - self.max_position_embeddings, self.max_position_embeddings, )? .contiguous()? } } cache.kvs[block_idx] = Some((k.clone(), v.clone())) } let k = self.repeat_kv(k)?; let v = self.repeat_kv(v)?; let y = if self.use_flash_attn { // flash-attn expects (b_sz, seq_len, nheads, head_dim) let q = q.transpose(1, 2)?; let k = k.transpose(1, 2)?; let v = v.transpose(1, 2)?; let softmax_scale = 1f32 / (self.head_dim as f32).sqrt(); flash_attn(&q, &k, &v, softmax_scale, seq_len > 1)?.transpose(1, 2)? } else { let in_dtype = q.dtype(); let q = q.to_dtype(DType::F32)?; let k = k.to_dtype(DType::F32)?; let v = v.to_dtype(DType::F32)?; let att = (q.matmul(&k.t()?)? / (self.head_dim as f64).sqrt())?; let att = if seq_len == 1 { att } else { let mask = cache.mask(seq_len)?.broadcast_as(att.shape())?; masked_fill(&att, &mask, f32::NEG_INFINITY)? }; let att = candle_nn::ops::softmax(&att, D::Minus1)?; // Convert to contiguous as matmul doesn't support strided vs for now. att.matmul(&v.contiguous()?)?.to_dtype(in_dtype)? }; let y = y.transpose(1, 2)?.reshape(&[b_sz, seq_len, hidden_size])?; let y = self.o_proj.forward(&y)?; Ok(y) } fn repeat_kv(&self, x: Tensor) -> Result<Tensor> { crate::utils::repeat_kv(x, self.num_attention_heads / self.num_key_value_heads) } fn load(vb: VarBuilder, cfg: &Config) -> Result<Self> { let span = tracing::span!(tracing::Level::TRACE, "attn"); let span_rot = tracing::span!(tracing::Level::TRACE, "attn-rot"); let size_in = cfg.hidden_size; let size_q = (cfg.hidden_size / cfg.num_attention_heads) * cfg.num_attention_heads; let size_kv = (cfg.hidden_size / cfg.num_attention_heads) * cfg.num_key_value_heads; let q_proj = linear(size_in, size_q, vb.pp("q_proj"))?; let k_proj = linear(size_in, size_kv, vb.pp("k_proj"))?; let v_proj = linear(size_in, size_kv, vb.pp("v_proj"))?; let o_proj = linear(size_q, size_in, vb.pp("o_proj"))?; Ok(Self { q_proj, k_proj, v_proj, o_proj, num_attention_heads: cfg.num_attention_heads, num_key_value_heads: cfg.num_key_value_heads, head_dim: cfg.hidden_size / cfg.num_attention_heads, use_flash_attn: cfg.use_flash_attn, span, span_rot, max_position_embeddings: cfg.max_position_embeddings, }) } } fn masked_fill(on_false: &Tensor, mask: &Tensor, on_true: f32) -> Result<Tensor> { let shape = mask.shape(); let on_true = Tensor::new(on_true, on_false.device())?.broadcast_as(shape.dims())?; let m = mask.where_cond(&on_true, on_false)?; Ok(m) } #[derive(Debug, Clone)] struct Mlp { c_fc1: Linear, c_fc2: Linear, c_proj: Linear, span: tracing::Span, } impl Mlp { fn forward(&self, x: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let x = (candle_nn::ops::silu(&self.c_fc1.forward(x)?)? * self.c_fc2.forward(x)?)?; self.c_proj.forward(&x) } fn load(vb: VarBuilder, cfg: &Config) -> Result<Self> { let span = tracing::span!(tracing::Level::TRACE, "mlp"); let h_size = cfg.hidden_size; let i_size = cfg.intermediate_size; let c_fc1 = linear(h_size, i_size, vb.pp("gate_proj"))?; let c_fc2 = linear(h_size, i_size, vb.pp("up_proj"))?; let c_proj = linear(i_size, h_size, vb.pp("down_proj"))?; Ok(Self { c_fc1, c_fc2, c_proj, span, }) } } #[derive(Debug, Clone)] struct Block { rms_1: RmsNorm, attn: CausalSelfAttention, rms_2: RmsNorm, mlp: Mlp, span: tracing::Span, } impl Block { fn forward( &self, x: &Tensor, index_pos: usize, block_idx: usize, cache: &mut Cache, ) -> Result<Tensor> { let _enter = self.span.enter(); let residual = x; let x = self.rms_1.forward(x)?; let x = (self.attn.forward(&x, index_pos, block_idx, cache)? + residual)?; let residual = &x; let x = (self.mlp.forward(&self.rms_2.forward(&x)?)? + residual)?; Ok(x) } fn load(vb: VarBuilder, cfg: &Config) -> Result<Self> { let span = tracing::span!(tracing::Level::TRACE, "block"); let attn = CausalSelfAttention::load(vb.pp("self_attn"), cfg)?; let mlp = Mlp::load(vb.pp("mlp"), cfg)?; let rms_1 = RmsNorm::new(cfg.hidden_size, cfg.rms_norm_eps, vb.pp("input_layernorm"))?; let rms_2 = RmsNorm::new( cfg.hidden_size, cfg.rms_norm_eps, vb.pp("post_attention_layernorm"), )?; Ok(Self { rms_1, attn, rms_2, mlp, span, }) } } #[derive(Debug, Clone)] pub struct Granite { wte: Embedding, blocks: Vec<Block>, ln_f: RmsNorm, lm_head: Linear, } impl Granite { pub fn forward(&self, x: &Tensor, index_pos: usize, cache: &mut Cache) -> Result<Tensor> { let (_b_sz, seq_len) = x.dims2()?; let mut x = self.wte.forward(x)?; for (block_idx, block) in self.blocks.iter().enumerate() { x = block.forward(&x, index_pos, block_idx, cache)?; } let x = self.ln_f.forward(&x)?; let x = x.i((.., seq_len - 1, ..))?.contiguous()?; let logits = self.lm_head.forward(&x)?; logits.to_dtype(DType::F32) } pub fn load(vb: VarBuilder, cfg: &Config) -> Result<Self> { let wte = embedding(cfg.vocab_size, cfg.hidden_size, vb.pp("model.embed_tokens"))?; let lm_head = linear(cfg.hidden_size, cfg.vocab_size, vb.pp("lm_head"))?; let ln_f = RmsNorm::new(cfg.hidden_size, cfg.rms_norm_eps, vb.pp("model.norm"))?; let blocks: Vec<_> = (0..cfg.num_hidden_layers) .map(|i| Block::load(vb.pp(format!("model.layers.{i}")), cfg).unwrap()) .collect(); Ok(Self { wte, blocks, ln_f, lm_head, }) } }
candle/candle-transformers/src/models/granite.rs/0
{ "file_path": "candle/candle-transformers/src/models/granite.rs", "repo_id": "candle", "token_count": 8417 }
54
// Copyright (c) Kyutai, all rights reserved. // This source code is licensed under the license found in the // LICENSE file in the root directory of this source tree. use candle::{IndexOp, Layout, Result, Shape, Tensor, D}; use candle_nn::{linear, Linear, VarBuilder}; struct CodebookEncode; impl candle::CustomOp2 for CodebookEncode { fn name(&self) -> &'static str { "cb" } fn cpu_fwd( &self, lhs_storage: &candle::CpuStorage, lhs_layout: &Layout, rhs_storage: &candle::CpuStorage, rhs_layout: &Layout, ) -> Result<(candle::CpuStorage, Shape)> { use rayon::prelude::*; let (lhs_dim1, lhs_dim2) = lhs_layout.shape().dims2()?; let (rhs_dim1, rhs_dim2) = rhs_layout.shape().dims2()?; if lhs_dim2 != rhs_dim2 { candle::bail!("CodebookEncode, mismatch on last dim, {lhs_layout:?} {rhs_layout:?}"); } if lhs_dim2 == 0 { candle::bail!("CodebookEncode, empty last dim {lhs_layout:?}") } let lhs = match lhs_layout.contiguous_offsets() { None => candle::bail!("CodebookEncode, lhs has to be contiguous, got {lhs_layout:?}"), Some((o1, o2)) => { let slice = lhs_storage.as_slice::<f32>()?; &slice[o1..o2] } }; let rhs = match rhs_layout.contiguous_offsets() { None => candle::bail!("CodebookEncode, rhs has to be contiguous, got {rhs_layout:?}"), Some((o1, o2)) => { let slice = rhs_storage.as_slice::<f32>()?; &slice[o1..o2] } }; let dst = (0..lhs_dim1) .into_par_iter() .map(|idx1| { let mut where_min = 0; let mut min_dist = f32::INFINITY; let lhs = &lhs[idx1 * lhs_dim2..(idx1 + 1) * lhs_dim2]; for idx2 in 0..rhs_dim1 { let rhs = &rhs[idx2 * rhs_dim2..(idx2 + 1) * rhs_dim2]; let mut dist = 0f32; for (a, b) in lhs.iter().zip(rhs.iter()) { dist += (a - b) * (a - b) } if dist < min_dist { min_dist = dist; where_min = idx2; } } where_min as u32 }) .collect(); let storage = candle::WithDType::to_cpu_storage_owned(dst); Ok((storage, (lhs_dim1,).into())) } } #[allow(unused)] #[derive(Debug, Clone)] pub struct EuclideanCodebook { initialized: Tensor, cluster_usage: Tensor, embedding_sum: Tensor, embedding: Tensor, c2: Tensor, epsilon: f64, dim: usize, span_encode: tracing::Span, span_decode: tracing::Span, } impl EuclideanCodebook { pub fn new(dim: usize, codebook_size: usize, vb: VarBuilder) -> Result<Self> { let epsilon = 1e-5; let initialized = vb.get(1, "initialized")?; let cluster_usage = vb.get(codebook_size, "cluster_usage")?; let embedding_sum = vb.get((codebook_size, dim), "embed_sum")?; let embedding = { let cluster_usage = cluster_usage.maximum(epsilon)?.unsqueeze(1)?; embedding_sum.broadcast_div(&cluster_usage)? }; let c2 = ((&embedding * &embedding)?.sum(D::Minus1)? / 2.0)?; Ok(Self { initialized, cluster_usage, embedding_sum, embedding, c2, epsilon, dim, span_encode: tracing::span!(tracing::Level::TRACE, "euclidean-encode"), span_decode: tracing::span!(tracing::Level::TRACE, "euclidean-encode"), }) } pub fn encode_very_slow(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span_encode.enter(); let mut target_shape = xs.dims().to_vec(); target_shape.pop(); let xs = xs.flatten_to(D::Minus2)?; let _ = xs.dims2()?; // TODO: avoid repeating this. let cluster_usage = self.cluster_usage.maximum(self.epsilon)?.unsqueeze(1)?; let embedding = self.embedding_sum.broadcast_div(&cluster_usage)?; // Manual cdist implementation. let diff = xs.unsqueeze(1)?.broadcast_sub(&embedding.unsqueeze(0)?)?; let dists = diff.sqr()?.sum(D::Minus1)?; let codes = dists.argmin(D::Minus1)?; codes.reshape(target_shape) } pub fn encode_slow(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span_encode.enter(); let mut target_shape = xs.dims().to_vec(); target_shape.pop(); let xs = xs.flatten_to(D::Minus2)?; let _ = xs.dims2()?; let dot_prod = xs.matmul(&self.embedding.t()?)?; let codes = self.c2.broadcast_sub(&dot_prod)?.argmin(D::Minus1)?; codes.reshape(target_shape) } pub fn encode(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span_encode.enter(); let mut target_shape = xs.dims().to_vec(); target_shape.pop(); let xs = xs.flatten_to(D::Minus2)?; let _ = xs.dims2()?; let codes = Tensor::apply_op2(&xs, &self.embedding, CodebookEncode)?; codes.reshape(target_shape) } pub fn decode(&self, indexes: &Tensor) -> Result<Tensor> { let _enter = self.span_decode.enter(); // let ys = candle_nn::Embedding::new(self.embedding.clone(), self.dim).forward(xs)?; let mut final_dims = indexes.dims().to_vec(); final_dims.push(self.dim); let indexes = indexes.flatten_all()?; let values = self.embedding.index_select(&indexes, 0)?; let values = values.reshape(final_dims)?; Ok(values) } } #[allow(unused)] #[derive(Debug, Clone)] pub struct VectorQuantization { project_in: Option<Linear>, project_out: Option<Linear>, codebook: EuclideanCodebook, } impl VectorQuantization { pub fn new( dim: usize, codebook_size: usize, codebook_dim: Option<usize>, vb: VarBuilder, ) -> Result<Self> { let codebook_dim = codebook_dim.unwrap_or(dim); let (project_in, project_out) = if codebook_dim == dim { (None, None) } else { let p_in = linear(dim, codebook_dim, vb.pp("project_in"))?; let p_out = linear(codebook_dim, dim, vb.pp("project_out"))?; (Some(p_in), Some(p_out)) }; let codebook = EuclideanCodebook::new(codebook_dim, codebook_size, vb.pp("codebook"))?; Ok(Self { project_in, project_out, codebook, }) } pub fn encode(&self, xs: &Tensor) -> Result<Tensor> { let xs = xs.t()?.apply(&self.project_in.as_ref())?; self.codebook.encode_slow(&xs) } pub fn decode(&self, codes: &Tensor) -> Result<Tensor> { let quantized = self.codebook.decode(codes)?; let quantized = match &self.project_out { None => quantized, Some(p) => quantized.apply(p)?, }; quantized.t() } } #[derive(Debug, Clone)] pub struct ResidualVectorQuantization { layers: Vec<VectorQuantization>, } impl ResidualVectorQuantization { pub fn new( n_q: usize, dim: usize, codebook_size: usize, codebook_dim: Option<usize>, vb: VarBuilder, ) -> Result<Self> { let vb = vb.pp("layers"); let mut layers = Vec::with_capacity(n_q); for i in 0..n_q { let layer = VectorQuantization::new(dim, codebook_size, codebook_dim, vb.pp(i))?; layers.push(layer) } Ok(Self { layers }) } pub fn encode(&self, xs: &Tensor) -> Result<Tensor> { let mut codes = Vec::with_capacity(self.layers.len()); let mut residual = xs.clone(); for layer in self.layers.iter() { let indices = layer.encode(&residual)?; let quantized = layer.decode(&indices)?; residual = (residual - quantized)?; codes.push(indices) } Tensor::stack(&codes, 0) } pub fn decode(&self, xs: &Tensor) -> Result<Tensor> { if self.layers.is_empty() { candle::bail!("empty layers in ResidualVectorQuantization") } if self.layers.len() != xs.dim(0)? { candle::bail!( "mismatch between the number of layers {} and the code shape {:?}", self.layers.len(), xs.shape() ) } let mut quantized = self.layers[0].decode(&xs.i(0)?)?; for (i, layer) in self.layers.iter().enumerate().skip(1) { let xs = xs.i(i)?; quantized = (quantized + layer.decode(&xs))? } Ok(quantized) } } #[allow(unused)] #[derive(Debug, Clone)] pub struct ResidualVectorQuantizer { vq: ResidualVectorQuantization, input_proj: Option<candle_nn::Conv1d>, output_proj: Option<candle_nn::Conv1d>, } impl ResidualVectorQuantizer { pub fn new( dim: usize, input_dim: Option<usize>, output_dim: Option<usize>, n_q: usize, bins: usize, force_projection: bool, vb: VarBuilder, ) -> Result<Self> { let input_dim = input_dim.unwrap_or(dim); let output_dim = output_dim.unwrap_or(dim); let input_proj = if input_dim == dim && !force_projection { None } else { let c = candle_nn::conv1d_no_bias( input_dim, dim, 1, Default::default(), vb.pp("input_proj"), )?; Some(c) }; let output_proj = if output_dim == dim && !force_projection { None } else { let c = candle_nn::conv1d_no_bias( dim, output_dim, 1, Default::default(), vb.pp("output_proj"), )?; Some(c) }; let vq = ResidualVectorQuantization::new( n_q, dim, /* codebook_size */ bins, /* codebook_dim */ None, vb, )?; Ok(Self { vq, input_proj, output_proj, }) } pub fn encode(&self, xs: &Tensor) -> Result<Tensor> { let codes = self.vq.encode(&xs.apply(&self.input_proj.as_ref())?)?; codes.transpose(0, 1) } pub fn decode(&self, codes: &Tensor) -> Result<Tensor> { // codes is [B, K, T], with T frames, K nb of codebooks, vq.decode expects [K, B, T]. let codes = codes.transpose(0, 1)?; let quantized = self.vq.decode(&codes)?; match &self.output_proj { None => Ok(quantized), Some(p) => quantized.apply(p), } } } // we do not use any codebook_offset at the moment. When reconstructing the codes, we could just // concatenate the indexes. #[derive(Debug, Clone)] pub struct SplitResidualVectorQuantizer { rvq_first: ResidualVectorQuantizer, rvq_rest: ResidualVectorQuantizer, n_q: usize, span_encode: tracing::Span, span_decode: tracing::Span, } impl SplitResidualVectorQuantizer { pub fn new( dim: usize, input_dim: Option<usize>, output_dim: Option<usize>, n_q: usize, bins: usize, vb: VarBuilder, ) -> Result<Self> { let rvq_first = ResidualVectorQuantizer::new( dim, input_dim, output_dim, 1, bins, true, vb.pp("semantic_residual_vector_quantizer"), )?; let rvq_rest = ResidualVectorQuantizer::new( dim, input_dim, output_dim, n_q - 1, bins, true, vb.pp("acoustic_residual_vector_quantizer"), )?; let span_encode = tracing::span!(tracing::Level::TRACE, "split-rvq-encode"); let span_decode = tracing::span!(tracing::Level::TRACE, "split-rvq-decode"); Ok(Self { rvq_first, rvq_rest, n_q, span_encode, span_decode, }) } pub fn encode(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span_encode.enter(); let codes = self.rvq_first.encode(xs)?; if self.n_q > 1 { // We encode xs again here rather than the residual. The decomposition is not // hierarchical but rather having semantic tokens for rvq_first and the acoustic tokens // for rvq_rest. let rest_codes = self.rvq_rest.encode(xs)?; Tensor::cat(&[codes, rest_codes], 1) } else { Ok(codes) } } pub fn decode(&self, codes: &Tensor) -> Result<Tensor> { // codes is [B, K, T], with T frames, K nb of codebooks. let _enter = self.span_decode.enter(); let quantized = self.rvq_first.decode(&codes.i((.., ..1))?)?; let quantized = if self.n_q > 1 { (quantized + self.rvq_rest.decode(&codes.i((.., 1..))?))? } else { quantized }; Ok(quantized) } }
candle/candle-transformers/src/models/mimi/quantization.rs/0
{ "file_path": "candle/candle-transformers/src/models/mimi/quantization.rs", "repo_id": "candle", "token_count": 6873 }
55
//! MoonDream Model vision-to-text //! //! //! Moondream is a computer-vision model that can answer real-world questions about images. //! It's lightweight with only 1.6B parameters, enabling it to run on mobile phones and edge devices. //! [MoonDream Original Implementation](https://github.com/vikhyat/moondream) //! //! The model consists of: //! - Vision encoder using a ViT-style architecture //! - Text decoder based on Microsoft's Phi model //! - Vision projection module to align vision and text embeddings //! //! # Examples //! //! <img src="https://raw.githubusercontent.com/vikhyat/moondream/main/assets/demo-1.jpg" width="200"> //! //! ```bash //! # download an example image //! wget https://raw.githubusercontent.com/vikhyat/moondream/main/assets/demo-1.jpg //! //! # Now you can run Moondream from the `candle-examples` crate: //! cargo run --example moondream \ //! --release -- \ //! --prompt "What is the girl eating?" //! --image "./demo-1.jpg" //! //! > avavx: false, neon: true, simd128: false, f16c: false //! > temp: 0.00 repeat-penalty: 1.00 repeat-last-n: 64 //! > retrieved the files in 3.395583ms //! > Running on CPU, to run on GPU(metal), build this example with `--features metal` //! > loaded the model in 5.485493792s //! > loaded and encoded the image Tensor[dims 3, 378, 378; f32] in 4.801396417s //! > starting the inference loop //! > The girl is eating a hamburger.< //! > 9 tokens generated (0.68 token/s) //! ``` use crate::models::mixformer::{Config as PhiConfig, MixFormerSequentialForCausalLM as PhiModel}; use crate::models::with_tracing::{layer_norm, linear_b, LayerNorm, Linear}; use candle::{IndexOp, Module, Result, Tensor, D}; use candle_nn::VarBuilder; #[derive(Debug, Clone, serde::Deserialize)] pub struct Config { pub phi_config: PhiConfig, pub vision_config: VisionConfig, } impl Config { pub fn v2() -> Self { Self { phi_config: PhiConfig::v1_5(), vision_config: VisionConfig::v2(), } } } 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, PartialEq, serde::Deserialize)] pub struct VisionConfig { pub(crate) image_embedding_dim: usize, pub(crate) model_dim: usize, pub(crate) hidden_dim: usize, pub(crate) hidden_features: usize, pub(crate) embed_len: usize, pub(crate) embed_dim: usize, pub(crate) num_blocks: usize, pub(crate) num_heads: usize, pub(crate) act: candle_nn::Activation, } impl VisionConfig { pub fn v2() -> Self { Self { image_embedding_dim: 1152, model_dim: 2048, hidden_dim: 2048 * 4, hidden_features: 4304, embed_len: 729, embed_dim: 1152, num_blocks: 27, num_heads: 16, act: candle_nn::Activation::GeluPytorchTanh, } } } #[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, span: tracing::Span, } 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, span: tracing::span!(tracing::Level::TRACE, "vit-attn"), }) } } impl Module for Attention { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); 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: LayerNorm, norm2: LayerNorm, span: tracing::Span, } 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, span: tracing::span!(tracing::Level::TRACE, "vit-block"), }) } } impl Module for VitBlock { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); 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: LayerNorm, span: tracing::Span, } 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")?; 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, span: tracing::span!(tracing::Level::TRACE, "vit"), }) } } impl Module for VisionTransformer { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); 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, span: tracing::Span, } 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, span: tracing::span!(tracing::Level::TRACE, "mlp"), }) } } impl Module for Mlp { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); 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) } } #[derive(Debug, Clone)] 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/moondream.rs/0
{ "file_path": "candle/candle-transformers/src/models/moondream.rs", "repo_id": "candle", "token_count": 4946 }
56
use candle::{DType, Device, Module, Result, Tensor, D}; use candle_nn::{linear_b, rms_norm, Linear, RmsNorm, VarBuilder}; fn default_act() -> candle_nn::Activation { candle_nn::Activation::Silu } fn default_hidden_size() -> usize { 1024 } fn default_intermediate_size() -> usize { 4096 } fn default_num_channels() -> usize { 3 } fn default_num_hidden_layers() -> usize { 24 } fn default_num_attention_heads() -> usize { 16 } #[derive(serde::Deserialize, Debug, Clone)] pub struct Config { #[serde(default = "default_hidden_size")] pub hidden_size: usize, #[serde(default = "default_num_channels")] pub num_channels: usize, pub image_size: usize, pub patch_size: usize, pub rope_theta: f64, #[serde(default = "default_intermediate_size")] pub intermediate_size: usize, #[serde(default = "default_num_hidden_layers")] pub num_hidden_layers: usize, pub head_dim: Option<usize>, #[serde(default = "default_num_attention_heads")] pub num_attention_heads: usize, #[serde(default = "default_act")] pub hidden_act: candle_nn::Activation, } impl Config { pub fn pixtral_12b_2409() -> Self { Self { hidden_size: 1024, num_channels: 3, image_size: 1024, patch_size: 16, rope_theta: 10000.0, intermediate_size: 4096, num_hidden_layers: 24, num_attention_heads: 16, head_dim: None, // Default hidden_act: candle_nn::Activation::Silu, } } fn head_dim(&self) -> usize { self.head_dim .unwrap_or(self.hidden_size / self.num_attention_heads) } } #[derive(Debug, Clone)] struct Attention { q_proj: Linear, k_proj: Linear, v_proj: Linear, o_proj: Linear, scale: f64, num_heads: usize, head_dim: usize, } impl Attention { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let h = cfg.hidden_size; let num_heads = cfg.num_attention_heads; let head_dim = cfg.head_dim(); let q_proj = linear_b(h, h, false, vb.pp("q_proj"))?; let k_proj = linear_b(h, h, false, vb.pp("k_proj"))?; let v_proj = linear_b(h, h, false, vb.pp("v_proj"))?; let o_proj = linear_b(h, h, false, vb.pp("o_proj"))?; let scale = (head_dim as f64).powf(-0.5); Ok(Self { q_proj, k_proj, v_proj, o_proj, scale, num_heads, head_dim, }) } fn forward( &self, xs: &Tensor, emb: &RotaryEmbedding, subsampled_positions: Option<&Tensor>, attention_mask: Option<&Tensor>, ) -> Result<Tensor> { let (b, patches, _) = xs.dims3()?; let query_states = xs.apply(&self.q_proj)?; let key_states = xs.apply(&self.k_proj)?; let value_states = xs.apply(&self.v_proj)?; let shape = (b, patches, self.num_heads, self.head_dim); let query_states = query_states.reshape(shape)?.transpose(1, 2)?.contiguous()?; let key_states = key_states.reshape(shape)?.transpose(1, 2)?.contiguous()?; let value_states = value_states.reshape(shape)?.transpose(1, 2)?.contiguous()?; let (query_states, key_states) = emb.apply_rotary_emb_qkv(&query_states, &key_states, subsampled_positions)?; let attn_weights = (query_states.matmul(&key_states.t()?)? * self.scale)?; let attn_weights = match attention_mask { None => attn_weights, Some(mask) => attn_weights.broadcast_add(mask)?, }; let attn_weights = candle_nn::ops::softmax_last_dim(&attn_weights)?; attn_weights .matmul(&value_states)? .transpose(1, 2)? .reshape((b, patches, ()))? .apply(&self.o_proj) } } #[derive(Debug, Clone)] struct Mlp { gate_proj: Linear, up_proj: Linear, down_proj: Linear, act_fn: candle_nn::Activation, } impl Mlp { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let (h, i) = (cfg.hidden_size, cfg.intermediate_size); let gate_proj = linear_b(h, i, false, vb.pp("gate_proj"))?; let up_proj = linear_b(h, i, false, vb.pp("up_proj"))?; let down_proj = linear_b(i, h, false, vb.pp("down_proj"))?; Ok(Self { gate_proj, up_proj, down_proj, act_fn: cfg.hidden_act, }) } } impl Module for Mlp { fn forward(&self, xs: &Tensor) -> Result<Tensor> { (xs.apply(&self.gate_proj)?.apply(&self.act_fn)? * xs.apply(&self.up_proj))? .apply(&self.down_proj) } } #[derive(Debug, Clone)] struct AttentionLayer { attention_norm: RmsNorm, feed_forward: Mlp, attention: Attention, ffn_norm: RmsNorm, } impl AttentionLayer { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let attention_norm = rms_norm(cfg.hidden_size, 1e-5, vb.pp("attention_norm"))?; let feed_forward = Mlp::new(cfg, vb.pp("feed_forward"))?; let attention = Attention::new(cfg, vb.pp("attention"))?; let ffn_norm = rms_norm(cfg.hidden_size, 1e-5, vb.pp("ffn_norm"))?; Ok(Self { attention_norm, feed_forward, attention, ffn_norm, }) } fn forward( &self, xs: &Tensor, emb: &RotaryEmbedding, subsampled_positions: Option<&Tensor>, attention_mask: Option<&Tensor>, ) -> Result<Tensor> { let residual = xs; let xs = self.attention.forward( &xs.apply(&self.attention_norm)?, emb, subsampled_positions, attention_mask, )?; let xs = (residual + xs)?; let residual = &xs; let xs = xs.apply(&self.ffn_norm)?.apply(&self.feed_forward)?; xs + residual } } #[derive(Debug, Clone)] struct Transformer { layers: Vec<AttentionLayer>, } impl Transformer { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let mut layers = Vec::with_capacity(cfg.num_hidden_layers); let vb = vb.pp("layers"); for layer_idx in 0..cfg.num_hidden_layers { let layer = AttentionLayer::new(cfg, vb.pp(layer_idx))?; layers.push(layer) } Ok(Self { layers }) } fn forward( &self, xs: &Tensor, emb: &RotaryEmbedding, subsampled_positions: Option<&Tensor>, attention_mask: Option<&Tensor>, ) -> Result<Tensor> { let mut xs = xs.clone(); for layer in self.layers.iter() { xs = layer.forward(&xs, emb, subsampled_positions, attention_mask)? } Ok(xs) } } #[derive(Debug, Clone)] struct RotaryEmbedding { cos: Tensor, sin: Tensor, } impl RotaryEmbedding { fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let dtype = vb.dtype(); let dev = vb.device(); let dim = cfg.head_dim(); let rope_theta = cfg.rope_theta as f32; let max_patches_per_side = cfg.image_size / cfg.patch_size; let freqs: Vec<_> = (0..dim) .step_by(2) .map(|i| 1f32 / rope_theta.powf(i as f32 / dim as f32)) .collect(); let freqs_h = freqs.iter().step_by(2).copied().collect::<Vec<_>>(); let freqs_h = Tensor::new(freqs_h, dev)?; let freqs_w = freqs.iter().skip(1).step_by(2).copied().collect::<Vec<_>>(); let freqs_w = Tensor::new(freqs_w, dev)?; let h = Tensor::arange(0u32, max_patches_per_side as u32, dev)?.to_dtype(DType::F32)?; let w = Tensor::arange(0u32, max_patches_per_side as u32, dev)?.to_dtype(DType::F32)?; let freqs_h = h.unsqueeze(1)?.matmul(&freqs_h.unsqueeze(0)?)?; let freqs_w = w.unsqueeze(1)?.matmul(&freqs_w.unsqueeze(0)?)?; let inv_freq = Tensor::cat( &[ freqs_h.unsqueeze(1)?.repeat((1, max_patches_per_side, 1))?, freqs_w.unsqueeze(0)?.repeat((max_patches_per_side, 1, 1))?, ], D::Minus1, )? .reshape(((), dim / 2))?; let cos = inv_freq.cos()?.to_dtype(dtype)?; let sin = inv_freq.sin()?.to_dtype(dtype)?; Ok(Self { cos, sin }) } fn apply_rotary_emb_qkv( &self, q: &Tensor, k: &Tensor, subsampled_positions: Option<&Tensor>, ) -> Result<(Tensor, Tensor)> { let (_b_sz, _h, _seq_len, _n_embd) = q.dims4()?; let (cos, sin) = match subsampled_positions { None => (&self.cos, &self.sin), Some(pos) => ( &self.cos.index_select(pos, 0)?, &self.sin.index_select(pos, 0)?, ), }; let q_embed = candle_nn::rotary_emb::rope(q, cos, sin)?; let k_embed = candle_nn::rotary_emb::rope(k, cos, sin)?; Ok((q_embed, k_embed)) } } #[derive(Debug, Clone)] pub struct Model { patch_conv: candle_nn::Conv2d, ln_pre: RmsNorm, transformer: Transformer, patch_positional_embedding: RotaryEmbedding, max_image_width: u32, } impl Model { pub fn new(cfg: &Config, vb: VarBuilder) -> Result<Self> { let conv2d_cfg = candle_nn::Conv2dConfig { stride: cfg.patch_size, ..Default::default() }; let patch_conv = candle_nn::conv2d_no_bias( cfg.num_channels, cfg.hidden_size, cfg.patch_size, conv2d_cfg, vb.pp("patch_conv"), )?; let ln_pre = candle_nn::rms_norm(cfg.hidden_size, 1e-5, vb.pp("ln_pre"))?; let transformer = Transformer::new(cfg, vb.pp("transformer"))?; let patch_positional_embedding = RotaryEmbedding::new(cfg, vb.pp("patch_positional_embedding"))?; let max_image_width = (cfg.image_size / cfg.patch_size) as u32; Ok(Self { patch_conv, ln_pre, transformer, patch_positional_embedding, max_image_width, }) } pub fn position_ids_in_meshgrid( &self, num_patches_h: usize, num_patches_w: usize, device: &Device, ) -> Result<Tensor> { let idx = Tensor::arange(0, num_patches_h as u32, device)?; let idy = Tensor::arange(0, num_patches_w as u32, device)?; let mesh = Tensor::meshgrid(&[idx, idy], false)?; let ids = (&mesh[0] * (self.max_image_width as f64) + &mesh[1])?.flatten_all()?; Ok(ids) } } impl Module for Model { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let patch_embeds = xs.apply(&self.patch_conv)?; let subsampled_positions = Some(self.position_ids_in_meshgrid( patch_embeds.dim(2)?, patch_embeds.dim(3)?, patch_embeds.device(), )?); let patch_embeds = patch_embeds.flatten_from(2)?.t()?.apply(&self.ln_pre)?; self.transformer.forward( &patch_embeds, &self.patch_positional_embedding, subsampled_positions.as_ref(), None, ) } }
candle/candle-transformers/src/models/pixtral/vision_model.rs/0
{ "file_path": "candle/candle-transformers/src/models/pixtral/vision_model.rs", "repo_id": "candle", "token_count": 5788 }
57
//! Segment Anything Model (SAM) //! //! SAM is an architecture for image segmentation, capable of segmenting any object //! in an image based on prompts like points or boxes. //! This model provides a robust and fast image segmentation pipeline that can be tweaked via //! some prompting (requesting some points to be in the target mask, requesting some //! points to be part of the background so _not_ in the target mask, specifying some //! bounding box). //! //! - ⚡ [Interactive Wasm Example](https://huggingface.co/spaces/radames/candle-segment-anything-wasm) //! - 💻 [GH Link](https://github.com/facebookresearch/segment-anything) //! - 📝 [Paper](https://arxiv.org/abs/2304.02643) //! - 💡 The default backbone can be replaced by the smaller and faster TinyViT model based on [MobileSAM](https://github.com/ChaoningZhang/MobileSAM). //! //! //! ## Example //! //! ```bash //! cargo run --example segment-anything --release -- \ //! --image candle-examples/examples/yolo-v8/assets/bike.jpg //! --use-tiny --point 0.6,0.6 --point 0.6,0.55 //! ``` //! //! <div align=center style="display: flex; justify-content: center; gap: 10px;"> //! <img src="https://github.com/huggingface/candle/raw/main/candle-examples/examples/yolo-v8/assets/bike.jpg" alt="" width="30%"> //! <img src="https://github.com/huggingface/candle/raw/main/candle-examples/examples/segment-anything/assets/single_pt_prompt.jpg" alt="" width="30%"> //! <img src="https://github.com/huggingface/candle/raw/main/candle-examples/examples/segment-anything/assets/two_pt_prompt.jpg" alt="" width="30%"> //! </div> //! //! //! > Original; Prompt with `--point 0.6,0.55`; Prompt with `--point 0.6,0.6 --point 0.6,0.55` //! pub use crate::models::with_tracing::Linear; use candle::{Result, Tensor}; use candle_nn::{Module, VarBuilder}; pub mod image_encoder; pub mod mask_decoder; pub mod prompt_encoder; pub mod sam; pub mod tiny_vit; pub mod transformer; pub fn linear(vb: VarBuilder, in_dim: usize, out_dim: usize, bias: bool) -> Result<Linear> { if bias { crate::models::with_tracing::linear(in_dim, out_dim, vb) } else { crate::models::with_tracing::linear_no_bias(in_dim, out_dim, vb) } } #[derive(Debug)] pub struct LayerNorm2d { weight: Tensor, bias: Tensor, num_channels: usize, eps: f64, } impl LayerNorm2d { pub fn new(num_channels: usize, eps: f64, vb: VarBuilder) -> Result<Self> { let weight = vb.get(num_channels, "weight")?; let bias = vb.get(num_channels, "bias")?; Ok(Self { weight, bias, num_channels, eps, }) } } impl Module for LayerNorm2d { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let u = xs.mean_keepdim(1)?; let xs = xs.broadcast_sub(&u)?; let s = xs.sqr()?.mean_keepdim(1)?; let xs = xs.broadcast_div(&(s + self.eps)?.sqrt()?)?; xs.broadcast_mul(&self.weight.reshape((1, self.num_channels, 1, 1))?)? .broadcast_add(&self.bias.reshape((1, self.num_channels, 1, 1))?) } } #[derive(Debug)] pub struct MlpBlock { lin1: Linear, lin2: Linear, activation: candle_nn::Activation, span: tracing::Span, } impl MlpBlock { pub fn new( embedding_dim: usize, mlp_dim: usize, activation: candle_nn::Activation, vb: VarBuilder, ) -> Result<Self> { let lin1 = linear(vb.pp("lin1"), embedding_dim, mlp_dim, true)?; let lin2 = linear(vb.pp("lin2"), mlp_dim, embedding_dim, true)?; let span = tracing::span!(tracing::Level::TRACE, "mlp-block"); Ok(Self { lin1, lin2, activation, span, }) } } impl Module for MlpBlock { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); xs.apply(&self.lin1)? .apply(&self.activation)? .apply(&self.lin2) } }
candle/candle-transformers/src/models/segment_anything/mod.rs/0
{ "file_path": "candle/candle-transformers/src/models/segment_anything/mod.rs", "repo_id": "candle", "token_count": 1721 }
58
//! 2D UNet Denoising Models //! //! The 2D Unet models take as input a noisy sample and the current diffusion //! timestep and return a denoised version of the input. use super::embeddings::{TimestepEmbedding, Timesteps}; use super::unet_2d_blocks::*; use crate::models::with_tracing::{conv2d, Conv2d}; use candle::{Result, Tensor}; use candle_nn as nn; use candle_nn::Module; #[derive(Debug, Clone, Copy)] pub struct BlockConfig { pub out_channels: usize, /// When `None` no cross-attn is used, when `Some(d)` then cross-attn is used and `d` is the /// number of transformer blocks to be used. pub use_cross_attn: Option<usize>, pub attention_head_dim: usize, } #[derive(Debug, Clone)] pub struct UNet2DConditionModelConfig { pub center_input_sample: bool, pub flip_sin_to_cos: bool, pub freq_shift: f64, pub blocks: Vec<BlockConfig>, pub layers_per_block: usize, pub downsample_padding: usize, pub mid_block_scale_factor: f64, pub norm_num_groups: usize, pub norm_eps: f64, pub cross_attention_dim: usize, pub sliced_attention_size: Option<usize>, pub use_linear_projection: bool, } impl Default for UNet2DConditionModelConfig { fn default() -> Self { Self { center_input_sample: false, flip_sin_to_cos: true, freq_shift: 0., blocks: vec![ BlockConfig { out_channels: 320, use_cross_attn: Some(1), attention_head_dim: 8, }, BlockConfig { out_channels: 640, use_cross_attn: Some(1), attention_head_dim: 8, }, BlockConfig { out_channels: 1280, use_cross_attn: Some(1), attention_head_dim: 8, }, BlockConfig { out_channels: 1280, use_cross_attn: None, attention_head_dim: 8, }, ], layers_per_block: 2, downsample_padding: 1, mid_block_scale_factor: 1., norm_num_groups: 32, norm_eps: 1e-5, cross_attention_dim: 1280, sliced_attention_size: None, use_linear_projection: false, } } } #[derive(Debug)] pub(crate) enum UNetDownBlock { Basic(DownBlock2D), CrossAttn(CrossAttnDownBlock2D), } #[derive(Debug)] enum UNetUpBlock { Basic(UpBlock2D), CrossAttn(CrossAttnUpBlock2D), } #[derive(Debug)] pub struct UNet2DConditionModel { conv_in: Conv2d, time_proj: Timesteps, time_embedding: TimestepEmbedding, down_blocks: Vec<UNetDownBlock>, mid_block: UNetMidBlock2DCrossAttn, up_blocks: Vec<UNetUpBlock>, conv_norm_out: nn::GroupNorm, conv_out: Conv2d, span: tracing::Span, config: UNet2DConditionModelConfig, } impl UNet2DConditionModel { pub fn new( vs: nn::VarBuilder, in_channels: usize, out_channels: usize, use_flash_attn: bool, config: UNet2DConditionModelConfig, ) -> Result<Self> { let n_blocks = config.blocks.len(); let b_channels = config.blocks[0].out_channels; let bl_channels = config.blocks.last().unwrap().out_channels; let bl_attention_head_dim = config.blocks.last().unwrap().attention_head_dim; let time_embed_dim = b_channels * 4; let conv_cfg = nn::Conv2dConfig { padding: 1, ..Default::default() }; let conv_in = conv2d(in_channels, b_channels, 3, conv_cfg, vs.pp("conv_in"))?; let time_proj = Timesteps::new(b_channels, config.flip_sin_to_cos, config.freq_shift); let time_embedding = TimestepEmbedding::new(vs.pp("time_embedding"), b_channels, time_embed_dim)?; let vs_db = vs.pp("down_blocks"); let down_blocks = (0..n_blocks) .map(|i| { let BlockConfig { out_channels, use_cross_attn, attention_head_dim, } = config.blocks[i]; // Enable automatic attention slicing if the config sliced_attention_size is set to 0. let sliced_attention_size = match config.sliced_attention_size { Some(0) => Some(attention_head_dim / 2), _ => config.sliced_attention_size, }; let in_channels = if i > 0 { config.blocks[i - 1].out_channels } else { b_channels }; let db_cfg = DownBlock2DConfig { num_layers: config.layers_per_block, resnet_eps: config.norm_eps, resnet_groups: config.norm_num_groups, add_downsample: i < n_blocks - 1, downsample_padding: config.downsample_padding, ..Default::default() }; if let Some(transformer_layers_per_block) = use_cross_attn { let config = CrossAttnDownBlock2DConfig { downblock: db_cfg, attn_num_head_channels: attention_head_dim, cross_attention_dim: config.cross_attention_dim, sliced_attention_size, use_linear_projection: config.use_linear_projection, transformer_layers_per_block, }; let block = CrossAttnDownBlock2D::new( vs_db.pp(i.to_string()), in_channels, out_channels, Some(time_embed_dim), use_flash_attn, config, )?; Ok(UNetDownBlock::CrossAttn(block)) } else { let block = DownBlock2D::new( vs_db.pp(i.to_string()), in_channels, out_channels, Some(time_embed_dim), db_cfg, )?; Ok(UNetDownBlock::Basic(block)) } }) .collect::<Result<Vec<_>>>()?; // https://github.com/huggingface/diffusers/blob/a76f2ad538e73b34d5fe7be08c8eb8ab38c7e90c/src/diffusers/models/unet_2d_condition.py#L462 let mid_transformer_layers_per_block = match config.blocks.last() { None => 1, Some(block) => block.use_cross_attn.unwrap_or(1), }; let mid_cfg = UNetMidBlock2DCrossAttnConfig { resnet_eps: config.norm_eps, output_scale_factor: config.mid_block_scale_factor, cross_attn_dim: config.cross_attention_dim, attn_num_head_channels: bl_attention_head_dim, resnet_groups: Some(config.norm_num_groups), use_linear_projection: config.use_linear_projection, transformer_layers_per_block: mid_transformer_layers_per_block, ..Default::default() }; let mid_block = UNetMidBlock2DCrossAttn::new( vs.pp("mid_block"), bl_channels, Some(time_embed_dim), use_flash_attn, mid_cfg, )?; let vs_ub = vs.pp("up_blocks"); let up_blocks = (0..n_blocks) .map(|i| { let BlockConfig { out_channels, use_cross_attn, attention_head_dim, } = config.blocks[n_blocks - 1 - i]; // Enable automatic attention slicing if the config sliced_attention_size is set to 0. let sliced_attention_size = match config.sliced_attention_size { Some(0) => Some(attention_head_dim / 2), _ => config.sliced_attention_size, }; let prev_out_channels = if i > 0 { config.blocks[n_blocks - i].out_channels } else { bl_channels }; let in_channels = { let index = if i == n_blocks - 1 { 0 } else { n_blocks - i - 2 }; config.blocks[index].out_channels }; let ub_cfg = UpBlock2DConfig { num_layers: config.layers_per_block + 1, resnet_eps: config.norm_eps, resnet_groups: config.norm_num_groups, add_upsample: i < n_blocks - 1, ..Default::default() }; if let Some(transformer_layers_per_block) = use_cross_attn { let config = CrossAttnUpBlock2DConfig { upblock: ub_cfg, attn_num_head_channels: attention_head_dim, cross_attention_dim: config.cross_attention_dim, sliced_attention_size, use_linear_projection: config.use_linear_projection, transformer_layers_per_block, }; let block = CrossAttnUpBlock2D::new( vs_ub.pp(i.to_string()), in_channels, prev_out_channels, out_channels, Some(time_embed_dim), use_flash_attn, config, )?; Ok(UNetUpBlock::CrossAttn(block)) } else { let block = UpBlock2D::new( vs_ub.pp(i.to_string()), in_channels, prev_out_channels, out_channels, Some(time_embed_dim), ub_cfg, )?; Ok(UNetUpBlock::Basic(block)) } }) .collect::<Result<Vec<_>>>()?; let conv_norm_out = nn::group_norm( config.norm_num_groups, b_channels, config.norm_eps, vs.pp("conv_norm_out"), )?; let conv_out = conv2d(b_channels, out_channels, 3, conv_cfg, vs.pp("conv_out"))?; let span = tracing::span!(tracing::Level::TRACE, "unet2d"); Ok(Self { conv_in, time_proj, time_embedding, down_blocks, mid_block, up_blocks, conv_norm_out, conv_out, span, config, }) } pub fn forward( &self, xs: &Tensor, timestep: f64, encoder_hidden_states: &Tensor, ) -> Result<Tensor> { let _enter = self.span.enter(); self.forward_with_additional_residuals(xs, timestep, encoder_hidden_states, None, None) } pub fn forward_with_additional_residuals( &self, xs: &Tensor, timestep: f64, encoder_hidden_states: &Tensor, down_block_additional_residuals: Option<&[Tensor]>, mid_block_additional_residual: Option<&Tensor>, ) -> Result<Tensor> { let (bsize, _channels, height, width) = xs.dims4()?; let device = xs.device(); let n_blocks = self.config.blocks.len(); let num_upsamplers = n_blocks - 1; let default_overall_up_factor = 2usize.pow(num_upsamplers as u32); let forward_upsample_size = height % default_overall_up_factor != 0 || width % default_overall_up_factor != 0; // 0. center input if necessary let xs = if self.config.center_input_sample { ((xs * 2.0)? - 1.0)? } else { xs.clone() }; // 1. time let emb = (Tensor::ones(bsize, xs.dtype(), device)? * timestep)?; let emb = self.time_proj.forward(&emb)?; let emb = self.time_embedding.forward(&emb)?; // 2. pre-process let xs = self.conv_in.forward(&xs)?; // 3. down let mut down_block_res_xs = vec![xs.clone()]; let mut xs = xs; for down_block in self.down_blocks.iter() { let (_xs, res_xs) = match down_block { UNetDownBlock::Basic(b) => b.forward(&xs, Some(&emb))?, UNetDownBlock::CrossAttn(b) => { b.forward(&xs, Some(&emb), Some(encoder_hidden_states))? } }; down_block_res_xs.extend(res_xs); xs = _xs; } let new_down_block_res_xs = if let Some(down_block_additional_residuals) = down_block_additional_residuals { let mut v = vec![]; // A previous version of this code had a bug because of the addition being made // in place via += hence modifying the input of the mid block. for (i, residuals) in down_block_additional_residuals.iter().enumerate() { v.push((&down_block_res_xs[i] + residuals)?) } v } else { down_block_res_xs }; let mut down_block_res_xs = new_down_block_res_xs; // 4. mid let xs = self .mid_block .forward(&xs, Some(&emb), Some(encoder_hidden_states))?; let xs = match mid_block_additional_residual { None => xs, Some(m) => (m + xs)?, }; // 5. up let mut xs = xs; let mut upsample_size = None; for (i, up_block) in self.up_blocks.iter().enumerate() { let n_resnets = match up_block { UNetUpBlock::Basic(b) => b.resnets.len(), UNetUpBlock::CrossAttn(b) => b.upblock.resnets.len(), }; let res_xs = down_block_res_xs.split_off(down_block_res_xs.len() - n_resnets); if i < n_blocks - 1 && forward_upsample_size { let (_, _, h, w) = down_block_res_xs.last().unwrap().dims4()?; upsample_size = Some((h, w)) } xs = match up_block { UNetUpBlock::Basic(b) => b.forward(&xs, &res_xs, Some(&emb), upsample_size)?, UNetUpBlock::CrossAttn(b) => b.forward( &xs, &res_xs, Some(&emb), upsample_size, Some(encoder_hidden_states), )?, }; } // 6. post-process let xs = self.conv_norm_out.forward(&xs)?; let xs = nn::ops::silu(&xs)?; self.conv_out.forward(&xs) } }
candle/candle-transformers/src/models/stable_diffusion/unet_2d.rs/0
{ "file_path": "candle/candle-transformers/src/models/stable_diffusion/unet_2d.rs", "repo_id": "candle", "token_count": 8419 }
59
import init, { Model } from "./build/m.js"; async function fetchArrayBuffer(url, cacheFile = true) { if (!cacheFile) return new Uint8Array(await (await fetch(url)).arrayBuffer()); const cacheName = "blip-candle-cache"; const cache = await caches.open(cacheName); const cachedResponse = await cache.match(url); if (cachedResponse) { const data = await cachedResponse.arrayBuffer(); return new Uint8Array(data); } const res = await fetch(url, { cache: "force-cache" }); cache.put(url, res.clone()); return new Uint8Array(await res.arrayBuffer()); } class Blip { static instance = {}; static async getInstance( weightsURL, tokenizerURL, configURL, modelID, quantized ) { if (!this.instance[modelID]) { await init(); self.postMessage({ status: "loading", message: "Loading Model" }); const [weightsArrayU8, tokenizerArrayU8, configArrayU8] = await Promise.all([ fetchArrayBuffer(weightsURL), fetchArrayBuffer(tokenizerURL), fetchArrayBuffer(configURL), ]); this.instance[modelID] = new Model( weightsArrayU8, tokenizerArrayU8, configArrayU8, quantized ); } else { self.postMessage({ status: "ready", message: "Model Already Loaded" }); } return this.instance[modelID]; } } self.addEventListener("message", async (event) => { const { weightsURL, tokenizerURL, configURL, modelID, imageURL, quantized } = event.data; try { self.postMessage({ status: "status", message: "Loading Blip Model..." }); const model = await Blip.getInstance( weightsURL, tokenizerURL, configURL, modelID, quantized ); self.postMessage({ status: "status", message: "Running Blip Inference...", }); const imageArrayU8 = await fetchArrayBuffer(imageURL, false); const output = model.generate_caption_from_image(imageArrayU8); self.postMessage({ status: "complete", message: "complete", output: output, }); } catch (e) { self.postMessage({ error: e }); } });
candle/candle-wasm-examples/blip/blipWorker.js/0
{ "file_path": "candle/candle-wasm-examples/blip/blipWorker.js", "repo_id": "candle", "token_count": 815 }
60
mod app; pub mod model; pub mod worker; pub use app::App; pub use worker::Worker;
candle/candle-wasm-examples/llama2-c/src/lib.rs/0
{ "file_path": "candle/candle-wasm-examples/llama2-c/src/lib.rs", "repo_id": "candle", "token_count": 29 }
61
use candle::{DType, Device, Tensor}; use candle_nn::VarBuilder; use candle_transformers::generation::LogitsProcessor; use candle_transformers::models::mixformer::{Config, MixFormerSequentialForCausalLM as MixFormer}; use candle_transformers::models::quantized_mixformer::MixFormerSequentialForCausalLM as QMixFormer; use candle_wasm_example_phi::console_log; use js_sys::Date; use serde::Deserialize; use tokenizers::Tokenizer; use wasm_bindgen::prelude::*; enum SelectedModel { MixFormer(MixFormer), Quantized(QMixFormer), } #[wasm_bindgen] pub struct Model { model: SelectedModel, tokenizer: Tokenizer, logits_processor: LogitsProcessor, tokens: Vec<u32>, repeat_penalty: f32, repeat_last_n: usize, } #[derive(Debug, Clone, PartialEq, Deserialize)] pub struct ModelName { pub _name_or_path: String, } #[wasm_bindgen] impl Model { #[wasm_bindgen(constructor)] pub fn load( weights: Vec<u8>, tokenizer: Vec<u8>, config: Vec<u8>, quantized: bool, ) -> Result<Model, JsError> { console_error_panic_hook::set_once(); console_log!("loading model"); let device = Device::Cpu; let name: ModelName = serde_json::from_slice(&config)?; let config: Config = serde_json::from_slice(&config)?; console_log!("config loaded {:?}", name); let tokenizer = Tokenizer::from_bytes(&tokenizer).map_err(|m| JsError::new(&m.to_string()))?; let start = Date::now(); console_log!("weights len: {:?}", weights.len()); let model = if quantized { let vb = candle_transformers::quantized_var_builder::VarBuilder::from_gguf_buffer( &weights, &device, )?; console_log!("weights loaded"); if name._name_or_path == "microsoft/phi-2" { let model = QMixFormer::new_v2(&config, vb)?; SelectedModel::Quantized(model) } else { let model = QMixFormer::new(&config, vb)?; SelectedModel::Quantized(model) } } else { let device = &Device::Cpu; let vb = VarBuilder::from_buffered_safetensors(weights, DType::F32, device)?; let model = MixFormer::new(&config, vb)?; SelectedModel::MixFormer(model) }; console_log!("model loaded in {:?}s", (Date::now() - start) / 1000.); let logits_processor = LogitsProcessor::new(299792458, None, None); Ok(Self { model, tokenizer, tokens: vec![], logits_processor, repeat_penalty: 1., repeat_last_n: 64, }) } #[wasm_bindgen] pub fn init_with_prompt( &mut self, prompt: String, temp: f64, top_p: f64, repeat_penalty: f32, repeat_last_n: usize, seed: u64, ) -> Result<String, JsError> { match &mut self.model { SelectedModel::MixFormer(m) => m.clear_kv_cache(), SelectedModel::Quantized(m) => m.clear_kv_cache(), }; let temp = if temp <= 0. { None } else { Some(temp) }; let top_p = if top_p <= 0. || top_p >= 1. { None } else { Some(top_p) }; self.logits_processor = LogitsProcessor::new(seed, temp, top_p); self.repeat_penalty = repeat_penalty; self.repeat_last_n = repeat_last_n; self.tokens.clear(); let tokens = self .tokenizer .encode(prompt, true) .map_err(|m| JsError::new(&m.to_string()))? .get_ids() .to_vec(); let text = self .process(&tokens) .map_err(|m| JsError::new(&m.to_string()))?; Ok(text) } #[wasm_bindgen] pub fn next_token(&mut self) -> Result<String, JsError> { let last_token = *self.tokens.last().unwrap(); let text = self .process(&[last_token]) .map_err(|m| JsError::new(&m.to_string()))?; Ok(text) } } impl Model { fn process(&mut self, tokens: &[u32]) -> candle::Result<String> { let dev = Device::Cpu; let input = Tensor::new(tokens, &dev)?.unsqueeze(0)?; let logits = match &mut self.model { SelectedModel::MixFormer(m) => m.forward(&input)?, SelectedModel::Quantized(m) => m.forward(&input)?, }; let logits = logits.squeeze(0)?.to_dtype(DType::F32)?; let logits = if self.repeat_penalty == 1. { logits } else { let start_at = tokens.len().saturating_sub(self.repeat_last_n); candle_transformers::utils::apply_repeat_penalty( &logits, self.repeat_penalty, &tokens[start_at..], )? }; let next_token = self.logits_processor.sample(&logits)?; self.tokens.push(next_token); let token = match self.tokenizer.decode(&[next_token], false) { Ok(token) => token, Err(e) => { console_log!("error decoding token: {:?}", e); "".to_string() } }; // console_log!("token: {:?}: {:?}", token, next_token); Ok(token) } } fn main() { console_error_panic_hook::set_once(); }
candle/candle-wasm-examples/phi/src/bin/m.rs/0
{ "file_path": "candle/candle-wasm-examples/phi/src/bin/m.rs", "repo_id": "candle", "token_count": 2646 }
62