text
stringlengths
7
328k
id
stringlengths
14
166
metadata
dict
__index_level_0__
int64
0
459
# coding=utf-8 # 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 TimeSformer model. """ import copy import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import TimesformerConfig from transformers.models.auto import get_values 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, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ( MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, TimesformerForVideoClassification, TimesformerModel, ) from transformers.models.timesformer.modeling_timesformer import TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import VideoMAEImageProcessor class TimesformerModelTester: def __init__( self, parent, batch_size=13, image_size=10, num_channels=3, patch_size=2, num_frames=2, 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, num_labels=10, initializer_range=0.02, attention_type="divided_space_time", scope=None, ): self.parent = parent self.batch_size = batch_size self.image_size = image_size self.num_channels = num_channels self.patch_size = patch_size self.num_frames = num_frames 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.attention_type = attention_type self.initializer_range = initializer_range self.scope = scope self.num_labels = num_labels # in TimeSformer, the number of spatial tokens equals num_frames * num_patches per frame + 1 CLS token self.num_patches_per_frame = (image_size // patch_size) ** 2 self.seq_length = (num_frames) * self.num_patches_per_frame + 1 def prepare_config_and_inputs(self): pixel_values = floats_tensor( [self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size] ) labels = None if self.use_labels: labels = ids_tensor([self.batch_size], self.num_labels) config = self.get_config() return config, pixel_values, labels def get_config(self): config = TimesformerConfig( image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, num_frames=self.num_frames, 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, initializer_range=self.initializer_range, attention_type=self.attention_type, ) config.num_labels = self.num_labels return config def create_and_check_model(self, config, pixel_values, labels): model = TimesformerModel(config=config) model.to(torch_device) model.eval() result = model(pixel_values) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) def create_and_check_for_video_classification(self, config, pixel_values, labels): model = TimesformerForVideoClassification(config) model.to(torch_device) model.eval() result = model(pixel_values) # verify the logits shape expected_shape = torch.Size((self.batch_size, self.num_labels)) self.parent.assertEqual(result.logits.shape, expected_shape) 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 TimesformerModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): """ Here we also overwrite some of the tests of test_modeling_common.py, as TimeSformer does not use input_ids, inputs_embeds, attention_mask and seq_length. """ all_model_classes = (TimesformerModel, TimesformerForVideoClassification) if is_torch_available() else () pipeline_model_mapping = ( {"feature-extraction": TimesformerModel, "video-classification": TimesformerForVideoClassification} if is_torch_available() else {} ) test_pruning = False test_torchscript = False test_resize_embeddings = False test_head_masking = False def setUp(self): self.model_tester = TimesformerModelTester(self) self.config_tester = ConfigTester( self, config_class=TimesformerConfig, has_text_modality=False, hidden_size=37 ) def _prepare_for_class(self, inputs_dict, model_class, return_labels=False): inputs_dict = copy.deepcopy(inputs_dict) if return_labels: if model_class in get_values(MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING): inputs_dict["labels"] = torch.zeros( self.model_tester.batch_size, dtype=torch.long, device=torch_device ) return inputs_dict def test_config(self): self.config_tester.run_common_tests() @unittest.skip(reason="TimeSformer does not use inputs_embeds") def test_inputs_embeds(self): pass def test_model_common_attributes(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_for_video_classification(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_video_classification(*config_and_inputs) @slow def test_model_from_pretrained(self): for model_name in TIMESFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: model = TimesformerModel.from_pretrained(model_name) self.assertIsNotNone(model) def test_attention_outputs(self): if not self.has_attentions: pass else: config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() config.return_dict = True for model_class in self.all_model_classes: seq_len = self.model_tester.seq_length num_frames = self.model_tester.num_frames inputs_dict["output_attentions"] = True inputs_dict["output_hidden_states"] = False config.return_dict = 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) # 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) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(attentions[0].shape[-3:]), [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1], ) 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)) self.assertEqual(out_len + 1, len(outputs)) self_attentions = outputs.attentions self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers) # attentions has shape (batch_size x num_frames) x num_heads x (num_patches per frame + 1) x (num_patches per frame + 1) self.assertListEqual( list(self_attentions[0].shape[-3:]), [self.model_tester.num_attention_heads, seq_len // num_frames + 1, seq_len // num_frames + 1], ) 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 = self.model_tester.num_hidden_layers + 1 self.assertEqual(len(hidden_states), expected_num_layers) seq_length = self.model_tester.seq_length 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) # We will verify our results on a video of eating spaghetti # Frame indices used: [164 168 172 176 181 185 189 193 198 202 206 210 215 219 223 227] def prepare_video(): file = hf_hub_download( repo_id="hf-internal-testing/spaghetti-video", filename="eating_spaghetti.npy", repo_type="dataset" ) video = np.load(file) return list(video) @require_torch @require_vision class TimesformerModelIntegrationTest(unittest.TestCase): @cached_property def default_image_processor(self): # logits were tested with a different mean and std, so we use the same here return ( VideoMAEImageProcessor(image_mean=[0.5, 0.5, 0.5], image_std=[0.5, 0.5, 0.5]) if is_vision_available() else None ) @slow def test_inference_for_video_classification(self): model = TimesformerForVideoClassification.from_pretrained("facebook/timesformer-base-finetuned-k400").to( torch_device ) image_processor = self.default_image_processor video = prepare_video() inputs = image_processor(video[:8], return_tensors="pt").to(torch_device) # forward pass with torch.no_grad(): outputs = model(**inputs) # verify the logits expected_shape = torch.Size((1, 400)) self.assertEqual(outputs.logits.shape, expected_shape) expected_slice = torch.tensor([-0.3016, -0.7713, -0.4205]).to(torch_device) self.assertTrue(torch.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4))
transformers/tests/models/timesformer/test_modeling_timesformer.py/0
{ "file_path": "transformers/tests/models/timesformer/test_modeling_timesformer.py", "repo_id": "transformers", "token_count": 5998 }
435
# coding=utf-8 # Copyright 2021 HuggingFace Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from transformers.testing_utils import require_torch, require_vision from transformers.utils import is_vision_available from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs if is_vision_available(): from PIL import Image from transformers import ViltImageProcessor class ViltImageProcessingTester(unittest.TestCase): def __init__( self, parent, batch_size=7, num_channels=3, image_size=18, min_resolution=30, max_resolution=400, do_resize=True, size=None, size_divisor=2, do_normalize=True, image_mean=[0.5, 0.5, 0.5], image_std=[0.5, 0.5, 0.5], ): size = size if size is not None else {"shortest_edge": 30} self.parent = parent self.batch_size = batch_size self.num_channels = num_channels self.image_size = image_size self.min_resolution = min_resolution self.max_resolution = max_resolution self.do_resize = do_resize self.size = size self.size_divisor = size_divisor self.do_normalize = do_normalize self.image_mean = image_mean self.image_std = image_std def prepare_image_processor_dict(self): return { "image_mean": self.image_mean, "image_std": self.image_std, "do_normalize": self.do_normalize, "do_resize": self.do_resize, "size": self.size, "size_divisor": self.size_divisor, } def get_expected_values(self, image_inputs, batched=False): """ This function computes the expected height and width when providing images to ViltImageProcessor, assuming do_resize is set to True with a scalar size and size_divisor. """ if not batched: size = self.size["shortest_edge"] image = image_inputs[0] if isinstance(image, Image.Image): w, h = image.size else: h, w = image.shape[1], image.shape[2] scale = size / min(w, h) if h < w: newh, neww = size, scale * w else: newh, neww = scale * h, size max_size = int((1333 / 800) * size) if max(newh, neww) > max_size: scale = max_size / max(newh, neww) newh = newh * scale neww = neww * scale newh, neww = int(newh + 0.5), int(neww + 0.5) expected_height, expected_width = ( newh // self.size_divisor * self.size_divisor, neww // self.size_divisor * self.size_divisor, ) else: expected_values = [] for image in image_inputs: expected_height, expected_width = self.get_expected_values([image]) expected_values.append((expected_height, expected_width)) expected_height = max(expected_values, key=lambda item: item[0])[0] expected_width = max(expected_values, key=lambda item: item[1])[1] return expected_height, expected_width def expected_output_image_shape(self, images): height, width = self.get_expected_values(images, batched=True) return (self.num_channels, height, width) def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False): return prepare_image_inputs( batch_size=self.batch_size, num_channels=self.num_channels, min_resolution=self.min_resolution, max_resolution=self.max_resolution, equal_resolution=equal_resolution, numpify=numpify, torchify=torchify, ) @require_torch @require_vision class ViltImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase): image_processing_class = ViltImageProcessor if is_vision_available() else None def setUp(self): self.image_processor_tester = ViltImageProcessingTester(self) @property def image_processor_dict(self): return self.image_processor_tester.prepare_image_processor_dict() def test_image_processor_properties(self): image_processing = self.image_processing_class(**self.image_processor_dict) self.assertTrue(hasattr(image_processing, "image_mean")) self.assertTrue(hasattr(image_processing, "image_std")) self.assertTrue(hasattr(image_processing, "do_normalize")) self.assertTrue(hasattr(image_processing, "do_resize")) self.assertTrue(hasattr(image_processing, "size")) self.assertTrue(hasattr(image_processing, "size_divisor")) def test_image_processor_from_dict_with_kwargs(self): image_processor = self.image_processing_class.from_dict(self.image_processor_dict) self.assertEqual(image_processor.size, {"shortest_edge": 30}) image_processor = self.image_processing_class.from_dict(self.image_processor_dict, size=42) self.assertEqual(image_processor.size, {"shortest_edge": 42})
transformers/tests/models/vilt/test_image_processing_vilt.py/0
{ "file_path": "transformers/tests/models/vilt/test_image_processing_vilt.py", "repo_id": "transformers", "token_count": 2455 }
436
# coding=utf-8 # 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 XCLIP model. """ import inspect import os import tempfile import unittest import numpy as np from huggingface_hub import hf_hub_download from transformers import XCLIPConfig, XCLIPTextConfig, XCLIPVisionConfig from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device from transformers.utils import is_torch_available, is_vision_available 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 torch import nn from transformers import XCLIPModel, XCLIPTextModel, XCLIPVisionModel from transformers.models.x_clip.modeling_x_clip import XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from transformers import XCLIPProcessor class XCLIPVisionModelTester: def __init__( self, parent, batch_size=8, image_size=30, patch_size=2, num_channels=3, num_frames=8, # important; the batch size * time must be divisible by the number of frames is_training=True, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=37, mit_hidden_size=64, dropout=0.1, attention_dropout=0.1, 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.num_frames = num_frames self.is_training = is_training 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.mit_hidden_size = mit_hidden_size self.dropout = dropout self.attention_dropout = attention_dropout self.initializer_range = initializer_range self.scope = scope # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) num_patches = (image_size // patch_size) ** 2 self.seq_length = num_patches + 1 def prepare_config_and_inputs(self): pixel_values = 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 def get_config(self): return XCLIPVisionConfig( image_size=self.image_size, patch_size=self.patch_size, num_channels=self.num_channels, num_frames=self.num_frames, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, mit_hidden_size=self.mit_hidden_size, dropout=self.dropout, attention_dropout=self.attention_dropout, initializer_range=self.initializer_range, ) def create_and_check_model(self, config, pixel_values): model = XCLIPVisionModel(config=config) model.to(torch_device) model.eval() with torch.no_grad(): result = model(pixel_values) # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) image_size = (self.image_size, self.image_size) patch_size = (self.patch_size, self.patch_size) num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) self.parent.assertEqual( result.last_hidden_state.shape, (self.batch_size * self.num_frames, num_patches + 1, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape, (self.batch_size * self.num_frames, self.hidden_size)) 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 class XCLIPVisionModelTest(ModelTesterMixin, unittest.TestCase): """ Here we also overwrite some of the tests of test_modeling_common.py, as X-CLIP does not use input_ids, inputs_embeds, attention_mask and seq_length. """ all_model_classes = (XCLIPVisionModel,) if is_torch_available() else () fx_compatible = False test_pruning = False test_resize_embeddings = False test_head_masking = False def setUp(self): self.model_tester = XCLIPVisionModelTester(self) self.config_tester = ConfigTester( self, config_class=XCLIPVisionConfig, has_text_modality=False, hidden_size=37 ) def test_config(self): self.config_tester.run_common_tests() @unittest.skip(reason="X-CLIP does not use inputs_embeds") def test_inputs_embeds(self): pass def test_model_common_attributes(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_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_model(self): config_and_inputs = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*config_and_inputs) def test_training(self): pass def test_training_gradient_checkpointing(self): pass @unittest.skip( reason="This architecure 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 architecure 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="XCLIPVisionModel has no base class and is not available in MODEL_MAPPING") def test_save_load_fast_init_from_base(self): pass @unittest.skip(reason="XCLIPVisionModel has no base class and is not available in MODEL_MAPPING") def test_save_load_fast_init_to_base(self): pass @slow def test_model_from_pretrained(self): for model_name in XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: model = XCLIPVisionModel.from_pretrained(model_name) self.assertIsNotNone(model) def test_gradient_checkpointing_backward_compatibility(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: if not model_class.supports_gradient_checkpointing: continue print("Model class:", model_class) config.gradient_checkpointing = True model = model_class(config) self.assertTrue(model.is_gradient_checkpointing) def test_attention_outputs(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() config.return_dict = True # we add 1 here due to the special message token in X-CLIP's vision encoder seq_len = getattr(self.model_tester, "seq_length", None) + 1 encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", 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(config) model.to(torch_device) model.eval() with torch.no_grad(): outputs = model(**self._prepare_for_class(inputs_dict, model_class)) self.assertEqual(len(outputs.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)) self.assertEqual(len(outputs.attentions), self.model_tester.num_hidden_layers) self.assertListEqual( list(outputs.attentions[0].shape[-3:]), [self.model_tester.num_attention_heads, encoder_seq_length, encoder_seq_length], ) 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)) self.assertEqual(out_len + 1, 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, encoder_seq_length, encoder_seq_length], ) @require_torch_multi_gpu def test_multi_gpu_data_parallel_forward(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() # some params shouldn't be scattered by nn.DataParallel # so just remove them if they are present. blacklist_non_batched_params = ["head_mask", "decoder_head_mask", "cross_attn_head_mask"] for k in blacklist_non_batched_params: inputs_dict.pop(k, None) # move input tensors to cuda:O for k, v in inputs_dict.items(): if torch.is_tensor(v): inputs_dict[k] = v.to(0) for model_class in self.all_model_classes: model = model_class(config=config) model.to(0) model.eval() # Wrap model in nn.DataParallel model = nn.DataParallel(model) with torch.no_grad(): test = self._prepare_for_class(inputs_dict, model_class) for k, v in test.items(): if isinstance(v, torch.Tensor): print(k, v.shape) else: print(k, v) _ = model(**self._prepare_for_class(inputs_dict, model_class)) class XCLIPTextModelTester: def __init__( self, parent, batch_size=8, seq_length=7, is_training=True, use_input_mask=True, use_labels=True, vocab_size=99, hidden_size=32, num_hidden_layers=2, num_attention_heads=4, intermediate_size=37, dropout=0.1, attention_dropout=0.1, max_position_embeddings=512, initializer_range=0.02, scope=None, ): self.parent = parent self.batch_size = batch_size self.seq_length = seq_length self.is_training = is_training self.use_input_mask = use_input_mask self.use_labels = use_labels self.vocab_size = vocab_size self.hidden_size = hidden_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.intermediate_size = intermediate_size self.dropout = dropout self.attention_dropout = attention_dropout self.max_position_embeddings = max_position_embeddings self.initializer_range = initializer_range self.scope = scope def prepare_config_and_inputs(self): input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) input_mask = None if self.use_input_mask: input_mask = random_attention_mask([self.batch_size, self.seq_length]) if input_mask is not None: batch_size, seq_length = input_mask.shape rnd_start_indices = np.random.randint(1, seq_length - 1, size=(batch_size,)) for batch_idx, start_index in enumerate(rnd_start_indices): input_mask[batch_idx, :start_index] = 1 input_mask[batch_idx, start_index:] = 0 config = self.get_config() return config, input_ids, input_mask def get_config(self): return XCLIPTextConfig( vocab_size=self.vocab_size, hidden_size=self.hidden_size, num_hidden_layers=self.num_hidden_layers, num_attention_heads=self.num_attention_heads, intermediate_size=self.intermediate_size, dropout=self.dropout, attention_dropout=self.attention_dropout, max_position_embeddings=self.max_position_embeddings, initializer_range=self.initializer_range, ) def create_and_check_model(self, config, input_ids, input_mask): model = XCLIPTextModel(config=config) model.to(torch_device) model.eval() with torch.no_grad(): result = model(input_ids, attention_mask=input_mask) result = model(input_ids) self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size)) self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size)) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, input_ids, input_mask = config_and_inputs inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class XCLIPTextModelTest(ModelTesterMixin, unittest.TestCase): all_model_classes = (XCLIPTextModel,) if is_torch_available() else () fx_compatible = False test_pruning = False test_head_masking = False def setUp(self): self.model_tester = XCLIPTextModelTester(self) self.config_tester = ConfigTester(self, config_class=XCLIPTextConfig, 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_training(self): pass def test_training_gradient_checkpointing(self): pass @unittest.skip( reason="This architecure 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 architecure 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="X-CLIP does not use inputs_embeds") def test_inputs_embeds(self): pass @unittest.skip(reason="XCLIPTextModel has no base class and is not available in MODEL_MAPPING") def test_save_load_fast_init_from_base(self): pass @unittest.skip(reason="XCLIPTextModel has no base class and is not available in MODEL_MAPPING") def test_save_load_fast_init_to_base(self): pass @slow def test_model_from_pretrained(self): for model_name in XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: model = XCLIPTextModel.from_pretrained(model_name) self.assertIsNotNone(model) class XCLIPModelTester: def __init__( self, parent, text_kwargs=None, vision_kwargs=None, projection_dim=64, mit_hidden_size=64, is_training=True, ): if text_kwargs is None: text_kwargs = {} if vision_kwargs is None: vision_kwargs = {} self.parent = parent self.projection_dim = projection_dim self.mit_hidden_size = mit_hidden_size self.text_model_tester = XCLIPTextModelTester(parent, **text_kwargs) self.vision_model_tester = XCLIPVisionModelTester(parent, **vision_kwargs) self.batch_size = self.text_model_tester.batch_size # need bs for batching_equivalence test self.is_training = is_training def prepare_config_and_inputs(self): text_config, input_ids, attention_mask = self.text_model_tester.prepare_config_and_inputs() vision_config, _ = self.vision_model_tester.prepare_config_and_inputs() pixel_values = floats_tensor( [ self.vision_model_tester.batch_size, self.vision_model_tester.num_frames, self.vision_model_tester.num_channels, self.vision_model_tester.image_size, self.vision_model_tester.image_size, ] ) config = self.get_config() return config, input_ids, attention_mask, pixel_values def get_config(self): return XCLIPConfig.from_text_vision_configs( self.text_model_tester.get_config(), self.vision_model_tester.get_config(), projection_dim=self.projection_dim, ) def create_and_check_model(self, config, input_ids, attention_mask, pixel_values): model = XCLIPModel(config).to(torch_device).eval() with torch.no_grad(): result = model(input_ids, pixel_values, attention_mask) self.parent.assertEqual( result.logits_per_video.shape, (self.vision_model_tester.batch_size, self.text_model_tester.batch_size), ) self.parent.assertEqual( result.logits_per_text.shape, (self.text_model_tester.batch_size, self.vision_model_tester.batch_size), ) def prepare_config_and_inputs_for_common(self): config_and_inputs = self.prepare_config_and_inputs() config, input_ids, attention_mask, pixel_values = config_and_inputs inputs_dict = { "input_ids": input_ids, "attention_mask": attention_mask, "pixel_values": pixel_values, "return_loss": True, } return config, inputs_dict @require_torch class XCLIPModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): all_model_classes = (XCLIPModel,) if is_torch_available() else () pipeline_model_mapping = {"feature-extraction": XCLIPModel} if is_torch_available() else {} fx_compatible = False test_head_masking = False test_pruning = False test_resize_embeddings = False test_attention_outputs = False test_torchscript = False maxdiff = None def setUp(self): self.model_tester = XCLIPModelTester(self) 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="Hidden_states is tested in individual model tests") def test_hidden_states_output(self): pass @unittest.skip(reason="Inputs_embeds is tested in individual model tests") def test_inputs_embeds(self): pass @unittest.skip(reason="Retain_grad is tested in individual model tests") def test_retain_grad_hidden_states_attentions(self): pass @unittest.skip(reason="XCLIPModel does not have input/output embeddings") def test_model_common_attributes(self): pass @unittest.skip(reason="XCLIPModel does not support feedforward chunking") def test_feed_forward_chunking(self): pass # override as the `logit_scale`, `prompts_generator.alpha` parameters require special treatment 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(): if param.requires_grad: # check if `logit_scale` is initilized as per the original implementation if name == "logit_scale": self.assertAlmostEqual( param.data.item(), np.log(1 / 0.07), delta=1e-3, msg=f"Parameter {name} of model {model_class} seems not properly initialized", ) elif name == "prompts_generator.alpha": self.assertAlmostEqual(param.data.mean().item(), model.config.prompt_alpha) 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", ) def _create_and_check_torchscript(self, config, inputs_dict): if not self.test_torchscript: return configs_no_init = _config_zero_init(config) # To be sure we have no Nan configs_no_init.torchscript = True configs_no_init.return_dict = False for model_class in self.all_model_classes: model = model_class(config=configs_no_init) model.to(torch_device) model.eval() try: input_ids = inputs_dict["input_ids"] pixel_values = inputs_dict["pixel_values"] # X-CLIP needs pixel_values traced_model = torch.jit.trace(model, (input_ids, pixel_values)) except RuntimeError: self.fail("Couldn't trace module.") with tempfile.TemporaryDirectory() as tmp_dir_name: pt_file_name = os.path.join(tmp_dir_name, "traced_model.pt") try: torch.jit.save(traced_model, pt_file_name) except Exception: self.fail("Couldn't save module.") try: loaded_model = torch.jit.load(pt_file_name) except Exception: self.fail("Couldn't load module.") model.to(torch_device) model.eval() loaded_model.to(torch_device) loaded_model.eval() model_state_dict = model.state_dict() loaded_model_state_dict = loaded_model.state_dict() non_persistent_buffers = {} for key in loaded_model_state_dict.keys(): if key not in model_state_dict.keys(): non_persistent_buffers[key] = loaded_model_state_dict[key] loaded_model_state_dict = { key: value for key, value in loaded_model_state_dict.items() if key not in non_persistent_buffers } self.assertEqual(set(model_state_dict.keys()), set(loaded_model_state_dict.keys())) model_buffers = list(model.buffers()) for non_persistent_buffer in non_persistent_buffers.values(): found_buffer = False for i, model_buffer in enumerate(model_buffers): if torch.equal(non_persistent_buffer, model_buffer): found_buffer = True break self.assertTrue(found_buffer) model_buffers.pop(i) models_equal = True for layer_name, p1 in model_state_dict.items(): p2 = loaded_model_state_dict[layer_name] if p1.data.ne(p2.data).sum() > 0: models_equal = False self.assertTrue(models_equal) def test_load_vision_text_config(self): config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() # Save XCLIPConfig and check if we can load XCLIPVisionConfig from it with tempfile.TemporaryDirectory() as tmp_dir_name: config.save_pretrained(tmp_dir_name) vision_config = XCLIPVisionConfig.from_pretrained(tmp_dir_name) self.assertDictEqual(config.vision_config.to_dict(), vision_config.to_dict()) # Save XCLIPConfig and check if we can load XCLIPTextConfig from it with tempfile.TemporaryDirectory() as tmp_dir_name: config.save_pretrained(tmp_dir_name) text_config = XCLIPTextConfig.from_pretrained(tmp_dir_name) self.assertDictEqual(config.text_config.to_dict(), text_config.to_dict()) @slow def test_model_from_pretrained(self): for model_name in XCLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: model = XCLIPModel.from_pretrained(model_name) self.assertIsNotNone(model) # We will verify our results on a spaghetti video def prepare_video(): file = hf_hub_download( repo_id="hf-internal-testing/spaghetti-video", filename="eating_spaghetti_8_frames.npy", repo_type="dataset" ) video = np.load(file) return list(video) @require_vision @require_torch class XCLIPModelIntegrationTest(unittest.TestCase): @slow def test_inference(self): model_name = "microsoft/xclip-base-patch32" model = XCLIPModel.from_pretrained(model_name).to(torch_device) processor = XCLIPProcessor.from_pretrained(model_name) video = prepare_video() inputs = processor( text=["playing sports", "eating spaghetti", "go shopping"], videos=video, return_tensors="pt", padding=True ).to(torch_device) # forward pass with torch.no_grad(): outputs = model(**inputs) # verify the logits self.assertEqual( outputs.logits_per_video.shape, torch.Size((inputs.pixel_values.shape[0], inputs.input_ids.shape[0])), ) self.assertEqual( outputs.logits_per_text.shape, torch.Size((inputs.input_ids.shape[0], inputs.pixel_values.shape[0])), ) expected_logits = torch.tensor([[14.0181, 20.2771, 14.4776]], device=torch_device) self.assertTrue(torch.allclose(outputs.logits_per_video, expected_logits, atol=1e-3))
transformers/tests/models/x_clip/test_modeling_x_clip.py/0
{ "file_path": "transformers/tests/models/x_clip/test_modeling_x_clip.py", "repo_id": "transformers", "token_count": 12644 }
437
# coding=utf-8 # Copyright 2020 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from transformers import is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow if is_torch_available(): import torch from transformers import XLMRobertaModel @require_sentencepiece @require_tokenizers @require_torch class XLMRobertaModelIntegrationTest(unittest.TestCase): @slow def test_xlm_roberta_base(self): model = XLMRobertaModel.from_pretrained("FacebookAI/xlm-roberta-base") input_ids = torch.tensor([[0, 581, 10269, 83, 99942, 136, 60742, 23, 70, 80583, 18276, 2]]) # The dog is cute and lives in the garden house expected_output_shape = torch.Size((1, 12, 768)) # batch_size, sequence_length, embedding_vector_dim expected_output_values_last_dim = torch.tensor( [[-0.0101, 0.1218, -0.0803, 0.0801, 0.1327, 0.0776, -0.1215, 0.2383, 0.3338, 0.3106, 0.0300, 0.0252]] ) # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base') # xlmr.eval() # expected_output_values_last_dim = xlmr.extract_features(input_ids[0])[:, :, -1] with torch.no_grad(): output = model(input_ids)["last_hidden_state"].detach() self.assertEqual(output.shape, expected_output_shape) # compare the actual values for a slice of last dim self.assertTrue(torch.allclose(output[:, :, -1], expected_output_values_last_dim, atol=1e-3)) @slow def test_xlm_roberta_large(self): model = XLMRobertaModel.from_pretrained("FacebookAI/xlm-roberta-large") input_ids = torch.tensor([[0, 581, 10269, 83, 99942, 136, 60742, 23, 70, 80583, 18276, 2]]) # The dog is cute and lives in the garden house expected_output_shape = torch.Size((1, 12, 1024)) # batch_size, sequence_length, embedding_vector_dim expected_output_values_last_dim = torch.tensor( [[-0.0699, -0.0318, 0.0705, -0.1241, 0.0999, -0.0520, 0.1004, -0.1838, -0.4704, 0.1437, 0.0821, 0.0126]] ) # xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.large') # xlmr.eval() # expected_output_values_last_dim = xlmr.extract_features(input_ids[0])[:, :, -1] with torch.no_grad(): output = model(input_ids)["last_hidden_state"].detach() self.assertEqual(output.shape, expected_output_shape) # compare the actual values for a slice of last dim self.assertTrue(torch.allclose(output[:, :, -1], expected_output_values_last_dim, atol=1e-3))
transformers/tests/models/xlm_roberta/test_modeling_xlm_roberta.py/0
{ "file_path": "transformers/tests/models/xlm_roberta/test_modeling_xlm_roberta.py", "repo_id": "transformers", "token_count": 1283 }
438
# coding=utf-8 # Copyright 2020 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import tempfile import unittest from transformers import is_torch_available from transformers.testing_utils import require_torch if is_torch_available(): import torch from torch import nn from transformers import ( Adafactor, AdamW, get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_inverse_sqrt_schedule, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, ) def unwrap_schedule(scheduler, num_steps=10): lrs = [] for _ in range(num_steps): lrs.append(scheduler.get_lr()[0]) scheduler.step() return lrs def unwrap_and_save_reload_schedule(scheduler, num_steps=10): lrs = [] for step in range(num_steps): lrs.append(scheduler.get_lr()[0]) scheduler.step() if step == num_steps // 2: with tempfile.TemporaryDirectory() as tmpdirname: file_name = os.path.join(tmpdirname, "schedule.bin") torch.save(scheduler.state_dict(), file_name) state_dict = torch.load(file_name) scheduler.load_state_dict(state_dict) return lrs @require_torch class OptimizationTest(unittest.TestCase): def assertListAlmostEqual(self, list1, list2, tol): self.assertEqual(len(list1), len(list2)) for a, b in zip(list1, list2): self.assertAlmostEqual(a, b, delta=tol) def test_adam_w(self): w = torch.tensor([0.1, -0.2, -0.1], requires_grad=True) target = torch.tensor([0.4, 0.2, -0.5]) criterion = nn.MSELoss() # No warmup, constant schedule, no gradient clipping optimizer = AdamW(params=[w], lr=2e-1, weight_decay=0.0) for _ in range(100): loss = criterion(w, target) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist(), [0.4, 0.2, -0.5], tol=1e-2) def test_adafactor(self): w = torch.tensor([0.1, -0.2, -0.1], requires_grad=True) target = torch.tensor([0.4, 0.2, -0.5]) criterion = nn.MSELoss() # No warmup, constant schedule, no gradient clipping optimizer = Adafactor( params=[w], lr=1e-2, eps=(1e-30, 1e-3), clip_threshold=1.0, decay_rate=-0.8, beta1=None, weight_decay=0.0, relative_step=False, scale_parameter=False, warmup_init=False, ) for _ in range(1000): loss = criterion(w, target) loss.backward() optimizer.step() w.grad.detach_() # No zero_grad() function on simple tensors. we do it ourselves. w.grad.zero_() self.assertListAlmostEqual(w.tolist(), [0.4, 0.2, -0.5], tol=1e-2) @require_torch class ScheduleInitTest(unittest.TestCase): m = nn.Linear(50, 50) if is_torch_available() else None optimizer = AdamW(m.parameters(), lr=10.0) if is_torch_available() else None num_steps = 10 def assertListAlmostEqual(self, list1, list2, tol, msg=None): self.assertEqual(len(list1), len(list2)) for a, b in zip(list1, list2): self.assertAlmostEqual(a, b, delta=tol, msg=msg) def test_schedulers(self): common_kwargs = {"num_warmup_steps": 2, "num_training_steps": 10} # schedulers doct format # function: (sched_args_dict, expected_learning_rates) scheds = { get_constant_schedule: ({}, [10.0] * self.num_steps), get_constant_schedule_with_warmup: ( {"num_warmup_steps": 4}, [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0], ), get_linear_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25], ), get_cosine_schedule_with_warmup: ( {**common_kwargs}, [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38], ), get_cosine_with_hard_restarts_schedule_with_warmup: ( {**common_kwargs, "num_cycles": 2}, [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46], ), get_polynomial_decay_schedule_with_warmup: ( {**common_kwargs, "power": 2.0, "lr_end": 1e-7}, [0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156], ), get_inverse_sqrt_schedule: ( {"num_warmup_steps": 2}, [0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714], ), } for scheduler_func, data in scheds.items(): kwargs, expected_learning_rates = data scheduler = scheduler_func(self.optimizer, **kwargs) self.assertEqual(len([scheduler.get_lr()[0]]), 1) lrs_1 = unwrap_schedule(scheduler, self.num_steps) self.assertListAlmostEqual( lrs_1, expected_learning_rates, tol=1e-2, msg=f"failed for {scheduler_func} in normal scheduler", ) scheduler = scheduler_func(self.optimizer, **kwargs) if scheduler_func.__name__ != "get_constant_schedule": LambdaScheduleWrapper.wrap_scheduler(scheduler) # wrap to test picklability of the schedule lrs_2 = unwrap_and_save_reload_schedule(scheduler, self.num_steps) self.assertListEqual(lrs_1, lrs_2, msg=f"failed for {scheduler_func} in save and reload") class LambdaScheduleWrapper: """See https://github.com/huggingface/transformers/issues/21689""" def __init__(self, fn): self.fn = fn def __call__(self, *args, **kwargs): return self.fn(*args, **kwargs) @classmethod def wrap_scheduler(self, scheduler): scheduler.lr_lambdas = list(map(self, scheduler.lr_lambdas))
transformers/tests/optimization/test_optimization.py/0
{ "file_path": "transformers/tests/optimization/test_optimization.py", "repo_id": "transformers", "token_count": 3392 }
439
# Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import requests from transformers import MODEL_FOR_VISION_2_SEQ_MAPPING, TF_MODEL_FOR_VISION_2_SEQ_MAPPING, is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class Image: @staticmethod def open(*args, **kwargs): pass @is_pipeline_test @require_vision class ImageToTextPipelineTests(unittest.TestCase): model_mapping = MODEL_FOR_VISION_2_SEQ_MAPPING tf_model_mapping = TF_MODEL_FOR_VISION_2_SEQ_MAPPING def get_test_pipeline(self, model, tokenizer, processor): pipe = pipeline("image-to-text", model=model, tokenizer=tokenizer, image_processor=processor) examples = [ Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"), "./tests/fixtures/tests_samples/COCO/000000039769.png", ] return pipe, examples def run_pipeline_test(self, pipe, examples): outputs = pipe(examples) self.assertEqual( outputs, [ [{"generated_text": ANY(str)}], [{"generated_text": ANY(str)}], ], ) @require_tf def test_small_model_tf(self): pipe = pipeline("image-to-text", model="hf-internal-testing/tiny-random-vit-gpt2", framework="tf") image = "./tests/fixtures/tests_samples/COCO/000000039769.png" outputs = pipe(image) self.assertEqual( outputs, [ { "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO" }, ], ) outputs = pipe([image, image]) self.assertEqual( outputs, [ [ { "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO" } ], [ { "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO" } ], ], ) outputs = pipe(image, max_new_tokens=1) self.assertEqual( outputs, [{"generated_text": "growth"}], ) @require_torch def test_small_model_pt(self): pipe = pipeline("image-to-text", model="hf-internal-testing/tiny-random-vit-gpt2") image = "./tests/fixtures/tests_samples/COCO/000000039769.png" outputs = pipe(image) self.assertEqual( outputs, [ { "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO" }, ], ) outputs = pipe([image, image]) self.assertEqual( outputs, [ [ { "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO" } ], [ { "generated_text": "growthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthgrowthGOGO" } ], ], ) @require_torch def test_small_model_pt_conditional(self): pipe = pipeline("image-to-text", model="hf-internal-testing/tiny-random-BlipForConditionalGeneration") image = "./tests/fixtures/tests_samples/COCO/000000039769.png" prompt = "a photo of" outputs = pipe(image, prompt=prompt) self.assertTrue(outputs[0]["generated_text"].startswith(prompt)) @require_torch def test_consistent_batching_behaviour(self): pipe = pipeline("image-to-text", model="hf-internal-testing/tiny-random-BlipForConditionalGeneration") image = "./tests/fixtures/tests_samples/COCO/000000039769.png" prompt = "a photo of" outputs = pipe([image, image], prompt=prompt) self.assertTrue(outputs[0][0]["generated_text"].startswith(prompt)) self.assertTrue(outputs[1][0]["generated_text"].startswith(prompt)) outputs = pipe([image, image], prompt=prompt, batch_size=2) self.assertTrue(outputs[0][0]["generated_text"].startswith(prompt)) self.assertTrue(outputs[1][0]["generated_text"].startswith(prompt)) from torch.utils.data import Dataset class MyDataset(Dataset): def __len__(self): return 5 def __getitem__(self, i): return "./tests/fixtures/tests_samples/COCO/000000039769.png" dataset = MyDataset() for batch_size in (1, 2, 4): outputs = pipe(dataset, prompt=prompt, batch_size=batch_size if batch_size > 1 else None) self.assertTrue(list(outputs)[0][0]["generated_text"].startswith(prompt)) self.assertTrue(list(outputs)[1][0]["generated_text"].startswith(prompt)) @slow @require_torch def test_large_model_pt(self): pipe = pipeline("image-to-text", model="ydshieh/vit-gpt2-coco-en") image = "./tests/fixtures/tests_samples/COCO/000000039769.png" outputs = pipe(image) self.assertEqual(outputs, [{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}]) outputs = pipe([image, image]) self.assertEqual( outputs, [ [{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}], [{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}], ], ) @slow @require_torch def test_generation_pt_blip(self): pipe = pipeline("image-to-text", model="Salesforce/blip-image-captioning-base") url = "https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/pokemon.png" image = Image.open(requests.get(url, stream=True).raw) outputs = pipe(image) self.assertEqual(outputs, [{"generated_text": "a pink pokemon pokemon with a blue shirt and a blue shirt"}]) @slow @require_torch def test_generation_pt_git(self): pipe = pipeline("image-to-text", model="microsoft/git-base-coco") url = "https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/pokemon.png" image = Image.open(requests.get(url, stream=True).raw) outputs = pipe(image) self.assertEqual(outputs, [{"generated_text": "a cartoon of a purple character."}]) @slow @require_torch def test_conditional_generation_pt_blip(self): pipe = pipeline("image-to-text", model="Salesforce/blip-image-captioning-base") url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg" image = Image.open(requests.get(url, stream=True).raw) prompt = "a photography of" outputs = pipe(image, prompt=prompt) self.assertEqual(outputs, [{"generated_text": "a photography of a volcano"}]) with self.assertRaises(ValueError): outputs = pipe([image, image], prompt=[prompt, prompt]) @slow @require_torch def test_conditional_generation_pt_git(self): pipe = pipeline("image-to-text", model="microsoft/git-base-coco") url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg" image = Image.open(requests.get(url, stream=True).raw) prompt = "a photo of a" outputs = pipe(image, prompt=prompt) self.assertEqual(outputs, [{"generated_text": "a photo of a tent with a tent and a tent in the background."}]) with self.assertRaises(ValueError): outputs = pipe([image, image], prompt=[prompt, prompt]) @slow @require_torch def test_conditional_generation_pt_pix2struct(self): pipe = pipeline("image-to-text", model="google/pix2struct-ai2d-base") url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg" image = Image.open(requests.get(url, stream=True).raw) prompt = "What does the label 15 represent? (1) lava (2) core (3) tunnel (4) ash cloud" outputs = pipe(image, prompt=prompt) self.assertEqual(outputs, [{"generated_text": "ash cloud"}]) with self.assertRaises(ValueError): outputs = pipe([image, image], prompt=[prompt, prompt]) @slow @require_tf def test_large_model_tf(self): pipe = pipeline("image-to-text", model="ydshieh/vit-gpt2-coco-en", framework="tf") image = "./tests/fixtures/tests_samples/COCO/000000039769.png" outputs = pipe(image) self.assertEqual(outputs, [{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}]) outputs = pipe([image, image]) self.assertEqual( outputs, [ [{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}], [{"generated_text": "a cat laying on a blanket next to a cat laying on a bed "}], ], ) @slow @require_torch def test_conditional_generation_llava(self): pipe = pipeline("image-to-text", model="llava-hf/bakLlava-v1-hf") prompt = ( "<image>\nUSER: What does the label 15 represent? (1) lava (2) core (3) tunnel (4) ash cloud?\nASSISTANT:" ) outputs = pipe( "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg", prompt=prompt, generate_kwargs={"max_new_tokens": 200}, ) self.assertEqual( outputs, [ { "generated_text": "<image> \nUSER: What does the label 15 represent? (1) lava (2) core (3) tunnel (4) ash cloud?\nASSISTANT: Lava" } ], ) @slow @require_torch def test_nougat(self): pipe = pipeline("image-to-text", "facebook/nougat-base") outputs = pipe("https://huggingface.co/datasets/Xenova/transformers.js-docs/resolve/main/nougat_paper.png") self.assertEqual( outputs, [{"generated_text": "# Nougat: Neural Optical Understanding for Academic Documents\n\n Lukas Blec"}], )
transformers/tests/pipelines/test_pipelines_image_to_text.py/0
{ "file_path": "transformers/tests/pipelines/test_pipelines_image_to_text.py", "repo_id": "transformers", "token_count": 5160 }
440
# 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 unittest from transformers import is_vision_available from transformers.pipelines import pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_tf, require_torch, require_vision, slow, ) from .test_pipelines_common import ANY if is_vision_available(): from PIL import Image else: class Image: @staticmethod def open(*args, **kwargs): pass @is_pipeline_test @require_vision class ZeroShotImageClassificationPipelineTests(unittest.TestCase): # Deactivating auto tests since we don't have a good MODEL_FOR_XX mapping, # and only CLIP would be there for now. # model_mapping = {CLIPConfig: CLIPModel} # def get_test_pipeline(self, model, tokenizer, processor): # if tokenizer is None: # # Side effect of no Fast Tokenizer class for these model, so skipping # # But the slow tokenizer test should still run as they're quite small # self.skipTest("No tokenizer available") # return # # return None, None # image_classifier = ZeroShotImageClassificationPipeline( # model=model, tokenizer=tokenizer, feature_extractor=processor # ) # # test with a raw waveform # image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") # image2 = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") # return image_classifier, [image, image2] # def run_pipeline_test(self, pipe, examples): # image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") # outputs = pipe(image, candidate_labels=["A", "B"]) # self.assertEqual(outputs, {"text": ANY(str)}) # # Batching # outputs = pipe([image] * 3, batch_size=2, candidate_labels=["A", "B"]) @require_torch def test_small_model_pt(self): image_classifier = pipeline( model="hf-internal-testing/tiny-random-clip-zero-shot-image-classification", ) image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") output = image_classifier(image, candidate_labels=["a", "b", "c"]) # The floating scores are so close, we enter floating error approximation and the order is not guaranteed across # python and torch versions. self.assertIn( nested_simplify(output), [ [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "b"}, {"score": 0.333, "label": "c"}], [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "c"}, {"score": 0.333, "label": "b"}], [{"score": 0.333, "label": "b"}, {"score": 0.333, "label": "a"}, {"score": 0.333, "label": "c"}], ], ) output = image_classifier([image] * 5, candidate_labels=["A", "B", "C"], batch_size=2) self.assertEqual( nested_simplify(output), # Pipeline outputs are supposed to be deterministic and # So we could in theory have real values "A", "B", "C" instead # of ANY(str). # However it seems that in this particular case, the floating # scores are so close, we enter floating error approximation # and the order is not guaranteed anymore with batching. [ [ {"score": 0.333, "label": ANY(str)}, {"score": 0.333, "label": ANY(str)}, {"score": 0.333, "label": ANY(str)}, ], [ {"score": 0.333, "label": ANY(str)}, {"score": 0.333, "label": ANY(str)}, {"score": 0.333, "label": ANY(str)}, ], [ {"score": 0.333, "label": ANY(str)}, {"score": 0.333, "label": ANY(str)}, {"score": 0.333, "label": ANY(str)}, ], [ {"score": 0.333, "label": ANY(str)}, {"score": 0.333, "label": ANY(str)}, {"score": 0.333, "label": ANY(str)}, ], [ {"score": 0.333, "label": ANY(str)}, {"score": 0.333, "label": ANY(str)}, {"score": 0.333, "label": ANY(str)}, ], ], ) @require_tf def test_small_model_tf(self): image_classifier = pipeline( model="hf-internal-testing/tiny-random-clip-zero-shot-image-classification", framework="tf" ) image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") output = image_classifier(image, candidate_labels=["a", "b", "c"]) self.assertEqual( nested_simplify(output), [{"score": 0.333, "label": "a"}, {"score": 0.333, "label": "b"}, {"score": 0.333, "label": "c"}], ) output = image_classifier([image] * 5, candidate_labels=["A", "B", "C"], batch_size=2) self.assertEqual( nested_simplify(output), # Pipeline outputs are supposed to be deterministic and # So we could in theory have real values "A", "B", "C" instead # of ANY(str). # However it seems that in this particular case, the floating # scores are so close, we enter floating error approximation # and the order is not guaranteed anymore with batching. [ [ {"score": 0.333, "label": ANY(str)}, {"score": 0.333, "label": ANY(str)}, {"score": 0.333, "label": ANY(str)}, ], [ {"score": 0.333, "label": ANY(str)}, {"score": 0.333, "label": ANY(str)}, {"score": 0.333, "label": ANY(str)}, ], [ {"score": 0.333, "label": ANY(str)}, {"score": 0.333, "label": ANY(str)}, {"score": 0.333, "label": ANY(str)}, ], [ {"score": 0.333, "label": ANY(str)}, {"score": 0.333, "label": ANY(str)}, {"score": 0.333, "label": ANY(str)}, ], [ {"score": 0.333, "label": ANY(str)}, {"score": 0.333, "label": ANY(str)}, {"score": 0.333, "label": ANY(str)}, ], ], ) @slow @require_torch def test_large_model_pt(self): image_classifier = pipeline( task="zero-shot-image-classification", model="openai/clip-vit-base-patch32", ) # This is an image of 2 cats with remotes and no planes image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") output = image_classifier(image, candidate_labels=["cat", "plane", "remote"]) self.assertEqual( nested_simplify(output), [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ], ) output = image_classifier([image] * 5, candidate_labels=["cat", "plane", "remote"], batch_size=2) self.assertEqual( nested_simplify(output), [ [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ], ] * 5, ) @slow @require_tf def test_large_model_tf(self): image_classifier = pipeline( task="zero-shot-image-classification", model="openai/clip-vit-base-patch32", framework="tf" ) # This is an image of 2 cats with remotes and no planes image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") output = image_classifier(image, candidate_labels=["cat", "plane", "remote"]) self.assertEqual( nested_simplify(output), [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ], ) output = image_classifier([image] * 5, candidate_labels=["cat", "plane", "remote"], batch_size=2) self.assertEqual( nested_simplify(output), [ [ {"score": 0.511, "label": "remote"}, {"score": 0.485, "label": "cat"}, {"score": 0.004, "label": "plane"}, ], ] * 5, ) @slow @require_torch def test_siglip_model_pt(self): image_classifier = pipeline( task="zero-shot-image-classification", model="google/siglip-base-patch16-224", ) # This is an image of 2 cats with remotes and no planes image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") output = image_classifier(image, candidate_labels=["2 cats", "a plane", "a remote"]) self.assertEqual( nested_simplify(output), [ {"score": 0.198, "label": "2 cats"}, {"score": 0.0, "label": "a remote"}, {"score": 0.0, "label": "a plane"}, ], ) output = image_classifier([image] * 5, candidate_labels=["2 cats", "a plane", "a remote"], batch_size=2) self.assertEqual( nested_simplify(output), [ [ {"score": 0.198, "label": "2 cats"}, {"score": 0.0, "label": "a remote"}, {"score": 0.0, "label": "a plane"}, ] ] * 5, )
transformers/tests/pipelines/test_pipelines_zero_shot_image_classification.py/0
{ "file_path": "transformers/tests/pipelines/test_pipelines_zero_shot_image_classification.py", "repo_id": "transformers", "token_count": 5307 }
441
# Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys import unittest git_repo_path = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) sys.path.append(os.path.join(git_repo_path, "utils")) import check_dummies # noqa: E402 from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init # noqa: E402 # Align TRANSFORMERS_PATH in check_dummies with the current path check_dummies.PATH_TO_TRANSFORMERS = os.path.join(git_repo_path, "src", "transformers") DUMMY_CONSTANT = """ {0} = None """ DUMMY_CLASS = """ class {0}(metaclass=DummyObject): _backends = {1} def __init__(self, *args, **kwargs): requires_backends(self, {1}) """ DUMMY_FUNCTION = """ def {0}(*args, **kwargs): requires_backends({0}, {1}) """ class CheckDummiesTester(unittest.TestCase): def test_find_backend(self): no_backend = find_backend(' _import_structure["models.albert"].append("AlbertTokenizerFast")') self.assertIsNone(no_backend) simple_backend = find_backend(" if not is_tokenizers_available():") self.assertEqual(simple_backend, "tokenizers") backend_with_underscore = find_backend(" if not is_tensorflow_text_available():") self.assertEqual(backend_with_underscore, "tensorflow_text") double_backend = find_backend(" if not (is_sentencepiece_available() and is_tokenizers_available()):") self.assertEqual(double_backend, "sentencepiece_and_tokenizers") double_backend_with_underscore = find_backend( " if not (is_sentencepiece_available() and is_tensorflow_text_available()):" ) self.assertEqual(double_backend_with_underscore, "sentencepiece_and_tensorflow_text") triple_backend = find_backend( " if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):" ) self.assertEqual(triple_backend, "sentencepiece_and_tokenizers_and_vision") def test_read_init(self): objects = read_init() # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects self.assertIn("torch", objects) self.assertIn("tensorflow_text", objects) self.assertIn("sentencepiece_and_tokenizers", objects) # Likewise, we can't assert on the exact content of a key self.assertIn("BertModel", objects["torch"]) self.assertIn("TFBertModel", objects["tf"]) self.assertIn("FlaxBertModel", objects["flax"]) self.assertIn("BertModel", objects["torch"]) self.assertIn("TFBertTokenizer", objects["tensorflow_text"]) self.assertIn("convert_slow_tokenizer", objects["sentencepiece_and_tokenizers"]) def test_create_dummy_object(self): dummy_constant = create_dummy_object("CONSTANT", "'torch'") self.assertEqual(dummy_constant, "\nCONSTANT = None\n") dummy_function = create_dummy_object("function", "'torch'") self.assertEqual( dummy_function, "\ndef function(*args, **kwargs):\n requires_backends(function, 'torch')\n" ) expected_dummy_class = """ class FakeClass(metaclass=DummyObject): _backends = 'torch' def __init__(self, *args, **kwargs): requires_backends(self, 'torch') """ dummy_class = create_dummy_object("FakeClass", "'torch'") self.assertEqual(dummy_class, expected_dummy_class) def test_create_dummy_files(self): expected_dummy_pytorch_file = """# This file is autogenerated by the command `make fix-copies`, do not edit. from ..utils import DummyObject, requires_backends CONSTANT = None def function(*args, **kwargs): requires_backends(function, ["torch"]) class FakeClass(metaclass=DummyObject): _backends = ["torch"] def __init__(self, *args, **kwargs): requires_backends(self, ["torch"]) """ dummy_files = create_dummy_files({"torch": ["CONSTANT", "function", "FakeClass"]}) self.assertEqual(dummy_files["torch"], expected_dummy_pytorch_file)
transformers/tests/repo_utils/test_check_dummies.py/0
{ "file_path": "transformers/tests/repo_utils/test_check_dummies.py", "repo_id": "transformers", "token_count": 1800 }
442
# coding=utf-8 # Copyright 2023 HuggingFace Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from parameterized import parameterized from transformers import set_seed from transformers.testing_utils import ( is_torch_available, require_auto_gptq, require_torch, require_torch_gpu, slow, torch_device, ) if is_torch_available(): import torch from transformers import ( AutoModelForCausalLM, AutoTokenizer, DynamicCache, LlamaConfig, LlamaForCausalLM, SinkCache, StaticCache, ) @require_torch class CacheTest(unittest.TestCase): def test_dynamic_cache_retrocompatibility(self): """Tests that we can convert back and forth between the legacy cache format and DynamicCache""" legacy_cache = () new_cache = DynamicCache() # Creates a new cache with 10 layers in both formats for layer_idx in range(10): new_key = torch.rand((2, 4, 8, 16)) new_value = torch.rand((2, 4, 8, 16)) new_cache.update(new_key, new_value, layer_idx) legacy_cache += ((new_key, new_value),) # Sanity check 1: they must have the same shapes self.assertTrue(len(legacy_cache), len(new_cache)) for layer_idx in range(10): self.assertTrue(len(legacy_cache[layer_idx]), len(legacy_cache[layer_idx])) for key_value_idx in range(2): self.assertTrue( legacy_cache[layer_idx][key_value_idx].shape == new_cache[layer_idx][key_value_idx].shape ) # Sanity check 2: we can get the sequence length in multiple ways with DynamicCache, and they return the # expected value self.assertTrue(legacy_cache[0][0].shape[-2] == new_cache[0][0].shape[-2] == new_cache.get_seq_length() == 8) # Sanity check 3: they must be equal, and both support indexing for layer_idx in range(10): for key_value_idx in range(2): self.assertTrue( torch.allclose(new_cache[layer_idx][key_value_idx], legacy_cache[layer_idx][key_value_idx]) ) # Test 1: We can convert from legacy to new with no changes from_legacy = DynamicCache.from_legacy_cache(legacy_cache) for layer_idx in range(10): for key_value_idx in range(2): self.assertTrue( torch.allclose(from_legacy[layer_idx][key_value_idx], legacy_cache[layer_idx][key_value_idx]) ) # Test 2: We can convert from new to legacy with no changes to_legacy = new_cache.to_legacy_cache() for layer_idx in range(10): for key_value_idx in range(2): self.assertTrue( torch.allclose(to_legacy[layer_idx][key_value_idx], new_cache[layer_idx][key_value_idx]) ) def test_reorder_cache_retrocompatibility(self): """Tests that Cache.reorder_cache is retrocompatible with the legacy code path""" legacy_reorder_fn = LlamaForCausalLM._reorder_cache # An example of a legacy `_reorder_cache` function legacy_cache = () new_cache = DynamicCache() # Creates a new cache with 10 layers in both formats for layer_idx in range(10): new_key = torch.rand((4, 4, 8, 16)) new_value = torch.rand((4, 4, 8, 16)) new_cache.update(new_key, new_value, layer_idx) legacy_cache += ((new_key, new_value),) # Let's create some dummy beam indices. From the shape above, it is equivalent to the case where num_beams=4 # and batch_size=1 beam_idx = torch.randint(low=0, high=4, size=(4,)) legacy_cache_reordered = legacy_reorder_fn(legacy_cache, beam_idx) new_cache.reorder_cache(beam_idx) # Let's check that the results are the same for layer_idx in range(10): for key_value_idx in range(2): self.assertTrue( torch.allclose( new_cache[layer_idx][key_value_idx], legacy_cache_reordered[layer_idx][key_value_idx] ) ) def test_static_cache_mha_mqa_gqa(self): """ Tests that static cache works with multi-head attention (MHA), grouped query attention (GQA), and multi-query attention (MQA) """ def _random_kvs(config): # shape for key and values: (batch_size, num_heads, seq_len, head_dim) random_keys = torch.rand( (1, config.num_key_value_heads, 1, config.hidden_size // config.num_attention_heads), device=torch_device, ) random_values = torch.rand( (1, config.num_key_value_heads, 1, config.hidden_size // config.num_attention_heads), device=torch_device, ) return random_keys, random_values mha_config = LlamaConfig(num_attention_heads=32) mha_static_cache = StaticCache(config=mha_config, max_batch_size=1, max_cache_len=10, device=torch_device) cached_keys, cached_values = mha_static_cache.update( *_random_kvs(mha_config), 0, cache_kwargs={"cache_position": torch.arange(1)} ) self.assertTrue(cached_keys.shape == (1, 32, 10, 128)) self.assertTrue(cached_values.shape == (1, 32, 10, 128)) gqa_config = LlamaConfig(num_attention_heads=32, num_key_value_heads=4) gqa_static_cache = StaticCache(config=gqa_config, max_batch_size=1, max_cache_len=10, device=torch_device) cached_keys, cached_values = gqa_static_cache.update( *_random_kvs(gqa_config), 0, cache_kwargs={"cache_position": torch.arange(1)} ) self.assertTrue(cached_keys.shape == (1, 4, 10, 128)) self.assertTrue(cached_values.shape == (1, 4, 10, 128)) mqa_config = LlamaConfig(num_attention_heads=32, num_key_value_heads=1) mqa_static_cache = StaticCache(config=mqa_config, max_batch_size=1, max_cache_len=10, device=torch_device) cached_keys, cached_values = mqa_static_cache.update( *_random_kvs(mqa_config), 0, cache_kwargs={"cache_position": torch.arange(1)} ) self.assertTrue(cached_keys.shape == (1, 1, 10, 128)) self.assertTrue(cached_values.shape == (1, 1, 10, 128)) @require_torch_gpu @slow class CacheIntegrationTest(unittest.TestCase): def test_dynamic_cache_hard(self): tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf", padding_side="left") model = AutoModelForCausalLM.from_pretrained( "meta-llama/Llama-2-7b-hf", device_map="auto", torch_dtype=torch.float16 ) inputs = tokenizer(["Here's everything I know about cats. Cats"], return_tensors="pt").to(model.device) # DynamicCache and the legacy cache format should be equivalent set_seed(0) gen_out_legacy = model.generate(**inputs, do_sample=True, max_new_tokens=256) set_seed(0) gen_out = model.generate(**inputs, do_sample=True, max_new_tokens=256, past_key_values=DynamicCache()) self.assertListEqual(gen_out_legacy.tolist(), gen_out.tolist()) decoded = tokenizer.batch_decode(gen_out, skip_special_tokens=True) expected_text = ( "Here's everything I know about cats. Cats are mysterious creatures. They can't talk, and they don't like " "to be held. They don't play fetch, and they don't like to be hugged. But they do like to be petted.\n" "Cats are also very independent. They don't like to be told what to do, and they don't like to be told " "what to eat. They are also very territorial. They don't like to share their food or their toys.\nCats " "are also very curious. They like to explore, and they like to play. They are also very fast. They can " "run very fast, and they can jump very high.\nCats are also very smart. They can learn tricks, and they " "can solve problems. They are also very playful. They like to play with toys, and they like to play with " "other cats.\nCats are also very affectionate. They like to be petted, and they like to be held. They " "also like to be scratched.\nCats are also very clean. They like to groom themselves, and they like to " "clean their litter box.\nCats are also very independent. They don't" ) self.assertEqual(decoded[0], expected_text) def test_dynamic_cache_batched(self): tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf", padding_side="left") tokenizer.pad_token = tokenizer.eos_token model = AutoModelForCausalLM.from_pretrained( "meta-llama/Llama-2-7b-hf", device_map="auto", torch_dtype=torch.float16 ) inputs = tokenizer(["A sequence: 1, 2, 3, 4, 5", "A sequence: A, B, C"], padding=True, return_tensors="pt").to( model.device ) gen_out = model.generate(**inputs, do_sample=False, max_new_tokens=10, past_key_values=DynamicCache()) decoded = tokenizer.batch_decode(gen_out, skip_special_tokens=True) expected_text = ["A sequence: 1, 2, 3, 4, 5, 6, 7, 8,", "A sequence: A, B, C, D, E, F, G, H"] self.assertListEqual(decoded, expected_text) def test_dynamic_cache_beam_search(self): tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf", padding_side="left") model = AutoModelForCausalLM.from_pretrained( "meta-llama/Llama-2-7b-hf", device_map="auto", torch_dtype=torch.float16 ) inputs = tokenizer(["The best color is"], return_tensors="pt").to(model.device) gen_out = model.generate( **inputs, do_sample=False, max_new_tokens=20, num_beams=2, num_return_sequences=2, ) decoded = tokenizer.batch_decode(gen_out, skip_special_tokens=True) expected_text = [ "The best color is the one that makes you feel good.\nThe best color is the one that makes you feel good", "The best color is the one that suits you.\nThe best color is the one that suits you. The", ] self.assertListEqual(decoded, expected_text) @require_auto_gptq def test_sink_cache_hard(self): tokenizer = AutoTokenizer.from_pretrained("TheBloke/LLaMa-7B-GPTQ") model = AutoModelForCausalLM.from_pretrained("TheBloke/LLaMa-7B-GPTQ", device_map="auto") inputs = tokenizer(["Vaswani et al. (2017) introduced the Transformers"], return_tensors="pt").to(model.device) # Set up the SinkCache. Using a small window length to contain computational complexity. If this example is run # without a SinkCache, the last few tokens are gibberish (ends in "of the of the of a of a of") cache = SinkCache(window_length=508, num_sink_tokens=4) gen_out = model.generate(**inputs, do_sample=False, max_new_tokens=3000, past_key_values=cache) decoded = tokenizer.batch_decode(gen_out, skip_special_tokens=True) self.assertTrue(decoded[0].endswith("to perform a variety of tasks. The Transformer is a neural network")) def test_sink_cache_iterative_prompts(self): """Tests that SinkCache supports more than one new token at once, when shifting the cache""" tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-beta") model = AutoModelForCausalLM.from_pretrained( "HuggingFaceH4/zephyr-7b-beta", device_map="auto", torch_dtype=torch.float16 ) prompt = ( "Compose an engaging travel blog post about a recent trip to Hawaii, highlighting cultural experiences " "and must-see attractions." ) # Prepare generation settings cache = SinkCache(window_length=256, num_sink_tokens=4) input_ids = torch.tensor([], device=model.device, dtype=torch.int) for _ in range(3): # Tokenize the prompt with the correct chat template chat = [{"role": "user", "content": prompt}] tokenized_chat = tokenizer.apply_chat_template(chat, return_tensors="pt", add_generation_prompt=True).to( model.device ) input_ids = torch.cat((input_ids, tokenized_chat), dim=1) # Perform the generation gen_out = model.generate( input_ids, do_sample=False, max_new_tokens=100, past_key_values=cache, use_cache=True ) input_ids = gen_out # We went well beyond the cache length self.assertTrue(input_ids.shape[1] > cache.get_max_length() * 1.5) # And it still produces a coherent english decoded = tokenizer.batch_decode(input_ids, skip_special_tokens=True) last_output = ( "<|assistant|>\nAs the sun began to set over the Pacific Ocean, I found myself standing on the shores of " "Waikiki Beach, my heart filled with awe and wonder. I had just returned from a two-week journey to the " "beautiful island of Hawaii, and it had been an unforgettable experience filled with cultural experiences " "and must-see attractions that left me breathless.\n\nOne of the most memorable experiences of my trip " "was visiting the historic district of Honolulu. Here," ) self.assertTrue(decoded[0].endswith(last_output)) @require_torch_gpu @parameterized.expand(["eager", "sdpa", "flash_attention_2"]) def test_static_cache_greedy_decoding_pad_left(self, attn_implementation): EXPECTED_GENERATION = [ "The best color is the one that complements the skin tone of the", "We should not undermind the issues at hand.\nWe should not undermind the issues", ] tokenizer = AutoTokenizer.from_pretrained( "NousResearch/Llama-2-7b-chat-hf", padding_side="left", pad_token="<s>" ) model = AutoModelForCausalLM.from_pretrained( "NousResearch/Llama-2-7b-chat-hf", torch_dtype=torch.bfloat16, attn_implementation=attn_implementation, ).to(torch_device) inputs = tokenizer( ["The best color is", "We should not undermind the issues at hand"], padding=True, return_tensors="pt" ).to(model.device) set_seed(0) gen_out = model.generate(**inputs, do_sample=False, max_new_tokens=10) decoded = tokenizer.batch_decode(gen_out, skip_special_tokens=True) with self.subTest(f"{attn_implementation}, dynamic"): self.assertListEqual(decoded, EXPECTED_GENERATION) set_seed(0) model.generation_config.cache_implementation = "static" gen_out = model.generate(**inputs, do_sample=False, max_new_tokens=10) decoded = tokenizer.batch_decode(gen_out, skip_special_tokens=True) with self.subTest(f"{attn_implementation}, static, eager"): self.assertListEqual(decoded, EXPECTED_GENERATION) set_seed(0) model.forward = torch.compile(model.forward) gen_out = model.generate(**inputs, do_sample=False, max_new_tokens=10) decoded = tokenizer.batch_decode(gen_out, skip_special_tokens=True) with self.subTest(f"{attn_implementation}, static, compiled"): self.assertListEqual(decoded, EXPECTED_GENERATION) @require_torch_gpu @parameterized.expand(["eager", "sdpa", "flash_attention_2"]) def test_static_cache_greedy_decoding_pad_right(self, attn_implementation): EXPECTED_GENERATION = [ "The best color isЋ the one that complements the skin tone of", "We should not undermind the issues at hand.\nWe should not undermind the issues", ] tokenizer = AutoTokenizer.from_pretrained( "NousResearch/Llama-2-7b-chat-hf", padding_side="right", pad_token="<s>" ) model = AutoModelForCausalLM.from_pretrained( "NousResearch/Llama-2-7b-chat-hf", torch_dtype=torch.bfloat16, attn_implementation=attn_implementation, ).to(torch_device) inputs = tokenizer( ["The best color is", "We should not undermind the issues at hand"], padding=True, return_tensors="pt" ).to(model.device) set_seed(0) gen_out = model.generate(**inputs, do_sample=False, max_new_tokens=10) decoded = tokenizer.batch_decode(gen_out, skip_special_tokens=True) with self.subTest(f"{attn_implementation}, dynamic"): self.assertListEqual(decoded, EXPECTED_GENERATION) set_seed(0) model.generation_config.cache_implementation = "static" gen_out = model.generate(**inputs, do_sample=False, max_new_tokens=10) decoded = tokenizer.batch_decode(gen_out, skip_special_tokens=True) with self.subTest(f"{attn_implementation}, static, eager"): self.assertListEqual(decoded, EXPECTED_GENERATION) set_seed(0) model._forward = model.forward compiled_forward = torch.compile(model.forward) def compiled(func, input_ids, **kwargs): return func(input_ids, **kwargs) def call(input_ids, **kwargs): if input_ids.shape[-1] == 1: return compiled(compiled_forward, input_ids, **kwargs) return model._forward(input_ids, **kwargs) model.forward = call gen_out = model.generate(**inputs, do_sample=False, max_new_tokens=10) decoded = tokenizer.batch_decode(gen_out, skip_special_tokens=True) with self.subTest(f"{attn_implementation}, static, compiled"): self.assertListEqual(decoded, EXPECTED_GENERATION) def test_dynamic_cache_extra_left_padding(self): """Tests that adding extra left-padding does not affect the generation with the dynamic cache""" EXPECTED_GENERATION = [ "The best color is the one that complements the skin tone of the", "We should not undermind the issues at hand.\nWe should not undermind the issues", ] tokenizer = AutoTokenizer.from_pretrained( "NousResearch/Llama-2-7b-chat-hf", padding_side="left", pad_token="<s>" ) model = AutoModelForCausalLM.from_pretrained( "NousResearch/Llama-2-7b-chat-hf", torch_dtype=torch.bfloat16, ).to(torch_device) inputs = tokenizer( ["The best color is", "We should not undermind the issues at hand"], padding=True, return_tensors="pt" ).to(model.device) gen_out = model.generate(**inputs, do_sample=False, max_new_tokens=10) decoded = tokenizer.batch_decode(gen_out, skip_special_tokens=True) self.assertListEqual(decoded, EXPECTED_GENERATION) # Now with extra left-padding inputs_expanded = tokenizer( ["The best color is", "We should not undermind the issues at hand"], padding=True, return_tensors="pt", pad_to_multiple_of=32, ).to(model.device) self.assertTrue(inputs.input_ids.shape[1] < inputs_expanded.input_ids.shape[1]) gen_out = model.generate(**inputs_expanded, do_sample=False, max_new_tokens=10) decoded = tokenizer.batch_decode(gen_out, skip_special_tokens=True) self.assertListEqual(decoded, EXPECTED_GENERATION) def test_static_cache_extra_left_padding(self): """Tests that adding extra left-padding does not affect the generation with the static cache""" EXPECTED_GENERATION = [ "The best color is the one that complements the skin tone of the", "We should not undermind the issues at hand.\nWe should not undermind the issues", ] tokenizer = AutoTokenizer.from_pretrained( "NousResearch/Llama-2-7b-chat-hf", padding_side="left", pad_token="<s>" ) model = AutoModelForCausalLM.from_pretrained( "NousResearch/Llama-2-7b-chat-hf", torch_dtype=torch.bfloat16, ).to(torch_device) inputs = tokenizer( ["The best color is", "We should not undermind the issues at hand"], padding=True, return_tensors="pt" ).to(model.device) model.generation_config.cache_implementation = "static" gen_out = model.generate(**inputs, do_sample=False, max_new_tokens=10) decoded = tokenizer.batch_decode(gen_out, skip_special_tokens=True) self.assertListEqual(decoded, EXPECTED_GENERATION) # Now with extra left-padding inputs_expanded = tokenizer( ["The best color is", "We should not undermind the issues at hand"], padding=True, return_tensors="pt", pad_to_multiple_of=32, ).to(model.device) self.assertTrue(inputs.input_ids.shape[1] < inputs_expanded.input_ids.shape[1]) gen_out = model.generate(**inputs_expanded, do_sample=False, max_new_tokens=10) decoded = tokenizer.batch_decode(gen_out, skip_special_tokens=True) self.assertListEqual(decoded, EXPECTED_GENERATION) @unittest.skip("TODO @gante static cache's does not support beam search yet") def test_static_cache_beam_search(self): pass
transformers/tests/test_cache_utils.py/0
{ "file_path": "transformers/tests/test_cache_utils.py", "repo_id": "transformers", "token_count": 9511 }
443
# coding=utf-8 # Copyright 2021 HuggingFace Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import numpy as np from transformers import BatchFeature from transformers.testing_utils import require_tf, 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) ) @require_tf def test_batch_feature_tf(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="tf") 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) @require_tf def test_padding_accepts_tensors_tf(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_tf = feat_extract.pad(processed_features, padding="longest", return_tensors="tf")[input_name] self.assertTrue(abs(input_np.astype(np.float32).sum() - input_tf.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": 7929 }
444
# coding=utf-8 # Copyright 2023 HuggingFace Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from transformers import load_tool from .test_tools_common import ToolTesterMixin TEXT = """ Hugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf originally as a company that developed a chatbot app targeted at teenagers.[2] After open-sourcing the model behind the chatbot, the company pivoted to focus on being a platform for machine learning. In March 2021, Hugging Face raised $40 million in a Series B funding round.[3] On April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model.[4] In 2022, the workshop concluded with the announcement of BLOOM, a multilingual large language model with 176 billion parameters.[5] """ class TextSummarizationToolTester(unittest.TestCase, ToolTesterMixin): def setUp(self): self.tool = load_tool("summarization") self.tool.setup() self.remote_tool = load_tool("summarization", remote=True) def test_exact_match_arg(self): result = self.tool(TEXT) self.assertEqual( result, "Hugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf. In March 2021, Hugging Face raised $40 million in a Series B funding round. On April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model. In 2022, the workshop concluded with the announcement of BLOOM.", ) def test_exact_match_arg_remote(self): result = self.remote_tool(TEXT) self.assertEqual( result, "Hugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf. In March 2021, Hugging Face raised $40 million in a Series B funding round. On April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model. In 2022, the workshop concluded with the announcement of BLOOM.", ) def test_exact_match_kwarg(self): result = self.tool(text=TEXT) self.assertEqual( result, "Hugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf. In March 2021, Hugging Face raised $40 million in a Series B funding round. On April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model. In 2022, the workshop concluded with the announcement of BLOOM.", ) def test_exact_match_kwarg_remote(self): result = self.remote_tool(text=TEXT) self.assertEqual( result, "Hugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf. In March 2021, Hugging Face raised $40 million in a Series B funding round. On April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model. In 2022, the workshop concluded with the announcement of BLOOM.", )
transformers/tests/tools/test_text_summarization.py/0
{ "file_path": "transformers/tests/tools/test_text_summarization.py", "repo_id": "transformers", "token_count": 1135 }
445
# coding=utf-8 # Copyright 2023 HuggingFace Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import numpy as np import pytest from transformers.audio_utils import ( amplitude_to_db, chroma_filter_bank, hertz_to_mel, mel_filter_bank, mel_to_hertz, power_to_db, spectrogram, window_function, ) from transformers.testing_utils import is_librosa_available, require_librosa if is_librosa_available(): from librosa.filters import chroma class AudioUtilsFunctionTester(unittest.TestCase): def test_hertz_to_mel(self): self.assertEqual(hertz_to_mel(0.0), 0.0) self.assertAlmostEqual(hertz_to_mel(100), 150.48910241) inputs = np.array([100, 200]) expected = np.array([150.48910241, 283.22989816]) self.assertTrue(np.allclose(hertz_to_mel(inputs), expected)) self.assertEqual(hertz_to_mel(0.0, "slaney"), 0.0) self.assertEqual(hertz_to_mel(100, "slaney"), 1.5) inputs = np.array([60, 100, 200, 1000, 1001, 2000]) expected = np.array([0.9, 1.5, 3.0, 15.0, 15.01453781, 25.08188016]) self.assertTrue(np.allclose(hertz_to_mel(inputs, "slaney"), expected)) inputs = np.array([60, 100, 200, 1000, 1001, 2000]) expected = np.array([92.6824, 150.4899, 283.2313, 999.9907, 1000.6534, 1521.3674]) self.assertTrue(np.allclose(hertz_to_mel(inputs, "kaldi"), expected)) with pytest.raises(ValueError): hertz_to_mel(100, mel_scale=None) def test_mel_to_hertz(self): self.assertEqual(mel_to_hertz(0.0), 0.0) self.assertAlmostEqual(mel_to_hertz(150.48910241), 100) inputs = np.array([150.48910241, 283.22989816]) expected = np.array([100, 200]) self.assertTrue(np.allclose(mel_to_hertz(inputs), expected)) self.assertEqual(mel_to_hertz(0.0, "slaney"), 0.0) self.assertEqual(mel_to_hertz(1.5, "slaney"), 100) inputs = np.array([0.9, 1.5, 3.0, 15.0, 15.01453781, 25.08188016]) expected = np.array([60, 100, 200, 1000, 1001, 2000]) self.assertTrue(np.allclose(mel_to_hertz(inputs, "slaney"), expected)) inputs = np.array([92.6824, 150.4899, 283.2313, 999.9907, 1000.6534, 1521.3674]) expected = np.array([60, 100, 200, 1000, 1001, 2000]) self.assertTrue(np.allclose(mel_to_hertz(inputs, "kaldi"), expected)) with pytest.raises(ValueError): mel_to_hertz(100, mel_scale=None) def test_mel_filter_bank_shape(self): mel_filters = mel_filter_bank( num_frequency_bins=513, num_mel_filters=13, min_frequency=100, max_frequency=4000, sampling_rate=16000, norm=None, mel_scale="htk", ) self.assertEqual(mel_filters.shape, (513, 13)) mel_filters = mel_filter_bank( num_frequency_bins=513, num_mel_filters=13, min_frequency=100, max_frequency=4000, sampling_rate=16000, norm="slaney", mel_scale="slaney", ) self.assertEqual(mel_filters.shape, (513, 13)) mel_filters = mel_filter_bank( num_frequency_bins=513, num_mel_filters=13, min_frequency=100, max_frequency=4000, sampling_rate=16000, norm="slaney", mel_scale="slaney", triangularize_in_mel_space=True, ) self.assertEqual(mel_filters.shape, (513, 13)) def test_mel_filter_bank_htk(self): mel_filters = mel_filter_bank( num_frequency_bins=16, num_mel_filters=4, min_frequency=0, max_frequency=2000, sampling_rate=4000, norm=None, mel_scale="htk", ) # fmt: off expected = np.array([ [0.0 , 0.0 , 0.0 , 0.0 ], [0.61454786, 0.0 , 0.0 , 0.0 ], [0.82511046, 0.17488954, 0.0 , 0.0 ], [0.35597035, 0.64402965, 0.0 , 0.0 ], [0.0 , 0.91360726, 0.08639274, 0.0 ], [0.0 , 0.55547007, 0.44452993, 0.0 ], [0.0 , 0.19733289, 0.80266711, 0.0 ], [0.0 , 0.0 , 0.87724349, 0.12275651], [0.0 , 0.0 , 0.6038449 , 0.3961551 ], [0.0 , 0.0 , 0.33044631, 0.66955369], [0.0 , 0.0 , 0.05704771, 0.94295229], [0.0 , 0.0 , 0.0 , 0.83483975], [0.0 , 0.0 , 0.0 , 0.62612982], [0.0 , 0.0 , 0.0 , 0.41741988], [0.0 , 0.0 , 0.0 , 0.20870994], [0.0 , 0.0 , 0.0 , 0.0 ] ]) # fmt: on self.assertTrue(np.allclose(mel_filters, expected)) def test_mel_filter_bank_slaney(self): mel_filters = mel_filter_bank( num_frequency_bins=16, num_mel_filters=4, min_frequency=0, max_frequency=2000, sampling_rate=4000, norm=None, mel_scale="slaney", ) # fmt: off expected = np.array([ [0.0 , 0.0 , 0.0 , 0.0 ], [0.39869419, 0.0 , 0.0 , 0.0 ], [0.79738839, 0.0 , 0.0 , 0.0 ], [0.80391742, 0.19608258, 0.0 , 0.0 ], [0.40522322, 0.59477678, 0.0 , 0.0 ], [0.00652903, 0.99347097, 0.0 , 0.0 ], [0.0 , 0.60796161, 0.39203839, 0.0 ], [0.0 , 0.20939631, 0.79060369, 0.0 ], [0.0 , 0.0 , 0.84685344, 0.15314656], [0.0 , 0.0 , 0.52418477, 0.47581523], [0.0 , 0.0 , 0.2015161 , 0.7984839 ], [0.0 , 0.0 , 0.0 , 0.9141874 ], [0.0 , 0.0 , 0.0 , 0.68564055], [0.0 , 0.0 , 0.0 , 0.4570937 ], [0.0 , 0.0 , 0.0 , 0.22854685], [0.0 , 0.0 , 0.0 , 0.0 ] ]) # fmt: on self.assertTrue(np.allclose(mel_filters, expected)) def test_mel_filter_bank_kaldi(self): mel_filters = mel_filter_bank( num_frequency_bins=16, num_mel_filters=4, min_frequency=0, max_frequency=2000, sampling_rate=4000, norm=None, mel_scale="kaldi", triangularize_in_mel_space=True, ) # fmt: off expected = np.array( [[0.0000, 0.0000, 0.0000, 0.0000], [0.6086, 0.0000, 0.0000, 0.0000], [0.8689, 0.1311, 0.0000, 0.0000], [0.4110, 0.5890, 0.0000, 0.0000], [0.0036, 0.9964, 0.0000, 0.0000], [0.0000, 0.6366, 0.3634, 0.0000], [0.0000, 0.3027, 0.6973, 0.0000], [0.0000, 0.0000, 0.9964, 0.0036], [0.0000, 0.0000, 0.7135, 0.2865], [0.0000, 0.0000, 0.4507, 0.5493], [0.0000, 0.0000, 0.2053, 0.7947], [0.0000, 0.0000, 0.0000, 0.9752], [0.0000, 0.0000, 0.0000, 0.7585], [0.0000, 0.0000, 0.0000, 0.5539], [0.0000, 0.0000, 0.0000, 0.3599], [0.0000, 0.0000, 0.0000, 0.1756]] ) # fmt: on self.assertTrue(np.allclose(mel_filters, expected, atol=5e-5)) def test_mel_filter_bank_slaney_norm(self): mel_filters = mel_filter_bank( num_frequency_bins=16, num_mel_filters=4, min_frequency=0, max_frequency=2000, sampling_rate=4000, norm="slaney", mel_scale="slaney", ) # fmt: off expected = np.array([ [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00], [1.19217795e-03, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00], [2.38435591e-03, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00], [2.40387905e-03, 5.86232616e-04, 0.00000000e+00, 0.00000000e+00], [1.21170110e-03, 1.77821783e-03, 0.00000000e+00, 0.00000000e+00], [1.95231437e-05, 2.97020305e-03, 0.00000000e+00, 0.00000000e+00], [0.00000000e+00, 1.81763684e-03, 1.04857612e-03, 0.00000000e+00], [0.00000000e+00, 6.26036972e-04, 2.11460963e-03, 0.00000000e+00], [0.00000000e+00, 0.00000000e+00, 2.26505954e-03, 3.07332945e-04], [0.00000000e+00, 0.00000000e+00, 1.40202503e-03, 9.54861093e-04], [0.00000000e+00, 0.00000000e+00, 5.38990521e-04, 1.60238924e-03], [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.83458185e-03], [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.37593638e-03], [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 9.17290923e-04], [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 4.58645462e-04], [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00] ]) # fmt: on self.assertTrue(np.allclose(mel_filters, expected)) def test_window_function(self): window = window_function(16, "hann") self.assertEqual(len(window), 16) # fmt: off expected = np.array([ 0.0, 0.03806023, 0.14644661, 0.30865828, 0.5, 0.69134172, 0.85355339, 0.96193977, 1.0, 0.96193977, 0.85355339, 0.69134172, 0.5, 0.30865828, 0.14644661, 0.03806023, ]) # fmt: on self.assertTrue(np.allclose(window, expected)) def _load_datasamples(self, num_samples): from datasets import load_dataset ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") speech_samples = ds.sort("id").select(range(num_samples))[:num_samples]["audio"] return [x["array"] for x in speech_samples] def test_spectrogram_impulse(self): waveform = np.zeros(40) waveform[9] = 1.0 # impulse shifted in time spec = spectrogram( waveform, window_function(12, "hann", frame_length=16), frame_length=16, hop_length=4, power=1.0, center=True, pad_mode="reflect", onesided=True, ) self.assertEqual(spec.shape, (9, 11)) expected = np.array([[0.0, 0.0669873, 0.9330127, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]) self.assertTrue(np.allclose(spec, expected)) def test_spectrogram_integration_test(self): waveform = self._load_datasamples(1)[0] spec = spectrogram( waveform, window_function(400, "hann", frame_length=512), frame_length=512, hop_length=128, power=1.0, center=True, pad_mode="reflect", onesided=True, ) self.assertEqual(spec.shape, (257, 732)) # fmt: off expected = np.array([ 0.02464888, 0.04648664, 0.05872392, 0.02311783, 0.0327175 , 0.02433643, 0.01198814, 0.02055709, 0.01559287, 0.01394357, 0.01299037, 0.01728045, 0.0254554 , 0.02486533, 0.02011792, 0.01755333, 0.02100457, 0.02337024, 0.01436963, 0.01464558, 0.0211017 , 0.0193489 , 0.01272165, 0.01858462, 0.03722598, 0.0456542 , 0.03281558, 0.00620586, 0.02226466, 0.03618042, 0.03508182, 0.02271432, 0.01051649, 0.01225771, 0.02315293, 0.02331886, 0.01417785, 0.0106844 , 0.01791214, 0.017177 , 0.02125114, 0.05028201, 0.06830665, 0.05216664, 0.01963666, 0.06941418, 0.11513043, 0.12257859, 0.10948435, 0.08568069, 0.05509328, 0.05047818, 0.047112 , 0.05060737, 0.02982424, 0.02803827, 0.02933729, 0.01760491, 0.00587815, 0.02117637, 0.0293578 , 0.03452379, 0.02194803, 0.01676056, ]) # fmt: on self.assertTrue(np.allclose(spec[:64, 400], expected)) spec = spectrogram( waveform, window_function(400, "hann"), frame_length=400, hop_length=128, fft_length=512, power=1.0, center=True, pad_mode="reflect", onesided=True, ) self.assertEqual(spec.shape, (257, 732)) self.assertTrue(np.allclose(spec[:64, 400], expected)) mel_filters = mel_filter_bank( num_frequency_bins=256, num_mel_filters=400, min_frequency=20, max_frequency=8000, sampling_rate=16000, norm=None, mel_scale="kaldi", triangularize_in_mel_space=True, ) mel_filters = np.pad(mel_filters, ((0, 1), (0, 0))) spec = spectrogram( waveform, window_function(400, "povey", periodic=False), frame_length=400, hop_length=160, fft_length=512, power=2.0, center=False, pad_mode="reflect", onesided=True, preemphasis=0.97, mel_filters=mel_filters, log_mel="log", mel_floor=1.1920928955078125e-07, remove_dc_offset=True, ) self.assertEqual(spec.shape, (400, 584)) # fmt: off expected = np.array([-15.94238515, -8.20712299, -8.22704352, -15.94238515, -15.94238515, -15.94238515, -15.94238515, -15.94238515, -6.52463769, -7.73677889, -15.94238515, -15.94238515, -15.94238515, -15.94238515, -4.18650018, -3.37195286, -15.94238515, -15.94238515, -15.94238515, -15.94238515, -4.70190154, -2.4217066 , -15.94238515, -15.94238515, -15.94238515, -15.94238515, -5.62755239, -3.53385194, -15.94238515, -15.94238515, -15.94238515, -15.94238515, -9.43303023, -8.77480925, -15.94238515, -15.94238515, -15.94238515, -15.94238515, -4.2951092 , -5.51585994, -15.94238515, -15.94238515, -15.94238515, -4.40151721, -3.95228878, -15.94238515, -15.94238515, -15.94238515, -6.10365415, -4.59494697, -15.94238515, -15.94238515, -15.94238515, -8.10727767, -6.2585298 , -15.94238515, -15.94238515, -15.94238515, -5.60161702, -4.47217004, -15.94238515, -15.94238515, -15.94238515, -5.91641988] ) # fmt: on self.assertTrue(np.allclose(spec[:64, 400], expected, atol=1e-5)) def test_spectrogram_center_padding(self): waveform = self._load_datasamples(1)[0] spec = spectrogram( waveform, window_function(512, "hann"), frame_length=512, hop_length=128, center=True, pad_mode="reflect", ) self.assertEqual(spec.shape, (257, 732)) # fmt: off expected = np.array([ 0.1287945 , 0.12792738, 0.08311573, 0.03155122, 0.02470202, 0.00727857, 0.00910694, 0.00686163, 0.01238981, 0.01473668, 0.00336144, 0.00370314, 0.00600871, 0.01120164, 0.01942998, 0.03132008, 0.0232842 , 0.01124642, 0.02754783, 0.02423725, 0.00147893, 0.00038027, 0.00112299, 0.00596233, 0.00571529, 0.02084235, 0.0231855 , 0.00810006, 0.01837943, 0.00651339, 0.00093931, 0.00067426, 0.01058399, 0.01270507, 0.00151734, 0.00331913, 0.00302416, 0.01081792, 0.00754549, 0.00148963, 0.00111943, 0.00152573, 0.00608017, 0.01749986, 0.01205949, 0.0143082 , 0.01910573, 0.00413786, 0.03916619, 0.09873404, 0.08302026, 0.02673891, 0.00401255, 0.01397392, 0.00751862, 0.01024884, 0.01544606, 0.00638907, 0.00623633, 0.0085103 , 0.00217659, 0.00276204, 0.00260835, 0.00299299, ]) # fmt: on self.assertTrue(np.allclose(spec[:64, 0], expected)) spec = spectrogram( waveform, window_function(512, "hann"), frame_length=512, hop_length=128, center=True, pad_mode="constant", ) self.assertEqual(spec.shape, (257, 732)) # fmt: off expected = np.array([ 0.06558744, 0.06889656, 0.06263352, 0.04264418, 0.03404115, 0.03244197, 0.02279134, 0.01646339, 0.01452216, 0.00826055, 0.00062093, 0.0031821 , 0.00419456, 0.00689327, 0.01106367, 0.01712119, 0.01721762, 0.00977533, 0.01606626, 0.02275621, 0.01727687, 0.00992739, 0.01217688, 0.01049927, 0.01022947, 0.01302475, 0.01166873, 0.01081812, 0.01057327, 0.00767912, 0.00429567, 0.00089625, 0.00654583, 0.00912084, 0.00700984, 0.00225026, 0.00290545, 0.00667712, 0.00730663, 0.00410813, 0.00073102, 0.00219296, 0.00527618, 0.00996585, 0.01123781, 0.00872816, 0.01165121, 0.02047945, 0.03681747, 0.0514379 , 0.05137928, 0.03960042, 0.02821562, 0.01813349, 0.01201322, 0.01260964, 0.00900654, 0.00207905, 0.00456714, 0.00850599, 0.00788239, 0.00664407, 0.00824227, 0.00628301, ]) # fmt: on self.assertTrue(np.allclose(spec[:64, 0], expected)) spec = spectrogram( waveform, window_function(512, "hann"), frame_length=512, hop_length=128, center=False, ) self.assertEqual(spec.shape, (257, 728)) # fmt: off expected = np.array([ 0.00250445, 0.02161521, 0.06232229, 0.04339567, 0.00937727, 0.01080616, 0.00248685, 0.0095264 , 0.00727476, 0.0079152 , 0.00839946, 0.00254932, 0.00716622, 0.005559 , 0.00272623, 0.00581774, 0.01896395, 0.01829788, 0.01020514, 0.01632692, 0.00870888, 0.02065827, 0.0136022 , 0.0132382 , 0.011827 , 0.00194505, 0.0189979 , 0.026874 , 0.02194014, 0.01923883, 0.01621437, 0.00661967, 0.00289517, 0.00470257, 0.00957801, 0.00191455, 0.00431664, 0.00544359, 0.01126213, 0.00785778, 0.00423469, 0.01322504, 0.02226548, 0.02318576, 0.03428908, 0.03648811, 0.0202938 , 0.011902 , 0.03226198, 0.06347476, 0.01306318, 0.05308729, 0.05474771, 0.03127991, 0.00998512, 0.01449977, 0.01272741, 0.00868176, 0.00850386, 0.00313876, 0.00811857, 0.00538216, 0.00685749, 0.00535275, ]) # fmt: on self.assertTrue(np.allclose(spec[:64, 0], expected)) def test_spectrogram_shapes(self): waveform = self._load_datasamples(1)[0] spec = spectrogram( waveform, window_function(400, "hann"), frame_length=400, hop_length=128, power=1.0, center=True, pad_mode="reflect", onesided=True, ) self.assertEqual(spec.shape, (201, 732)) spec = spectrogram( waveform, window_function(400, "hann"), frame_length=400, hop_length=128, power=1.0, center=False, pad_mode="reflect", onesided=True, ) self.assertEqual(spec.shape, (201, 729)) spec = spectrogram( waveform, window_function(400, "hann"), frame_length=400, hop_length=128, fft_length=512, power=1.0, center=True, pad_mode="reflect", onesided=True, ) self.assertEqual(spec.shape, (257, 732)) spec = spectrogram( waveform, window_function(400, "hann", frame_length=512), frame_length=512, hop_length=64, power=1.0, center=True, pad_mode="reflect", onesided=False, ) self.assertEqual(spec.shape, (512, 1464)) spec = spectrogram( waveform, window_function(512, "hann"), frame_length=512, hop_length=64, power=1.0, center=True, pad_mode="reflect", onesided=False, ) self.assertEqual(spec.shape, (512, 1464)) spec = spectrogram( waveform, window_function(512, "hann"), frame_length=512, hop_length=512, power=1.0, center=True, pad_mode="reflect", onesided=False, ) self.assertEqual(spec.shape, (512, 183)) def test_mel_spectrogram(self): waveform = self._load_datasamples(1)[0] mel_filters = mel_filter_bank( num_frequency_bins=513, num_mel_filters=13, min_frequency=100, max_frequency=4000, sampling_rate=16000, norm=None, mel_scale="htk", ) self.assertEqual(mel_filters.shape, (513, 13)) spec = spectrogram( waveform, window_function(800, "hann", frame_length=1024), frame_length=1024, hop_length=128, power=2.0, ) self.assertEqual(spec.shape, (513, 732)) spec = spectrogram( waveform, window_function(800, "hann", frame_length=1024), frame_length=1024, hop_length=128, power=2.0, mel_filters=mel_filters, ) self.assertEqual(spec.shape, (13, 732)) # fmt: off expected = np.array([ 1.08027889e+02, 1.48080673e+01, 7.70758213e+00, 9.57676639e-01, 8.81639061e-02, 5.26073833e-02, 1.52736155e-02, 9.95350117e-03, 7.95364356e-03, 1.01148004e-02, 4.29241020e-03, 9.90708797e-03, 9.44153646e-04 ]) # fmt: on self.assertTrue(np.allclose(spec[:, 300], expected)) def test_spectrogram_power(self): waveform = self._load_datasamples(1)[0] spec = spectrogram( waveform, window_function(400, "hann", frame_length=512), frame_length=512, hop_length=128, power=None, ) self.assertEqual(spec.shape, (257, 732)) self.assertEqual(spec.dtype, np.complex64) # fmt: off expected = np.array([ 0.01452305+0.01820039j, -0.01737362-0.01641946j, 0.0121028 +0.01565081j, -0.02794554-0.03021514j, 0.04719803+0.04086519j, -0.04391563-0.02779365j, 0.05682834+0.01571325j, -0.08604821-0.02023657j, 0.07497991+0.0186641j , -0.06366091-0.00922475j, 0.11003416+0.0114788j , -0.13677941-0.01523552j, 0.10934535-0.00117226j, -0.11635598+0.02551187j, 0.14708674-0.03469823j, -0.1328196 +0.06034218j, 0.12667368-0.13973421j, -0.14764774+0.18912019j, 0.10235471-0.12181523j, -0.00773012+0.04730498j, -0.01487191-0.07312611j, -0.02739162+0.09619419j, 0.02895459-0.05398273j, 0.01198589+0.05276592j, -0.02117299-0.10123465j, 0.00666388+0.09526499j, -0.01672773-0.05649684j, 0.02723125+0.05939891j, -0.01879361-0.062954j , 0.03686557+0.04568823j, -0.07394181-0.07949649j, 0.06238583+0.13905765j, ]) # fmt: on self.assertTrue(np.allclose(spec[64:96, 321], expected)) spec = spectrogram( waveform, window_function(400, "hann", frame_length=512), frame_length=512, hop_length=128, power=1.0, ) self.assertEqual(spec.shape, (257, 732)) self.assertEqual(spec.dtype, np.float64) # fmt: off expected = np.array([ 0.02328461, 0.02390484, 0.01978448, 0.04115711, 0.0624309 , 0.05197181, 0.05896072, 0.08839577, 0.07726794, 0.06432579, 0.11063128, 0.13762532, 0.10935163, 0.11911998, 0.15112405, 0.14588428, 0.18860507, 0.23992978, 0.15910825, 0.04793241, 0.07462307, 0.10001811, 0.06125769, 0.05411011, 0.10342509, 0.09549777, 0.05892122, 0.06534349, 0.06569936, 0.05870678, 0.10856833, 0.1524107 , 0.11463385, 0.05766969, 0.12385171, 0.14472842, 0.11978184, 0.10353675, 0.07244056, 0.03461861, 0.02624896, 0.02227475, 0.01238363, 0.00885281, 0.0110049 , 0.00807005, 0.01033663, 0.01703181, 0.01445856, 0.00585615, 0.0132431 , 0.02754132, 0.01524478, 0.0204908 , 0.07453328, 0.10716327, 0.07195779, 0.08816078, 0.18340898, 0.16449876, 0.12322842, 0.1621659 , 0.12334293, 0.06033659, ]) # fmt: on self.assertTrue(np.allclose(spec[64:128, 321], expected)) spec = spectrogram( waveform, window_function(400, "hann", frame_length=512), frame_length=512, hop_length=128, power=2.0, ) self.assertEqual(spec.shape, (257, 732)) self.assertEqual(spec.dtype, np.float64) # fmt: off expected = np.array([ 5.42173162e-04, 5.71441371e-04, 3.91425507e-04, 1.69390778e-03, 3.89761780e-03, 2.70106923e-03, 3.47636663e-03, 7.81381316e-03, 5.97033510e-03, 4.13780799e-03, 1.22392802e-02, 1.89407300e-02, 1.19577805e-02, 1.41895693e-02, 2.28384770e-02, 2.12822221e-02, 3.55718732e-02, 5.75663000e-02, 2.53154356e-02, 2.29751552e-03, 5.56860259e-03, 1.00036217e-02, 3.75250424e-03, 2.92790355e-03, 1.06967501e-02, 9.11982451e-03, 3.47171025e-03, 4.26977174e-03, 4.31640586e-03, 3.44648538e-03, 1.17870830e-02, 2.32290216e-02, 1.31409196e-02, 3.32579296e-03, 1.53392460e-02, 2.09463164e-02, 1.43476883e-02, 1.07198600e-02, 5.24763530e-03, 1.19844836e-03, 6.89007982e-04, 4.96164430e-04, 1.53354369e-04, 7.83722571e-05, 1.21107812e-04, 6.51257360e-05, 1.06845939e-04, 2.90082477e-04, 2.09049831e-04, 3.42945241e-05, 1.75379610e-04, 7.58524227e-04, 2.32403356e-04, 4.19872697e-04, 5.55520924e-03, 1.14839673e-02, 5.17792348e-03, 7.77232368e-03, 3.36388536e-02, 2.70598419e-02, 1.51852425e-02, 2.62977779e-02, 1.52134784e-02, 3.64050455e-03, ]) # fmt: on self.assertTrue(np.allclose(spec[64:128, 321], expected)) def test_power_to_db(self): spectrogram = np.zeros((2, 3)) spectrogram[0, 0] = 2.0 spectrogram[0, 1] = 0.5 spectrogram[0, 2] = 0.707 spectrogram[1, 1] = 1.0 output = power_to_db(spectrogram, reference=1.0) expected = np.array([[3.01029996, -3.01029996, -1.50580586], [-100.0, 0.0, -100.0]]) self.assertTrue(np.allclose(output, expected)) output = power_to_db(spectrogram, reference=2.0) expected = np.array([[0.0, -6.02059991, -4.51610582], [-103.01029996, -3.01029996, -103.01029996]]) self.assertTrue(np.allclose(output, expected)) output = power_to_db(spectrogram, min_value=1e-6) expected = np.array([[3.01029996, -3.01029996, -1.50580586], [-60.0, 0.0, -60.0]]) self.assertTrue(np.allclose(output, expected)) output = power_to_db(spectrogram, db_range=80) expected = np.array([[3.01029996, -3.01029996, -1.50580586], [-76.98970004, 0.0, -76.98970004]]) self.assertTrue(np.allclose(output, expected)) output = power_to_db(spectrogram, reference=2.0, db_range=80) expected = np.array([[0.0, -6.02059991, -4.51610582], [-80.0, -3.01029996, -80.0]]) self.assertTrue(np.allclose(output, expected)) output = power_to_db(spectrogram, reference=2.0, min_value=1e-6, db_range=80) expected = np.array([[0.0, -6.02059991, -4.51610582], [-63.01029996, -3.01029996, -63.01029996]]) self.assertTrue(np.allclose(output, expected)) with pytest.raises(ValueError): power_to_db(spectrogram, reference=0.0) with pytest.raises(ValueError): power_to_db(spectrogram, min_value=0.0) with pytest.raises(ValueError): power_to_db(spectrogram, db_range=-80) def test_amplitude_to_db(self): spectrogram = np.zeros((2, 3)) spectrogram[0, 0] = 2.0 spectrogram[0, 1] = 0.5 spectrogram[0, 2] = 0.707 spectrogram[1, 1] = 1.0 output = amplitude_to_db(spectrogram, reference=1.0) expected = np.array([[6.02059991, -6.02059991, -3.01161172], [-100.0, 0.0, -100.0]]) self.assertTrue(np.allclose(output, expected)) output = amplitude_to_db(spectrogram, reference=2.0) expected = np.array([[0.0, -12.04119983, -9.03221164], [-106.02059991, -6.02059991, -106.02059991]]) self.assertTrue(np.allclose(output, expected)) output = amplitude_to_db(spectrogram, min_value=1e-3) expected = np.array([[6.02059991, -6.02059991, -3.01161172], [-60.0, 0.0, -60.0]]) self.assertTrue(np.allclose(output, expected)) output = amplitude_to_db(spectrogram, db_range=80) expected = np.array([[6.02059991, -6.02059991, -3.01161172], [-73.97940009, 0.0, -73.97940009]]) self.assertTrue(np.allclose(output, expected)) output = amplitude_to_db(spectrogram, reference=2.0, db_range=80) expected = np.array([[0.0, -12.04119983, -9.03221164], [-80.0, -6.02059991, -80.0]]) self.assertTrue(np.allclose(output, expected)) output = amplitude_to_db(spectrogram, reference=2.0, min_value=1e-3, db_range=80) expected = np.array([[0.0, -12.04119983, -9.03221164], [-66.02059991, -6.02059991, -66.02059991]]) self.assertTrue(np.allclose(output, expected)) with pytest.raises(ValueError): amplitude_to_db(spectrogram, reference=0.0) with pytest.raises(ValueError): amplitude_to_db(spectrogram, min_value=0.0) with pytest.raises(ValueError): amplitude_to_db(spectrogram, db_range=-80) @require_librosa def test_chroma_equivalence(self): num_frequency_bins = 25 num_chroma = 6 sampling_rate = 24000 # test default parameters original_chroma = chroma(sr=sampling_rate, n_chroma=num_chroma, n_fft=num_frequency_bins) utils_chroma = chroma_filter_bank( num_frequency_bins=num_frequency_bins, num_chroma=num_chroma, sampling_rate=sampling_rate ) self.assertTrue(np.allclose(original_chroma, utils_chroma)) # test no weighting_parameters original_chroma = chroma(sr=sampling_rate, n_chroma=num_chroma, n_fft=num_frequency_bins, octwidth=None) utils_chroma = chroma_filter_bank( num_frequency_bins=num_frequency_bins, num_chroma=num_chroma, sampling_rate=sampling_rate, weighting_parameters=None, ) self.assertTrue(np.allclose(original_chroma, utils_chroma)) # test with L1 norm original_chroma = chroma(sr=sampling_rate, n_chroma=num_chroma, n_fft=num_frequency_bins, norm=1.0) utils_chroma = chroma_filter_bank( num_frequency_bins=num_frequency_bins, num_chroma=num_chroma, sampling_rate=sampling_rate, power=1.0 ) self.assertTrue(np.allclose(original_chroma, utils_chroma)) # test starting at 'A' chroma, power = None, tuning = 0, different weighting_parameters original_chroma = chroma( sr=sampling_rate, n_chroma=num_chroma, n_fft=num_frequency_bins, norm=None, base_c=None, octwidth=1.0, ctroct=4.0, ) utils_chroma = chroma_filter_bank( num_frequency_bins=num_frequency_bins, num_chroma=num_chroma, sampling_rate=sampling_rate, power=None, start_at_c_chroma=False, weighting_parameters=(4.0, 1.0), ) self.assertTrue(np.allclose(original_chroma, utils_chroma))
transformers/tests/utils/test_audio_utils.py/0
{ "file_path": "transformers/tests/utils/test_audio_utils.py", "repo_id": "transformers", "token_count": 18583 }
446
# 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 subprocess import sys from transformers import BertConfig, BertModel, BertTokenizer, pipeline from transformers.testing_utils import TestCasePlus, require_torch class OfflineTests(TestCasePlus): @require_torch def test_offline_mode(self): # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched load = """ from transformers import BertConfig, BertModel, BertTokenizer, pipeline """ run = """ mname = "hf-internal-testing/tiny-random-bert" BertConfig.from_pretrained(mname) BertModel.from_pretrained(mname) BertTokenizer.from_pretrained(mname) pipe = pipeline(task="fill-mask", model=mname) print("success") """ mock = """ import socket def offline_socket(*args, **kwargs): raise RuntimeError("Offline mode is enabled, we shouldn't access internet") socket.socket = offline_socket """ # Force fetching the files so that we can use the cache mname = "hf-internal-testing/tiny-random-bert" BertConfig.from_pretrained(mname) BertModel.from_pretrained(mname) BertTokenizer.from_pretrained(mname) pipeline(task="fill-mask", model=mname) # baseline - just load from_pretrained with normal network cmd = [sys.executable, "-c", "\n".join([load, run, mock])] # should succeed env = self.get_env() # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files env["TRANSFORMERS_OFFLINE"] = "1" result = subprocess.run(cmd, env=env, check=False, capture_output=True) self.assertEqual(result.returncode, 0, result.stderr) self.assertIn("success", result.stdout.decode()) @require_torch def test_offline_mode_no_internet(self): # python one-liner segments # this must be loaded before socket.socket is monkey-patched load = """ from transformers import BertConfig, BertModel, BertTokenizer, pipeline """ run = """ mname = "hf-internal-testing/tiny-random-bert" BertConfig.from_pretrained(mname) BertModel.from_pretrained(mname) BertTokenizer.from_pretrained(mname) pipe = pipeline(task="fill-mask", model=mname) print("success") """ mock = """ import socket def offline_socket(*args, **kwargs): raise socket.error("Faking flaky internet") socket.socket = offline_socket """ # Force fetching the files so that we can use the cache mname = "hf-internal-testing/tiny-random-bert" BertConfig.from_pretrained(mname) BertModel.from_pretrained(mname) BertTokenizer.from_pretrained(mname) pipeline(task="fill-mask", model=mname) # baseline - just load from_pretrained with normal network cmd = [sys.executable, "-c", "\n".join([load, run, mock])] # should succeed env = self.get_env() result = subprocess.run(cmd, env=env, check=False, capture_output=True) self.assertEqual(result.returncode, 0, result.stderr) self.assertIn("success", result.stdout.decode()) @require_torch def test_offline_mode_sharded_checkpoint(self): # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before # `transformers` is loaded, and it's too late for inside pytest - so we are changing it # while running an external program # python one-liner segments # this must be loaded before socket.socket is monkey-patched load = """ from transformers import BertConfig, BertModel, BertTokenizer """ run = """ mname = "hf-internal-testing/tiny-random-bert-sharded" BertConfig.from_pretrained(mname) BertModel.from_pretrained(mname) print("success") """ mock = """ import socket def offline_socket(*args, **kwargs): raise ValueError("Offline mode is enabled") socket.socket = offline_socket """ # baseline - just load from_pretrained with normal network cmd = [sys.executable, "-c", "\n".join([load, run])] # should succeed env = self.get_env() result = subprocess.run(cmd, env=env, check=False, capture_output=True) self.assertEqual(result.returncode, 0, result.stderr) self.assertIn("success", result.stdout.decode()) # next emulate no network cmd = [sys.executable, "-c", "\n".join([load, mock, run])] # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this. # env["TRANSFORMERS_OFFLINE"] = "0" # result = subprocess.run(cmd, env=env, check=False, capture_output=True) # self.assertEqual(result.returncode, 1, result.stderr) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files env["TRANSFORMERS_OFFLINE"] = "1" result = subprocess.run(cmd, env=env, check=False, capture_output=True) self.assertEqual(result.returncode, 0, result.stderr) self.assertIn("success", result.stdout.decode()) @require_torch def test_offline_mode_pipeline_exception(self): load = """ from transformers import pipeline """ run = """ mname = "hf-internal-testing/tiny-random-bert" pipe = pipeline(model=mname) """ mock = """ import socket def offline_socket(*args, **kwargs): raise socket.error("Offline mode is enabled") socket.socket = offline_socket """ env = self.get_env() env["TRANSFORMERS_OFFLINE"] = "1" cmd = [sys.executable, "-c", "\n".join([load, mock, run])] result = subprocess.run(cmd, env=env, check=False, capture_output=True) self.assertEqual(result.returncode, 1, result.stderr) self.assertIn( "You cannot infer task automatically within `pipeline` when using offline mode", result.stderr.decode().replace("\n", ""), ) @require_torch def test_offline_model_dynamic_model(self): load = """ from transformers import AutoModel """ run = """ mname = "hf-internal-testing/test_dynamic_model" AutoModel.from_pretrained(mname, trust_remote_code=True) print("success") """ # baseline - just load from_pretrained with normal network cmd = [sys.executable, "-c", "\n".join([load, run])] # should succeed env = self.get_env() result = subprocess.run(cmd, env=env, check=False, capture_output=True) self.assertEqual(result.returncode, 0, result.stderr) self.assertIn("success", result.stdout.decode()) # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files env["TRANSFORMERS_OFFLINE"] = "1" result = subprocess.run(cmd, env=env, check=False, capture_output=True) self.assertEqual(result.returncode, 0, result.stderr) self.assertIn("success", result.stdout.decode())
transformers/tests/utils/test_offline.py/0
{ "file_path": "transformers/tests/utils/test_offline.py", "repo_id": "transformers", "token_count": 2916 }
447
import argparse import json import subprocess def get_runner_status(target_runners, token): offline_runners = [] cmd = ( f'curl -H "Accept: application/vnd.github+json" -H "Authorization: Bearer {token}"' " https://api.github.com/repos/huggingface/transformers/actions/runners" ) output = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE) o = output.stdout.decode("utf-8") status = json.loads(o) runners = status["runners"] for runner in runners: if runner["name"] in target_runners: if runner["status"] == "offline": offline_runners.append(runner) # save the result so we can report them on Slack with open("offline_runners.txt", "w") as fp: fp.write(json.dumps(offline_runners)) if len(offline_runners) > 0: failed = "\n".join([x["name"] for x in offline_runners]) raise ValueError(f"The following runners are offline:\n{failed}") if __name__ == "__main__": def list_str(values): return values.split(",") parser = argparse.ArgumentParser() # Required parameters parser.add_argument( "--target_runners", default=None, type=list_str, required=True, help="Comma-separated list of runners to check status.", ) parser.add_argument( "--token", default=None, type=str, required=True, help="A token that has actions:read permission." ) args = parser.parse_args() get_runner_status(args.target_runners, args.token)
transformers/utils/check_self_hosted_runner.py/0
{ "file_path": "transformers/utils/check_self_hosted_runner.py", "repo_id": "transformers", "token_count": 611 }
448
# Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import collections import json import math import os import re import time from fnmatch import fnmatch from typing import Dict, List import requests from slack_sdk import WebClient client = WebClient(token=os.environ["CI_SLACK_BOT_TOKEN"]) def handle_test_results(test_results): expressions = test_results.split(" ") failed = 0 success = 0 # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" # When it is too long, those signs are not present. time_spent = expressions[-2] if "=" in expressions[-1] else expressions[-1] for i, expression in enumerate(expressions): if "failed" in expression: failed += int(expressions[i - 1]) if "passed" in expression: success += int(expressions[i - 1]) return failed, success, time_spent def extract_first_line_failure(failures_short_lines): failures = {} file = None in_error = False for line in failures_short_lines.split("\n"): if re.search(r"_ \[doctest\]", line): in_error = True file = line.split(" ")[2] elif in_error and not line.split(" ")[0].isdigit(): failures[file] = line in_error = False return failures class Message: def __init__(self, title: str, doc_test_results: Dict): self.title = title self._time_spent = doc_test_results["time_spent"].split(",")[0] self.n_success = doc_test_results["success"] self.n_failures = doc_test_results["failures"] self.n_tests = self.n_success + self.n_failures # Failures and success of the modeling tests self.doc_test_results = doc_test_results @property def time(self) -> str: time_spent = [self._time_spent] total_secs = 0 for time in time_spent: time_parts = time.split(":") # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. if len(time_parts) == 1: time_parts = [0, 0, time_parts[0]] hours, minutes, seconds = int(time_parts[0]), int(time_parts[1]), float(time_parts[2]) total_secs += hours * 3600 + minutes * 60 + seconds hours, minutes, seconds = total_secs // 3600, (total_secs % 3600) // 60, total_secs % 60 return f"{int(hours)}h{int(minutes)}m{int(seconds)}s" @property def header(self) -> Dict: return {"type": "header", "text": {"type": "plain_text", "text": self.title}} @property def no_failures(self) -> Dict: return { "type": "section", "text": { "type": "plain_text", "text": f"🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.", "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", }, } @property def failures(self) -> Dict: return { "type": "section", "text": { "type": "plain_text", "text": ( f"There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in" f" {self.time}." ), "emoji": True, }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", }, } @property def category_failures(self) -> List[Dict]: failure_blocks = [] MAX_ERROR_TEXT = 3000 - len("The following examples had failures:\n\n\n\n") - len("[Truncated]\n") line_length = 40 category_failures = {k: v["failed"] for k, v in doc_test_results.items() if isinstance(v, dict)} def single_category_failures(category, failures): text = "" if len(failures) == 0: return "" text += f"*{category} failures*:".ljust(line_length // 2).rjust(line_length // 2) + "\n" for idx, failure in enumerate(failures): new_text = text + f"`{failure}`\n" if len(new_text) > MAX_ERROR_TEXT: text = text + "[Truncated]\n" break text = new_text return text for category, failures in category_failures.items(): report = single_category_failures(category, failures) if len(report) == 0: continue block = { "type": "section", "text": { "type": "mrkdwn", "text": f"The following examples had failures:\n\n\n{report}\n", }, } failure_blocks.append(block) return failure_blocks @property def payload(self) -> str: blocks = [self.header] if self.n_failures > 0: blocks.append(self.failures) if self.n_failures > 0: blocks.extend(self.category_failures) if self.n_failures == 0: blocks.append(self.no_failures) return json.dumps(blocks) @staticmethod def error_out(): payload = [ { "type": "section", "text": { "type": "plain_text", "text": "There was an issue running the tests.", }, "accessory": { "type": "button", "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, "url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", }, } ] print("Sending the following payload") print(json.dumps({"blocks": json.loads(payload)})) client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"], text="There was an issue running the tests.", blocks=payload, ) def post(self): print("Sending the following payload") print(json.dumps({"blocks": json.loads(self.payload)})) text = f"{self.n_failures} failures out of {self.n_tests} tests," if self.n_failures else "All tests passed." self.thread_ts = client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"], blocks=self.payload, text=text, ) def get_reply_blocks(self, job_name, job_link, failures, text): # `text` must be less than 3001 characters in Slack SDK # keep some room for adding "[Truncated]" when necessary MAX_ERROR_TEXT = 3000 - len("[Truncated]") failure_text = "" for key, value in failures.items(): new_text = failure_text + f"*{key}*\n_{value}_\n\n" if len(new_text) > MAX_ERROR_TEXT: # `failure_text` here has length <= 3000 failure_text = failure_text + "[Truncated]" break # `failure_text` here has length <= MAX_ERROR_TEXT failure_text = new_text title = job_name content = {"type": "section", "text": {"type": "mrkdwn", "text": text}} if job_link is not None: content["accessory"] = { "type": "button", "text": {"type": "plain_text", "text": "GitHub Action job", "emoji": True}, "url": job_link, } return [ {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, content, {"type": "section", "text": {"type": "mrkdwn", "text": failure_text}}, ] def post_reply(self): if self.thread_ts is None: raise ValueError("Can only post reply if a post has been made.") job_link = self.doc_test_results.pop("job_link") self.doc_test_results.pop("failures") self.doc_test_results.pop("success") self.doc_test_results.pop("time_spent") sorted_dict = sorted(self.doc_test_results.items(), key=lambda t: t[0]) for job, job_result in sorted_dict: if len(job_result["failures"]): text = f"*Num failures* :{len(job_result['failed'])} \n" failures = job_result["failures"] blocks = self.get_reply_blocks(job, job_link, failures, text=text) print("Sending the following reply") print(json.dumps({"blocks": blocks})) client.chat_postMessage( channel=os.environ["CI_SLACK_CHANNEL_ID_DAILY"], text=f"Results for {job}", blocks=blocks, thread_ts=self.thread_ts["ts"], ) time.sleep(1) def get_job_links(): run_id = os.environ["GITHUB_RUN_ID"] url = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{run_id}/jobs?per_page=100" result = requests.get(url).json() jobs = {} try: jobs.update({job["name"]: job["html_url"] for job in result["jobs"]}) pages_to_iterate_over = math.ceil((result["total_count"] - 100) / 100) for i in range(pages_to_iterate_over): result = requests.get(url + f"&page={i + 2}").json() jobs.update({job["name"]: job["html_url"] for job in result["jobs"]}) return jobs except Exception as e: print("Unknown error, could not fetch links.", e) return {} def retrieve_artifact(name: str): _artifact = {} if os.path.exists(name): files = os.listdir(name) for file in files: try: with open(os.path.join(name, file), encoding="utf-8") as f: _artifact[file.split(".")[0]] = f.read() except UnicodeDecodeError as e: raise ValueError(f"Could not open {os.path.join(name, file)}.") from e return _artifact def retrieve_available_artifacts(): class Artifact: def __init__(self, name: str): self.name = name self.paths = [] def __str__(self): return self.name def add_path(self, path: str): self.paths.append({"name": self.name, "path": path}) _available_artifacts: Dict[str, Artifact] = {} directories = filter(os.path.isdir, os.listdir()) for directory in directories: artifact_name = directory if artifact_name not in _available_artifacts: _available_artifacts[artifact_name] = Artifact(artifact_name) _available_artifacts[artifact_name].add_path(directory) return _available_artifacts if __name__ == "__main__": github_actions_job_links = get_job_links() available_artifacts = retrieve_available_artifacts() docs = collections.OrderedDict( [ ("*.py", "API Examples"), ("*.md", "MD Examples"), ] ) # This dict will contain all the information relative to each doc test category: # - failed: list of failed tests # - failures: dict in the format 'test': 'error_message' doc_test_results = { v: { "failed": [], "failures": {}, } for v in docs.values() } # Link to the GitHub Action job doc_test_results["job_link"] = github_actions_job_links.get("run_doctests") artifact_path = available_artifacts["doc_tests_gpu_test_reports"].paths[0] artifact = retrieve_artifact(artifact_path["name"]) if "stats" in artifact: failed, success, time_spent = handle_test_results(artifact["stats"]) doc_test_results["failures"] = failed doc_test_results["success"] = success doc_test_results["time_spent"] = time_spent[1:-1] + ", " all_failures = extract_first_line_failure(artifact["failures_short"]) for line in artifact["summary_short"].split("\n"): if re.search("FAILED", line): line = line.replace("FAILED ", "") line = line.split()[0].replace("\n", "") if "::" in line: file_path, test = line.split("::") else: file_path, test = line, line for file_regex in docs.keys(): if fnmatch(file_path, file_regex): category = docs[file_regex] doc_test_results[category]["failed"].append(test) failure = all_failures[test] if test in all_failures else "N/A" doc_test_results[category]["failures"][test] = failure break message = Message("🤗 Results of the doc tests.", doc_test_results) message.post() message.post_reply()
transformers/utils/notification_service_doc_tests.py/0
{ "file_path": "transformers/utils/notification_service_doc_tests.py", "repo_id": "transformers", "token_count": 6457 }
449
# coding=utf-8 # Copyright 2021 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. """ Welcome to tests_fetcher V2. This util is designed to fetch tests to run on a PR so that only the tests impacted by the modifications are run, and when too many models are being impacted, only run the tests of a subset of core models. It works like this. Stage 1: Identify the modified files. For jobs that run on the main branch, it's just the diff with the last commit. On a PR, this takes all the files from the branching point to the current commit (so all modifications in a PR, not just the last commit) but excludes modifications that are on docstrings or comments only. Stage 2: Extract the tests to run. This is done by looking at the imports in each module and test file: if module A imports module B, then changing module B impacts module A, so the tests using module A should be run. We thus get the dependencies of each model and then recursively builds the 'reverse' map of dependencies to get all modules and tests impacted by a given file. We then only keep the tests (and only the core models tests if there are too many modules). Caveats: - This module only filters tests by files (not individual tests) so it's better to have tests for different things in different files. - This module assumes inits are just importing things, not really building objects, so it's better to structure them this way and move objects building in separate submodules. Usage: Base use to fetch the tests in a pull request ```bash python utils/tests_fetcher.py ``` Base use to fetch the tests on a the main branch (with diff from the last commit): ```bash python utils/tests_fetcher.py --diff_with_last_commit ``` """ import argparse import collections import importlib.util import json import os import re import tempfile from contextlib import contextmanager from pathlib import Path from typing import Dict, List, Optional, Tuple, Union from git import Repo PATH_TO_REPO = Path(__file__).parent.parent.resolve() PATH_TO_EXAMPLES = PATH_TO_REPO / "examples" PATH_TO_TRANFORMERS = PATH_TO_REPO / "src/transformers" PATH_TO_TESTS = PATH_TO_REPO / "tests" # The value is just a heuristic to determine if we `guess` all models are impacted. # This variable has effect only if `filter_models=False`. NUM_MODELS_TO_TRIGGER_FULL_CI = 30 # List here the models to always test. IMPORTANT_MODELS = [ "auto", # Most downloaded models "bert", "clip", "t5", "xlm-roberta", "gpt2", "bart", "mpnet", "gpt-j", "wav2vec2", "deberta-v2", "layoutlm", "llama", "opt", "longformer", "vit", # Pipeline-specific model (to be sure each pipeline has one model in this list) "tapas", "vilt", "clap", "detr", "owlvit", "dpt", "videomae", ] @contextmanager def checkout_commit(repo: Repo, commit_id: str): """ Context manager that checks out a given commit when entered, but gets back to the reference it was at on exit. Args: repo (`git.Repo`): A git repository (for instance the Transformers repo). commit_id (`str`): The commit reference to checkout inside the context manager. """ current_head = repo.head.commit if repo.head.is_detached else repo.head.ref try: repo.git.checkout(commit_id) yield finally: repo.git.checkout(current_head) def clean_code(content: str) -> str: """ Remove docstrings, empty line or comments from some code (used to detect if a diff is real or only concern comments or docstings). Args: content (`str`): The code to clean Returns: `str`: The cleaned code. """ # We need to deactivate autoformatting here to write escaped triple quotes (we cannot use real triple quotes or # this would mess up the result if this function applied to this particular file). # fmt: off # Remove docstrings by splitting on triple " then triple ': splits = content.split('\"\"\"') content = "".join(splits[::2]) splits = content.split("\'\'\'") # fmt: on content = "".join(splits[::2]) # Remove empty lines and comments lines_to_keep = [] for line in content.split("\n"): # remove anything that is after a # sign. line = re.sub("#.*$", "", line) # remove white lines if len(line) != 0 and not line.isspace(): lines_to_keep.append(line) return "\n".join(lines_to_keep) def keep_doc_examples_only(content: str) -> str: """ Remove everything from the code content except the doc examples (used to determined if a diff should trigger doc tests or not). Args: content (`str`): The code to clean Returns: `str`: The cleaned code. """ # Keep doc examples only by splitting on triple "`" splits = content.split("```") # Add leading and trailing "```" so the navigation is easier when compared to the original input `content` content = "```" + "```".join(splits[1::2]) + "```" # Remove empty lines and comments lines_to_keep = [] for line in content.split("\n"): # remove anything that is after a # sign. line = re.sub("#.*$", "", line) # remove white lines if len(line) != 0 and not line.isspace(): lines_to_keep.append(line) return "\n".join(lines_to_keep) def get_all_tests() -> List[str]: """ Walks the `tests` folder to return a list of files/subfolders. This is used to split the tests to run when using paralellism. The split is: - folders under `tests`: (`tokenization`, `pipelines`, etc) except the subfolder `models` is excluded. - folders under `tests/models`: `bert`, `gpt2`, etc. - test files under `tests`: `test_modeling_common.py`, `test_tokenization_common.py`, etc. """ # test folders/files directly under `tests` folder tests = os.listdir(PATH_TO_TESTS) tests = [f"tests/{f}" for f in tests if "__pycache__" not in f] tests = sorted([f for f in tests if (PATH_TO_REPO / f).is_dir() or f.startswith("tests/test_")]) # model specific test folders model_test_folders = os.listdir(PATH_TO_TESTS / "models") model_test_folders = [f"tests/models/{f}" for f in model_test_folders if "__pycache__" not in f] model_test_folders = sorted([f for f in model_test_folders if (PATH_TO_REPO / f).is_dir()]) tests.remove("tests/models") # Sagemaker tests are not meant to be run on the CI. if "tests/sagemaker" in tests: tests.remove("tests/sagemaker") tests = model_test_folders + tests return tests def diff_is_docstring_only(repo: Repo, branching_point: str, filename: str) -> bool: """ Check if the diff is only in docstrings (or comments and whitespace) in a filename. Args: repo (`git.Repo`): A git repository (for instance the Transformers repo). branching_point (`str`): The commit reference of where to compare for the diff. filename (`str`): The filename where we want to know if the diff isonly in docstrings/comments. Returns: `bool`: Whether the diff is docstring/comments only or not. """ folder = Path(repo.working_dir) with checkout_commit(repo, branching_point): with open(folder / filename, "r", encoding="utf-8") as f: old_content = f.read() with open(folder / filename, "r", encoding="utf-8") as f: new_content = f.read() old_content_clean = clean_code(old_content) new_content_clean = clean_code(new_content) return old_content_clean == new_content_clean def diff_contains_doc_examples(repo: Repo, branching_point: str, filename: str) -> bool: """ Check if the diff is only in code examples of the doc in a filename. Args: repo (`git.Repo`): A git repository (for instance the Transformers repo). branching_point (`str`): The commit reference of where to compare for the diff. filename (`str`): The filename where we want to know if the diff is only in codes examples. Returns: `bool`: Whether the diff is only in code examples of the doc or not. """ folder = Path(repo.working_dir) with checkout_commit(repo, branching_point): with open(folder / filename, "r", encoding="utf-8") as f: old_content = f.read() with open(folder / filename, "r", encoding="utf-8") as f: new_content = f.read() old_content_clean = keep_doc_examples_only(old_content) new_content_clean = keep_doc_examples_only(new_content) return old_content_clean != new_content_clean def get_impacted_files_from_tiny_model_summary(diff_with_last_commit: bool = False) -> List[str]: """ Return a list of python modeling files that are impacted by the changes of `tiny_model_summary.json` in between: - the current head and the main branch if `diff_with_last_commit=False` (default) - the current head and its parent commit otherwise. Returns: `List[str]`: The list of Python modeling files that are impacted by the changes of `tiny_model_summary.json`. """ repo = Repo(PATH_TO_REPO) folder = Path(repo.working_dir) if not diff_with_last_commit: print(f"main is at {repo.refs.main.commit}") print(f"Current head is at {repo.head.commit}") commits = repo.merge_base(repo.refs.main, repo.head) for commit in commits: print(f"Branching commit: {commit}") else: print(f"main is at {repo.head.commit}") commits = repo.head.commit.parents for commit in commits: print(f"Parent commit: {commit}") if not os.path.isfile(folder / "tests/utils/tiny_model_summary.json"): return [] files = set() for commit in commits: with checkout_commit(repo, commit): with open(folder / "tests/utils/tiny_model_summary.json", "r", encoding="utf-8") as f: old_content = f.read() with open(folder / "tests/utils/tiny_model_summary.json", "r", encoding="utf-8") as f: new_content = f.read() # get the content as json object old_content = json.loads(old_content) new_content = json.loads(new_content) old_keys = set(old_content.keys()) new_keys = set(new_content.keys()) # get the difference keys_with_diff = old_keys.symmetric_difference(new_keys) common_keys = old_keys.intersection(new_keys) # if both have the same key, check its content for key in common_keys: if old_content[key] != new_content[key]: keys_with_diff.add(key) # get the model classes impacted_model_classes = [] for key in keys_with_diff: if key in new_keys: impacted_model_classes.extend(new_content[key]["model_classes"]) # get the module where the model classes are defined. We want to use the main `__init__` file, but it requires # all the framework being installed, which is not ideal for a simple script like test fetcher. # So we create a temporary and modified main `__init__` and access its `_import_structure`. with open(folder / "src/transformers/__init__.py") as fp: lines = fp.readlines() new_lines = [] # Get all the code related to `_import_structure` for line in lines: if line == "_import_structure = {\n": new_lines.append(line) elif line == "# Direct imports for type-checking\n": break elif len(new_lines) > 0: # bypass the framework check so we can get all the information even if frameworks are not available line = re.sub(r"is_.+_available\(\)", "True", line) line = line.replace("OptionalDependencyNotAvailable", "Exception") line = line.replace("Exception()", "Exception") new_lines.append(line) # create and load the temporary module with tempfile.TemporaryDirectory() as tmpdirname: with open(os.path.join(tmpdirname, "temp_init.py"), "w") as fp: fp.write("".join(new_lines)) spec = importlib.util.spec_from_file_location("temp_init", os.path.join(tmpdirname, "temp_init.py")) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) # Finally, get `_import_structure` that we need import_structure = module._import_structure # map model classes to their defined module reversed_structure = {} for key, values in import_structure.items(): for value in values: reversed_structure[value] = key # Get the corresponding modeling file path for model_class in impacted_model_classes: module = reversed_structure[model_class] framework = "" if model_class.startswith("TF"): framework = "tf" elif model_class.startswith("Flax"): framework = "flax" fn = ( f"modeling_{module.split('.')[-1]}.py" if framework == "" else f"modeling_{framework}_{module.split('.')[-1]}.py" ) files.add( f"src.transformers.{module}.{fn}".replace(".", os.path.sep).replace(f"{os.path.sep}py", ".py") ) return sorted(files) def get_diff(repo: Repo, base_commit: str, commits: List[str]) -> List[str]: """ Get the diff between a base commit and one or several commits. Args: repo (`git.Repo`): A git repository (for instance the Transformers repo). base_commit (`str`): The commit reference of where to compare for the diff. This is the current commit, not the branching point! commits (`List[str]`): The list of commits with which to compare the repo at `base_commit` (so the branching point). Returns: `List[str]`: The list of Python files with a diff (files added, renamed or deleted are always returned, files modified are returned if the diff in the file is not only in docstrings or comments, see `diff_is_docstring_only`). """ print("\n### DIFF ###\n") code_diff = [] for commit in commits: for diff_obj in commit.diff(base_commit): # We always add new python files if diff_obj.change_type == "A" and diff_obj.b_path.endswith(".py"): code_diff.append(diff_obj.b_path) # We check that deleted python files won't break corresponding tests. elif diff_obj.change_type == "D" and diff_obj.a_path.endswith(".py"): code_diff.append(diff_obj.a_path) # Now for modified files elif diff_obj.change_type in ["M", "R"] and diff_obj.b_path.endswith(".py"): # In case of renames, we'll look at the tests using both the old and new name. if diff_obj.a_path != diff_obj.b_path: code_diff.extend([diff_obj.a_path, diff_obj.b_path]) else: # Otherwise, we check modifications are in code and not docstrings. if diff_is_docstring_only(repo, commit, diff_obj.b_path): print(f"Ignoring diff in {diff_obj.b_path} as it only concerns docstrings or comments.") else: code_diff.append(diff_obj.a_path) return code_diff def get_modified_python_files(diff_with_last_commit: bool = False) -> List[str]: """ Return a list of python files that have been modified between: - the current head and the main branch if `diff_with_last_commit=False` (default) - the current head and its parent commit otherwise. Returns: `List[str]`: The list of Python files with a diff (files added, renamed or deleted are always returned, files modified are returned if the diff in the file is not only in docstrings or comments, see `diff_is_docstring_only`). """ repo = Repo(PATH_TO_REPO) if not diff_with_last_commit: print(f"main is at {repo.refs.main.commit}") print(f"Current head is at {repo.head.commit}") branching_commits = repo.merge_base(repo.refs.main, repo.head) for commit in branching_commits: print(f"Branching commit: {commit}") return get_diff(repo, repo.head.commit, branching_commits) else: print(f"main is at {repo.head.commit}") parent_commits = repo.head.commit.parents for commit in parent_commits: print(f"Parent commit: {commit}") return get_diff(repo, repo.head.commit, parent_commits) def get_diff_for_doctesting(repo: Repo, base_commit: str, commits: List[str]) -> List[str]: """ Get the diff in doc examples between a base commit and one or several commits. Args: repo (`git.Repo`): A git repository (for instance the Transformers repo). base_commit (`str`): The commit reference of where to compare for the diff. This is the current commit, not the branching point! commits (`List[str]`): The list of commits with which to compare the repo at `base_commit` (so the branching point). Returns: `List[str]`: The list of Python and Markdown files with a diff (files added or renamed are always returned, files modified are returned if the diff in the file is only in doctest examples). """ print("\n### DIFF ###\n") code_diff = [] for commit in commits: for diff_obj in commit.diff(base_commit): # We only consider Python files and doc files. if not diff_obj.b_path.endswith(".py") and not diff_obj.b_path.endswith(".md"): continue # We always add new python/md files if diff_obj.change_type in ["A"]: code_diff.append(diff_obj.b_path) # Now for modified files elif diff_obj.change_type in ["M", "R"]: # In case of renames, we'll look at the tests using both the old and new name. if diff_obj.a_path != diff_obj.b_path: code_diff.extend([diff_obj.a_path, diff_obj.b_path]) else: # Otherwise, we check modifications contain some doc example(s). if diff_contains_doc_examples(repo, commit, diff_obj.b_path): code_diff.append(diff_obj.a_path) else: print(f"Ignoring diff in {diff_obj.b_path} as it doesn't contain any doc example.") return code_diff def get_all_doctest_files() -> List[str]: """ Return the complete list of python and Markdown files on which we run doctest. At this moment, we restrict this to only take files from `src/` or `docs/source/en/` that are not in `utils/not_doctested.txt`. Returns: `List[str]`: The complete list of Python and Markdown files on which we run doctest. """ py_files = [str(x.relative_to(PATH_TO_REPO)) for x in PATH_TO_REPO.glob("**/*.py")] md_files = [str(x.relative_to(PATH_TO_REPO)) for x in PATH_TO_REPO.glob("**/*.md")] test_files_to_run = py_files + md_files # only include files in `src` or `docs/source/en/` test_files_to_run = [x for x in test_files_to_run if x.startswith(("src/", "docs/source/en/"))] # not include init files test_files_to_run = [x for x in test_files_to_run if not x.endswith(("__init__.py",))] # These are files not doctested yet. with open("utils/not_doctested.txt") as fp: not_doctested = {x.split(" ")[0] for x in fp.read().strip().split("\n")} # So far we don't have 100% coverage for doctest. This line will be removed once we achieve 100%. test_files_to_run = [x for x in test_files_to_run if x not in not_doctested] return sorted(test_files_to_run) def get_new_doctest_files(repo, base_commit, branching_commit) -> List[str]: """ Get the list of files that were removed from "utils/not_doctested.txt", between `base_commit` and `branching_commit`. Returns: `List[str]`: List of files that were removed from "utils/not_doctested.txt". """ for diff_obj in branching_commit.diff(base_commit): # Ignores all but the "utils/not_doctested.txt" file. if diff_obj.a_path != "utils/not_doctested.txt": continue # Loads the two versions folder = Path(repo.working_dir) with checkout_commit(repo, branching_commit): with open(folder / "utils/not_doctested.txt", "r", encoding="utf-8") as f: old_content = f.read() with open(folder / "utils/not_doctested.txt", "r", encoding="utf-8") as f: new_content = f.read() # Compute the removed lines and return them removed_content = {x.split(" ")[0] for x in old_content.split("\n")} - { x.split(" ")[0] for x in new_content.split("\n") } return sorted(removed_content) return [] def get_doctest_files(diff_with_last_commit: bool = False) -> List[str]: """ Return a list of python and Markdown files where doc example have been modified between: - the current head and the main branch if `diff_with_last_commit=False` (default) - the current head and its parent commit otherwise. Returns: `List[str]`: The list of Python and Markdown files with a diff (files added or renamed are always returned, files modified are returned if the diff in the file is only in doctest examples). """ repo = Repo(PATH_TO_REPO) test_files_to_run = [] # noqa if not diff_with_last_commit: print(f"main is at {repo.refs.main.commit}") print(f"Current head is at {repo.head.commit}") branching_commits = repo.merge_base(repo.refs.main, repo.head) for commit in branching_commits: print(f"Branching commit: {commit}") test_files_to_run = get_diff_for_doctesting(repo, repo.head.commit, branching_commits) else: print(f"main is at {repo.head.commit}") parent_commits = repo.head.commit.parents for commit in parent_commits: print(f"Parent commit: {commit}") test_files_to_run = get_diff_for_doctesting(repo, repo.head.commit, parent_commits) all_test_files_to_run = get_all_doctest_files() # Add to the test files to run any removed entry from "utils/not_doctested.txt". new_test_files = get_new_doctest_files(repo, repo.head.commit, repo.refs.main.commit) test_files_to_run = list(set(test_files_to_run + new_test_files)) # Do not run slow doctest tests on CircleCI with open("utils/slow_documentation_tests.txt") as fp: slow_documentation_tests = set(fp.read().strip().split("\n")) test_files_to_run = [ x for x in test_files_to_run if x in all_test_files_to_run and x not in slow_documentation_tests ] # Make sure we did not end up with a test file that was removed test_files_to_run = [f for f in test_files_to_run if (PATH_TO_REPO / f).exists()] return sorted(test_files_to_run) # (:?^|\n) -> Non-catching group for the beginning of the doc or a new line. # \s*from\s+(\.+\S+)\s+import\s+([^\n]+) -> Line only contains from .xxx import yyy and we catch .xxx and yyy # (?=\n) -> Look-ahead to a new line. We can't just put \n here or using find_all on this re will only catch every # other import. _re_single_line_relative_imports = re.compile(r"(?:^|\n)\s*from\s+(\.+\S+)\s+import\s+([^\n]+)(?=\n)") # (:?^|\n) -> Non-catching group for the beginning of the doc or a new line. # \s*from\s+(\.+\S+)\s+import\s+\(([^\)]+)\) -> Line continues with from .xxx import (yyy) and we catch .xxx and yyy # yyy will take multiple lines otherwise there wouldn't be parenthesis. _re_multi_line_relative_imports = re.compile(r"(?:^|\n)\s*from\s+(\.+\S+)\s+import\s+\(([^\)]+)\)") # (:?^|\n) -> Non-catching group for the beginning of the doc or a new line. # \s*from\s+transformers(\S*)\s+import\s+([^\n]+) -> Line only contains from transformers.xxx import yyy and we catch # .xxx and yyy # (?=\n) -> Look-ahead to a new line. We can't just put \n here or using find_all on this re will only catch every # other import. _re_single_line_direct_imports = re.compile(r"(?:^|\n)\s*from\s+transformers(\S*)\s+import\s+([^\n]+)(?=\n)") # (:?^|\n) -> Non-catching group for the beginning of the doc or a new line. # \s*from\s+transformers(\S*)\s+import\s+\(([^\)]+)\) -> Line continues with from transformers.xxx import (yyy) and we # catch .xxx and yyy. yyy will take multiple lines otherwise there wouldn't be parenthesis. _re_multi_line_direct_imports = re.compile(r"(?:^|\n)\s*from\s+transformers(\S*)\s+import\s+\(([^\)]+)\)") def extract_imports(module_fname: str, cache: Dict[str, List[str]] = None) -> List[str]: """ Get the imports a given module makes. Args: module_fname (`str`): The name of the file of the module where we want to look at the imports (given relative to the root of the repo). cache (Dictionary `str` to `List[str]`, *optional*): To speed up this function if it was previously called on `module_fname`, the cache of all previously computed results. Returns: `List[str]`: The list of module filenames imported in the input `module_fname` (a submodule we import from that is a subfolder will give its init file). """ if cache is not None and module_fname in cache: return cache[module_fname] with open(PATH_TO_REPO / module_fname, "r", encoding="utf-8") as f: content = f.read() # Filter out all docstrings to not get imports in code examples. As before we need to deactivate formatting to # keep this as escaped quotes and avoid this function failing on this file. splits = content.split('\"\"\"') # fmt: skip content = "".join(splits[::2]) module_parts = str(module_fname).split(os.path.sep) imported_modules = [] # Let's start with relative imports relative_imports = _re_single_line_relative_imports.findall(content) relative_imports = [ (mod, imp) for mod, imp in relative_imports if "# tests_ignore" not in imp and imp.strip() != "(" ] multiline_relative_imports = _re_multi_line_relative_imports.findall(content) relative_imports += [(mod, imp) for mod, imp in multiline_relative_imports if "# tests_ignore" not in imp] # We need to remove parts of the module name depending on the depth of the relative imports. for module, imports in relative_imports: level = 0 while module.startswith("."): module = module[1:] level += 1 if len(module) > 0: dep_parts = module_parts[: len(module_parts) - level] + module.split(".") else: dep_parts = module_parts[: len(module_parts) - level] imported_module = os.path.sep.join(dep_parts) imported_modules.append((imported_module, [imp.strip() for imp in imports.split(",")])) # Let's continue with direct imports direct_imports = _re_single_line_direct_imports.findall(content) direct_imports = [(mod, imp) for mod, imp in direct_imports if "# tests_ignore" not in imp and imp.strip() != "("] multiline_direct_imports = _re_multi_line_direct_imports.findall(content) direct_imports += [(mod, imp) for mod, imp in multiline_direct_imports if "# tests_ignore" not in imp] # We need to find the relative path of those imports. for module, imports in direct_imports: import_parts = module.split(".")[1:] # ignore the name of the repo since we add it below. dep_parts = ["src", "transformers"] + import_parts imported_module = os.path.sep.join(dep_parts) imported_modules.append((imported_module, [imp.strip() for imp in imports.split(",")])) result = [] # Double check we get proper modules (either a python file or a folder with an init). for module_file, imports in imported_modules: if (PATH_TO_REPO / f"{module_file}.py").is_file(): module_file = f"{module_file}.py" elif (PATH_TO_REPO / module_file).is_dir() and (PATH_TO_REPO / module_file / "__init__.py").is_file(): module_file = os.path.sep.join([module_file, "__init__.py"]) imports = [imp for imp in imports if len(imp) > 0 and re.match("^[A-Za-z0-9_]*$", imp)] if len(imports) > 0: result.append((module_file, imports)) if cache is not None: cache[module_fname] = result return result def get_module_dependencies(module_fname: str, cache: Dict[str, List[str]] = None) -> List[str]: """ Refines the result of `extract_imports` to remove subfolders and get a proper list of module filenames: if a file as an import `from utils import Foo, Bar`, with `utils` being a subfolder containing many files, this will traverse the `utils` init file to check where those dependencies come from: for instance the files utils/foo.py and utils/bar.py. Warning: This presupposes that all intermediate inits are properly built (with imports from the respective submodules) and work better if objects are defined in submodules and not the intermediate init (otherwise the intermediate init is added, and inits usually have a lot of dependencies). Args: module_fname (`str`): The name of the file of the module where we want to look at the imports (given relative to the root of the repo). cache (Dictionary `str` to `List[str]`, *optional*): To speed up this function if it was previously called on `module_fname`, the cache of all previously computed results. Returns: `List[str]`: The list of module filenames imported in the input `module_fname` (with submodule imports refined). """ dependencies = [] imported_modules = extract_imports(module_fname, cache=cache) # The while loop is to recursively traverse all inits we may encounter: we will add things as we go. while len(imported_modules) > 0: new_modules = [] for module, imports in imported_modules: # If we end up in an __init__ we are often not actually importing from this init (except in the case where # the object is fully defined in the __init__) if module.endswith("__init__.py"): # So we get the imports from that init then try to find where our objects come from. new_imported_modules = extract_imports(module, cache=cache) for new_module, new_imports in new_imported_modules: if any(i in new_imports for i in imports): if new_module not in dependencies: new_modules.append((new_module, [i for i in new_imports if i in imports])) imports = [i for i in imports if i not in new_imports] if len(imports) > 0: # If there are any objects lefts, they may be a submodule path_to_module = PATH_TO_REPO / module.replace("__init__.py", "") dependencies.extend( [ os.path.join(module.replace("__init__.py", ""), f"{i}.py") for i in imports if (path_to_module / f"{i}.py").is_file() ] ) imports = [i for i in imports if not (path_to_module / f"{i}.py").is_file()] if len(imports) > 0: # Then if there are still objects left, they are fully defined in the init, so we keep it as a # dependency. dependencies.append(module) else: dependencies.append(module) imported_modules = new_modules return dependencies def create_reverse_dependency_tree() -> List[Tuple[str, str]]: """ Create a list of all edges (a, b) which mean that modifying a impacts b with a going over all module and test files. """ cache = {} all_modules = list(PATH_TO_TRANFORMERS.glob("**/*.py")) + list(PATH_TO_TESTS.glob("**/*.py")) all_modules = [str(mod.relative_to(PATH_TO_REPO)) for mod in all_modules] edges = [(dep, mod) for mod in all_modules for dep in get_module_dependencies(mod, cache=cache)] return list(set(edges)) def get_tree_starting_at(module: str, edges: List[Tuple[str, str]]) -> List[Union[str, List[str]]]: """ Returns the tree starting at a given module following all edges. Args: module (`str`): The module that will be the root of the subtree we want. eges (`List[Tuple[str, str]]`): The list of all edges of the tree. Returns: `List[Union[str, List[str]]]`: The tree to print in the following format: [module, [list of edges starting at module], [list of edges starting at the preceding level], ...] """ vertices_seen = [module] new_edges = [edge for edge in edges if edge[0] == module and edge[1] != module and "__init__.py" not in edge[1]] tree = [module] while len(new_edges) > 0: tree.append(new_edges) final_vertices = list({edge[1] for edge in new_edges}) vertices_seen.extend(final_vertices) new_edges = [ edge for edge in edges if edge[0] in final_vertices and edge[1] not in vertices_seen and "__init__.py" not in edge[1] ] return tree def print_tree_deps_of(module, all_edges=None): """ Prints the tree of modules depending on a given module. Args: module (`str`): The module that will be the root of the subtree we want. all_eges (`List[Tuple[str, str]]`, *optional*): The list of all edges of the tree. Will be set to `create_reverse_dependency_tree()` if not passed. """ if all_edges is None: all_edges = create_reverse_dependency_tree() tree = get_tree_starting_at(module, all_edges) # The list of lines is a list of tuples (line_to_be_printed, module) # Keeping the modules lets us know where to insert each new lines in the list. lines = [(tree[0], tree[0])] for index in range(1, len(tree)): edges = tree[index] start_edges = {edge[0] for edge in edges} for start in start_edges: end_edges = {edge[1] for edge in edges if edge[0] == start} # We will insert all those edges just after the line showing start. pos = 0 while lines[pos][1] != start: pos += 1 lines = lines[: pos + 1] + [(" " * (2 * index) + end, end) for end in end_edges] + lines[pos + 1 :] for line in lines: # We don't print the refs that where just here to help build lines. print(line[0]) def init_test_examples_dependencies() -> Tuple[Dict[str, List[str]], List[str]]: """ The test examples do not import from the examples (which are just scripts, not modules) so we need som extra care initializing the dependency map, which is the goal of this function. It initializes the dependency map for example files by linking each example to the example test file for the example framework. Returns: `Tuple[Dict[str, List[str]], List[str]]`: A tuple with two elements: the initialized dependency map which is a dict test example file to list of example files potentially tested by that test file, and the list of all example files (to avoid recomputing it later). """ test_example_deps = {} all_examples = [] for framework in ["flax", "pytorch", "tensorflow"]: test_files = list((PATH_TO_EXAMPLES / framework).glob("test_*.py")) all_examples.extend(test_files) # Remove the files at the root of examples/framework since they are not proper examples (they are eith utils # or example test files). examples = [ f for f in (PATH_TO_EXAMPLES / framework).glob("**/*.py") if f.parent != PATH_TO_EXAMPLES / framework ] all_examples.extend(examples) for test_file in test_files: with open(test_file, "r", encoding="utf-8") as f: content = f.read() # Map all examples to the test files found in examples/framework. test_example_deps[str(test_file.relative_to(PATH_TO_REPO))] = [ str(e.relative_to(PATH_TO_REPO)) for e in examples if e.name in content ] # Also map the test files to themselves. test_example_deps[str(test_file.relative_to(PATH_TO_REPO))].append( str(test_file.relative_to(PATH_TO_REPO)) ) return test_example_deps, all_examples def create_reverse_dependency_map() -> Dict[str, List[str]]: """ Create the dependency map from module/test filename to the list of modules/tests that depend on it recursively. Returns: `Dict[str, List[str]]`: The reverse dependency map as a dictionary mapping filenames to all the filenames depending on it recursively. This way the tests impacted by a change in file A are the test files in the list corresponding to key A in this result. """ cache = {} # Start from the example deps init. example_deps, examples = init_test_examples_dependencies() # Add all modules and all tests to all examples all_modules = list(PATH_TO_TRANFORMERS.glob("**/*.py")) + list(PATH_TO_TESTS.glob("**/*.py")) + examples all_modules = [str(mod.relative_to(PATH_TO_REPO)) for mod in all_modules] # Compute the direct dependencies of all modules. direct_deps = {m: get_module_dependencies(m, cache=cache) for m in all_modules} direct_deps.update(example_deps) # This recurses the dependencies something_changed = True while something_changed: something_changed = False for m in all_modules: for d in direct_deps[m]: # We stop recursing at an init (cause we always end up in the main init and we don't want to add all # files which the main init imports) if d.endswith("__init__.py"): continue if d not in direct_deps: raise ValueError(f"KeyError:{d}. From {m}") new_deps = set(direct_deps[d]) - set(direct_deps[m]) if len(new_deps) > 0: direct_deps[m].extend(list(new_deps)) something_changed = True # Finally we can build the reverse map. reverse_map = collections.defaultdict(list) for m in all_modules: for d in direct_deps[m]: reverse_map[d].append(m) # For inits, we don't do the reverse deps but the direct deps: if modifying an init, we want to make sure we test # all the modules impacted by that init. for m in [f for f in all_modules if f.endswith("__init__.py")]: direct_deps = get_module_dependencies(m, cache=cache) deps = sum([reverse_map[d] for d in direct_deps if not d.endswith("__init__.py")], direct_deps) reverse_map[m] = list(set(deps) - {m}) return reverse_map def create_module_to_test_map( reverse_map: Dict[str, List[str]] = None, filter_models: bool = False ) -> Dict[str, List[str]]: """ Extract the tests from the reverse_dependency_map and potentially filters the model tests. Args: reverse_map (`Dict[str, List[str]]`, *optional*): The reverse dependency map as created by `create_reverse_dependency_map`. Will default to the result of that function if not provided. filter_models (`bool`, *optional*, defaults to `False`): Whether or not to filter model tests to only include core models if a file impacts a lot of models. Returns: `Dict[str, List[str]]`: A dictionary that maps each file to the tests to execute if that file was modified. """ if reverse_map is None: reverse_map = create_reverse_dependency_map() # Utility that tells us if a given file is a test (taking test examples into account) def is_test(fname): if fname.startswith("tests"): return True if fname.startswith("examples") and fname.split(os.path.sep)[-1].startswith("test"): return True return False # Build the test map test_map = {module: [f for f in deps if is_test(f)] for module, deps in reverse_map.items()} if not filter_models: return test_map # Now we deal with the filtering if `filter_models` is True. num_model_tests = len(list(PATH_TO_TESTS.glob("models/*"))) def has_many_models(tests): # We filter to core models when a given file impacts more than half the model tests. model_tests = {Path(t).parts[2] for t in tests if t.startswith("tests/models/")} return len(model_tests) > num_model_tests // 2 def filter_tests(tests): return [t for t in tests if not t.startswith("tests/models/") or Path(t).parts[2] in IMPORTANT_MODELS] return {module: (filter_tests(tests) if has_many_models(tests) else tests) for module, tests in test_map.items()} def check_imports_all_exist(): """ Isn't used per se by the test fetcher but might be used later as a quality check. Putting this here for now so the code is not lost. This checks all imports in a given file do exist. """ cache = {} all_modules = list(PATH_TO_TRANFORMERS.glob("**/*.py")) + list(PATH_TO_TESTS.glob("**/*.py")) all_modules = [str(mod.relative_to(PATH_TO_REPO)) for mod in all_modules] direct_deps = {m: get_module_dependencies(m, cache=cache) for m in all_modules} for module, deps in direct_deps.items(): for dep in deps: if not (PATH_TO_REPO / dep).is_file(): print(f"{module} has dependency on {dep} which does not exist.") def _print_list(l) -> str: """ Pretty print a list of elements with one line per element and a - starting each line. """ return "\n".join([f"- {f}" for f in l]) def create_json_map(test_files_to_run: List[str], json_output_file: str): """ Creates a map from a list of tests to run to easily split them by category, when running parallelism of slow tests. Args: test_files_to_run (`List[str]`): The list of tests to run. json_output_file (`str`): The path where to store the built json map. """ if json_output_file is None: return test_map = {} for test_file in test_files_to_run: # `test_file` is a path to a test folder/file, starting with `tests/`. For example, # - `tests/models/bert/test_modeling_bert.py` or `tests/models/bert` # - `tests/trainer/test_trainer.py` or `tests/trainer` # - `tests/test_modeling_common.py` names = test_file.split(os.path.sep) if names[1] == "models": # take the part like `models/bert` for modeling tests key = os.path.sep.join(names[1:3]) elif len(names) > 2 or not test_file.endswith(".py"): # test folders under `tests` or python files under them # take the part like tokenization, `pipeline`, etc. for other test categories key = os.path.sep.join(names[1:2]) else: # common test files directly under `tests/` key = "common" if key not in test_map: test_map[key] = [] test_map[key].append(test_file) # sort the keys & values keys = sorted(test_map.keys()) test_map = {k: " ".join(sorted(test_map[k])) for k in keys} with open(json_output_file, "w", encoding="UTF-8") as fp: json.dump(test_map, fp, ensure_ascii=False) def infer_tests_to_run( output_file: str, diff_with_last_commit: bool = False, filter_models: bool = True, json_output_file: Optional[str] = None, ): """ The main function called by the test fetcher. Determines the tests to run from the diff. Args: output_file (`str`): The path where to store the summary of the test fetcher analysis. Other files will be stored in the same folder: - examples_test_list.txt: The list of examples tests to run. - test_repo_utils.txt: Will indicate if the repo utils tests should be run or not. - doctest_list.txt: The list of doctests to run. diff_with_last_commit (`bool`, *optional*, defaults to `False`): Whether to analyze the diff with the last commit (for use on the main branch after a PR is merged) or with the branching point from main (for use on each PR). filter_models (`bool`, *optional*, defaults to `True`): Whether or not to filter the tests to core models only, when a file modified results in a lot of model tests. json_output_file (`str`, *optional*): The path where to store the json file mapping categories of tests to tests to run (used for parallelism or the slow tests). """ modified_files = get_modified_python_files(diff_with_last_commit=diff_with_last_commit) print(f"\n### MODIFIED FILES ###\n{_print_list(modified_files)}") # Create the map that will give us all impacted modules. reverse_map = create_reverse_dependency_map() impacted_files = modified_files.copy() for f in modified_files: if f in reverse_map: impacted_files.extend(reverse_map[f]) # Remove duplicates impacted_files = sorted(set(impacted_files)) print(f"\n### IMPACTED FILES ###\n{_print_list(impacted_files)}") model_impacted = {"/".join(x.split("/")[:3]) for x in impacted_files if x.startswith("tests/models/")} # Grab the corresponding test files: if any(x in modified_files for x in ["setup.py", ".circleci/create_circleci_config.py"]): test_files_to_run = ["tests", "examples"] repo_utils_launch = True elif not filter_models and len(model_impacted) >= NUM_MODELS_TO_TRIGGER_FULL_CI: print( f"More than {NUM_MODELS_TO_TRIGGER_FULL_CI - 1} models are impacted and `filter_models=False`. CI is configured to test everything." ) test_files_to_run = ["tests", "examples"] repo_utils_launch = True else: # All modified tests need to be run. test_files_to_run = [ f for f in modified_files if f.startswith("tests") and f.split(os.path.sep)[-1].startswith("test") ] impacted_files = get_impacted_files_from_tiny_model_summary(diff_with_last_commit=diff_with_last_commit) # Then we grab the corresponding test files. test_map = create_module_to_test_map(reverse_map=reverse_map, filter_models=filter_models) for f in modified_files + impacted_files: if f in test_map: test_files_to_run.extend(test_map[f]) test_files_to_run = sorted(set(test_files_to_run)) # Remove repo utils tests test_files_to_run = [f for f in test_files_to_run if not f.split(os.path.sep)[1] == "repo_utils"] # Remove SageMaker tests test_files_to_run = [f for f in test_files_to_run if not f.split(os.path.sep)[1] == "sagemaker"] # Make sure we did not end up with a test file that was removed test_files_to_run = [f for f in test_files_to_run if (PATH_TO_REPO / f).exists()] repo_utils_launch = any(f.split(os.path.sep)[0] == "utils" for f in modified_files) if repo_utils_launch: repo_util_file = Path(output_file).parent / "test_repo_utils.txt" with open(repo_util_file, "w", encoding="utf-8") as f: f.write("tests/repo_utils") examples_tests_to_run = [f for f in test_files_to_run if f.startswith("examples")] test_files_to_run = [f for f in test_files_to_run if not f.startswith("examples")] print(f"\n### TEST TO RUN ###\n{_print_list(test_files_to_run)}") if len(test_files_to_run) > 0: with open(output_file, "w", encoding="utf-8") as f: f.write(" ".join(test_files_to_run)) # Create a map that maps test categories to test files, i.e. `models/bert` -> [...test_modeling_bert.py, ...] # Get all test directories (and some common test files) under `tests` and `tests/models` if `test_files_to_run` # contains `tests` (i.e. when `setup.py` is changed). if "tests" in test_files_to_run: test_files_to_run = get_all_tests() create_json_map(test_files_to_run, json_output_file) print(f"\n### EXAMPLES TEST TO RUN ###\n{_print_list(examples_tests_to_run)}") if len(examples_tests_to_run) > 0: # We use `all` in the case `commit_flags["test_all"]` as well as in `create_circleci_config.py` for processing if examples_tests_to_run == ["examples"]: examples_tests_to_run = ["all"] example_file = Path(output_file).parent / "examples_test_list.txt" with open(example_file, "w", encoding="utf-8") as f: f.write(" ".join(examples_tests_to_run)) doctest_list = get_doctest_files() print(f"\n### DOCTEST TO RUN ###\n{_print_list(doctest_list)}") if len(doctest_list) > 0: doctest_file = Path(output_file).parent / "doctest_list.txt" with open(doctest_file, "w", encoding="utf-8") as f: f.write(" ".join(doctest_list)) def filter_tests(output_file: str, filters: List[str]): """ Reads the content of the output file and filters out all the tests in a list of given folders. Args: output_file (`str` or `os.PathLike`): The path to the output file of the tests fetcher. filters (`List[str]`): A list of folders to filter. """ if not os.path.isfile(output_file): print("No test file found.") return with open(output_file, "r", encoding="utf-8") as f: test_files = f.read().split(" ") if len(test_files) == 0 or test_files == [""]: print("No tests to filter.") return if test_files == ["tests"]: test_files = [os.path.join("tests", f) for f in os.listdir("tests") if f not in ["__init__.py"] + filters] else: test_files = [f for f in test_files if f.split(os.path.sep)[1] not in filters] with open(output_file, "w", encoding="utf-8") as f: f.write(" ".join(test_files)) def parse_commit_message(commit_message: str) -> Dict[str, bool]: """ Parses the commit message to detect if a command is there to skip, force all or part of the CI. Args: commit_message (`str`): The commit message of the current commit. Returns: `Dict[str, bool]`: A dictionary of strings to bools with keys the following keys: `"skip"`, `"test_all_models"` and `"test_all"`. """ if commit_message is None: return {"skip": False, "no_filter": False, "test_all": False} command_search = re.search(r"\[([^\]]*)\]", commit_message) if command_search is not None: command = command_search.groups()[0] command = command.lower().replace("-", " ").replace("_", " ") skip = command in ["ci skip", "skip ci", "circleci skip", "skip circleci"] no_filter = set(command.split(" ")) == {"no", "filter"} test_all = set(command.split(" ")) == {"test", "all"} return {"skip": skip, "no_filter": no_filter, "test_all": test_all} else: return {"skip": False, "no_filter": False, "test_all": False} if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--output_file", type=str, default="test_list.txt", help="Where to store the list of tests to run" ) parser.add_argument( "--json_output_file", type=str, default="test_map.json", help="Where to store the tests to run in a dictionary format mapping test categories to test files", ) parser.add_argument( "--diff_with_last_commit", action="store_true", help="To fetch the tests between the current commit and the last commit", ) parser.add_argument( "--filter_tests", action="store_true", help="Will filter the pipeline/repo utils tests outside of the generated list of tests.", ) parser.add_argument( "--print_dependencies_of", type=str, help="Will only print the tree of modules depending on the file passed.", default=None, ) parser.add_argument( "--commit_message", type=str, help="The commit message (which could contain a command to force all tests or skip the CI).", default=None, ) args = parser.parse_args() if args.print_dependencies_of is not None: print_tree_deps_of(args.print_dependencies_of) elif args.filter_tests: filter_tests(args.output_file, ["pipelines", "repo_utils"]) else: repo = Repo(PATH_TO_REPO) commit_message = repo.head.commit.message commit_flags = parse_commit_message(commit_message) if commit_flags["skip"]: print("Force-skipping the CI") quit() if commit_flags["no_filter"]: print("Running all tests fetched without filtering.") if commit_flags["test_all"]: print("Force-launching all tests") is_main_branch = not repo.head.is_detached and repo.head.ref == repo.refs.main diff_with_last_commit = args.diff_with_last_commit if not diff_with_last_commit and is_main_branch: print("main branch detected, fetching tests against last commit.") diff_with_last_commit = True if not commit_flags["test_all"]: try: infer_tests_to_run( args.output_file, diff_with_last_commit=diff_with_last_commit, json_output_file=args.json_output_file, filter_models=(not (commit_flags["no_filter"] or is_main_branch)), ) filter_tests(args.output_file, ["repo_utils"]) except Exception as e: print(f"\nError when trying to grab the relevant tests: {e}\n\nRunning all tests.") commit_flags["test_all"] = True if commit_flags["test_all"]: with open(args.output_file, "w", encoding="utf-8") as f: f.write("tests") example_file = Path(args.output_file).parent / "examples_test_list.txt" with open(example_file, "w", encoding="utf-8") as f: f.write("all") test_files_to_run = get_all_tests() create_json_map(test_files_to_run, args.json_output_file)
transformers/utils/tests_fetcher.py/0
{ "file_path": "transformers/utils/tests_fetcher.py", "repo_id": "transformers", "token_count": 22466 }
450
import argparse import math import os import shlex import subprocess import uuid from distutils.util import strtobool import requests def parse_args(): # fmt: off parser = argparse.ArgumentParser() parser.add_argument("--command", type=str, default="", help="the command to run") parser.add_argument("--num-seeds", type=int, default=3, help="the number of random seeds") parser.add_argument("--start-seed", type=int, default=1, help="the number of the starting seed") parser.add_argument("--workers", type=int, default=0, help="the number of workers to run benchmark experimenets") parser.add_argument("--auto-tag", type=lambda x: bool(strtobool(x)), default=True, nargs="?", const=True, help="if toggled, the runs will be tagged with git tags, commit, and pull request number if possible") parser.add_argument("--slurm-template-path", type=str, default=None, help="the path to the slurm template file (see docs for more details)") parser.add_argument("--slurm-gpus-per-task", type=int, default=1, help="the number of gpus per task to use for slurm jobs") parser.add_argument("--slurm-total-cpus", type=int, default=50, help="the number of gpus per task to use for slurm jobs") parser.add_argument("--slurm-ntasks", type=int, default=1, help="the number of tasks to use for slurm jobs") parser.add_argument("--slurm-nodes", type=int, default=None, help="the number of nodes to use for slurm jobs") args = parser.parse_args() # fmt: on return args def run_experiment(command: str): command_list = shlex.split(command) print(f"running {command}") # Use subprocess.PIPE to capture the output fd = subprocess.Popen(command_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, errors = fd.communicate() return_code = fd.returncode assert return_code == 0, f"Command failed with error: {errors.decode('utf-8')}" # Convert bytes to string and strip leading/trailing whitespaces return output.decode("utf-8").strip() def autotag() -> str: wandb_tag = "" print("autotag feature is enabled") git_tag = "" try: git_tag = subprocess.check_output(["git", "describe", "--tags"]).decode("ascii").strip() print(f"identified git tag: {git_tag}") except subprocess.CalledProcessError as e: print(e) if len(git_tag) == 0: try: count = int(subprocess.check_output(["git", "rev-list", "--count", "HEAD"]).decode("ascii").strip()) hash = subprocess.check_output(["git", "rev-parse", "--short", "HEAD"]).decode("ascii").strip() git_tag = f"no-tag-{count}-g{hash}" print(f"identified git tag: {git_tag}") except subprocess.CalledProcessError as e: print(e) wandb_tag = f"{git_tag}" git_commit = subprocess.check_output(["git", "rev-parse", "--verify", "HEAD"]).decode("ascii").strip() try: # try finding the pull request number on github prs = requests.get(f"https://api.github.com/search/issues?q=repo:huggingface/trl+is:pr+{git_commit}") if prs.status_code == 200: prs = prs.json() if len(prs["items"]) > 0: pr = prs["items"][0] pr_number = pr["number"] wandb_tag += f",pr-{pr_number}" print(f"identified github pull request: {pr_number}") except Exception as e: print(e) return wandb_tag if __name__ == "__main__": args = parse_args() if args.auto_tag: existing_wandb_tag = os.environ.get("WANDB_TAGS", "") wandb_tag = autotag() if len(wandb_tag) > 0: if len(existing_wandb_tag) > 0: os.environ["WANDB_TAGS"] = ",".join([existing_wandb_tag, wandb_tag]) else: os.environ["WANDB_TAGS"] = wandb_tag print("WANDB_TAGS: ", os.environ.get("WANDB_TAGS", "")) commands = [] for seed in range(0, args.num_seeds): commands += [" ".join([args.command, "--seed", str(args.start_seed + seed)])] print("======= commands to run:") for command in commands: print(command) if args.workers > 0 and args.slurm_template_path is None: from concurrent.futures import ThreadPoolExecutor executor = ThreadPoolExecutor(max_workers=args.workers, thread_name_prefix="cleanrl-benchmark-worker-") for command in commands: executor.submit(run_experiment, command) executor.shutdown(wait=True) else: print("not running the experiments because --workers is set to 0; just printing the commands to run") # SLURM logic if args.slurm_template_path is not None: if not os.path.exists("slurm"): os.makedirs("slurm") if not os.path.exists("slurm/logs"): os.makedirs("slurm/logs") print("======= slurm commands to run:") with open(args.slurm_template_path) as f: slurm_template = f.read() slurm_template = slurm_template.replace("{{array}}", f"0-{len(commands) - 1}%{args.workers}") slurm_template = slurm_template.replace( "{{seeds}}", f"({' '.join([str(args.start_seed + int(seed)) for seed in range(args.num_seeds)])})" ) slurm_template = slurm_template.replace("{{len_seeds}}", f"{args.num_seeds}") slurm_template = slurm_template.replace("{{command}}", args.command) slurm_template = slurm_template.replace("{{gpus_per_task}}", f"{args.slurm_gpus_per_task}") total_gpus = args.slurm_gpus_per_task * args.slurm_ntasks slurm_cpus_per_gpu = math.ceil(args.slurm_total_cpus / total_gpus) slurm_template = slurm_template.replace("{{cpus_per_gpu}}", f"{slurm_cpus_per_gpu}") slurm_template = slurm_template.replace("{{ntasks}}", f"{args.slurm_ntasks}") if args.slurm_nodes is not None: slurm_template = slurm_template.replace("{{nodes}}", f"#SBATCH --nodes={args.slurm_nodes}") else: slurm_template = slurm_template.replace("{{nodes}}", "") filename = str(uuid.uuid4()) open(os.path.join("slurm", f"{filename}.slurm"), "w").write(slurm_template) slurm_path = os.path.join("slurm", f"{filename}.slurm") print(f"saving command in {slurm_path}") if args.workers > 0: job_id = run_experiment(f"sbatch --parsable {slurm_path}") print(f"Job ID: {job_id}")
trl/benchmark/benchmark.py/0
{ "file_path": "trl/benchmark/benchmark.py", "repo_id": "trl", "token_count": 2824 }
451
# 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://arxiv.org/abs/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-internal-testing/example-images/resolve/main/images/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 examples/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/lora_tuning_peft.mdx/0
{ "file_path": "trl/docs/source/lora_tuning_peft.mdx", "repo_id": "trl", "token_count": 2080 }
452
import argparse import os from accelerate import Accelerator from datasets import load_dataset from peft import LoraConfig from tqdm import tqdm from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments, logging, set_seed from trl import SFTTrainer from trl.trainer import ConstantLengthDataset """ Fine-Tune Llama-7b on SE paired dataset """ def get_args(): parser = argparse.ArgumentParser() parser.add_argument("--model_path", type=str, default="") parser.add_argument("--dataset_name", type=str, default="lvwerra/stack-exchange-paired") parser.add_argument("--subset", type=str, default="data/finetune") parser.add_argument("--split", type=str, default="train") parser.add_argument("--size_valid_set", type=int, default=4000) parser.add_argument("--streaming", action="store_true") parser.add_argument("--shuffle_buffer", type=int, default=5000) parser.add_argument("--seq_length", type=int, default=1024) parser.add_argument("--max_steps", type=int, default=10000) parser.add_argument("--batch_size", type=int, default=4) parser.add_argument("--gradient_accumulation_steps", type=int, default=1) parser.add_argument("--eos_token_id", type=int, default=49152) parser.add_argument("--learning_rate", type=float, default=1e-4) parser.add_argument("--lr_scheduler_type", type=str, default="cosine") parser.add_argument("--num_warmup_steps", type=int, default=100) parser.add_argument("--weight_decay", type=float, default=0.05) parser.add_argument("--local_rank", type=int, default=0) parser.add_argument("--fp16", action="store_true", default=False) parser.add_argument("--bf16", action="store_true", default=False) parser.add_argument("--gradient_checkpointing", action="store_true", default=False) parser.add_argument("--seed", type=int, default=0) parser.add_argument("--num_workers", type=int, default=None) parser.add_argument("--output_dir", type=str, default="./checkpoints") parser.add_argument("--log_freq", default=1, type=int) parser.add_argument("--eval_freq", default=1000, type=int) parser.add_argument("--save_freq", default=1000, type=int) return parser.parse_args() def chars_token_ratio(dataset, tokenizer, nb_examples=400): """ Estimate the average number of characters per token in the dataset. """ total_characters, total_tokens = 0, 0 for _, example in tqdm(zip(range(nb_examples), iter(dataset)), total=nb_examples): text = prepare_sample_text(example) total_characters += len(text) if tokenizer.is_fast: total_tokens += len(tokenizer(text).tokens()) else: total_tokens += len(tokenizer.tokenize(text)) return total_characters / total_tokens def print_trainable_parameters(model): """ Prints the number of trainable parameters in the model. """ trainable_params = 0 all_param = 0 for _, param in model.named_parameters(): all_param += param.numel() if param.requires_grad: trainable_params += param.numel() print( f"trainable params: {trainable_params} || all params: {all_param} || trainable%: {100 * trainable_params / all_param}" ) def prepare_sample_text(example): """Prepare the text from a sample of the dataset.""" text = f"Question: {example['question']}\n\nAnswer: {example['response_j']}" return text def create_datasets(tokenizer, args): dataset = load_dataset( args.dataset_name, data_dir=args.subset, split=args.split, use_auth_token=True, num_proc=args.num_workers if not args.streaming else None, streaming=args.streaming, ) if args.streaming: print("Loading the dataset in streaming mode") valid_data = dataset.take(args.size_valid_set) train_data = dataset.skip(args.size_valid_set) train_data = train_data.shuffle(buffer_size=args.shuffle_buffer, seed=args.seed) else: dataset = dataset.train_test_split(test_size=0.005, seed=args.seed) train_data = dataset["train"] valid_data = dataset["test"] print(f"Size of the train set: {len(train_data)}. Size of the validation set: {len(valid_data)}") chars_per_token = chars_token_ratio(train_data, tokenizer) print(f"The character to token ratio of the dataset is: {chars_per_token:.2f}") train_dataset = ConstantLengthDataset( tokenizer, train_data, formatting_func=prepare_sample_text, infinite=True, seq_length=args.seq_length, chars_per_token=chars_per_token, ) valid_dataset = ConstantLengthDataset( tokenizer, valid_data, formatting_func=prepare_sample_text, infinite=False, seq_length=args.seq_length, chars_per_token=chars_per_token, ) return train_dataset, valid_dataset def run_training(args, train_data, val_data): print("Loading the model") lora_config = LoraConfig( r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM", ) train_data.start_iteration = 0 print("Starting main loop") training_args = TrainingArguments( output_dir=args.output_dir, dataloader_drop_last=True, evaluation_strategy="steps", max_steps=args.max_steps, eval_steps=args.eval_freq, save_steps=args.save_freq, logging_steps=args.log_freq, per_device_train_batch_size=args.batch_size, per_device_eval_batch_size=args.batch_size, learning_rate=args.learning_rate, lr_scheduler_type=args.lr_scheduler_type, warmup_steps=args.num_warmup_steps, gradient_accumulation_steps=args.gradient_accumulation_steps, gradient_checkpointing=args.gradient_checkpointing, fp16=args.fp16, bf16=args.bf16, weight_decay=args.weight_decay, run_name="llama-7b-finetuned", report_to="wandb", ddp_find_unused_parameters=False, ) model = AutoModelForCausalLM.from_pretrained( args.model_path, load_in_8bit=True, device_map={"": Accelerator().process_index} ) trainer = SFTTrainer( model=model, args=training_args, train_dataset=train_data, eval_dataset=val_data, peft_config=lora_config, packing=True, ) print_trainable_parameters(trainer.model) print("Training...") trainer.train() print("Saving last checkpoint of the model") trainer.model.save_pretrained(os.path.join(args.output_dir, "final_checkpoint/")) def main(args): tokenizer = AutoTokenizer.from_pretrained(args.model_path) train_dataset, eval_dataset = create_datasets(tokenizer, args) run_training(args, train_dataset, eval_dataset) if __name__ == "__main__": args = get_args() assert args.model_path != "", "Please provide the llama model path" set_seed(args.seed) os.makedirs(args.output_dir, exist_ok=True) logging.set_verbosity_error() main(args)
trl/examples/research_projects/stack_llama/scripts/supervised_finetuning.py/0
{ "file_path": "trl/examples/research_projects/stack_llama/scripts/supervised_finetuning.py", "repo_id": "trl", "token_count": 2908 }
453
# 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. """ python examples/scripts/ppo.py \ --log_with=wandb """ from dataclasses import dataclass, field from typing import Optional import torch from accelerate import Accelerator from datasets import load_dataset from peft import LoraConfig from tqdm import tqdm from transformers import AutoTokenizer, HfArgumentParser, pipeline from trl import AutoModelForCausalLMWithValueHead, AutoModelForSeq2SeqLMWithValueHead, PPOConfig, PPOTrainer, set_seed from trl.core import LengthSampler from trl.import_utils import is_npu_available, is_xpu_available tqdm.pandas() @dataclass class ScriptArguments: use_seq2seq: bool = field(default=False, metadata={"help": "whether to use seq2seq"}) trust_remote_code: bool = field(default=False, metadata={"help": "Enable `trust_remote_code`"}) # LoraConfig use_peft: bool = field(default=False, metadata={"help": "whether to use peft"}) lora_alpha: Optional[float] = field(default=16, metadata={"help": "the lora alpha parameter"}) lora_r: Optional[int] = field(default=16, metadata={"help": "the lora r parameter"}) parser = HfArgumentParser((ScriptArguments, PPOConfig)) args, ppo_config = parser.parse_args_into_dataclasses() # We then define the arguments to pass to the sentiment analysis pipeline. # We set `return_all_scores` to True to get the sentiment score for each token. sent_kwargs = {"return_all_scores": True, "function_to_apply": "none", "batch_size": 16} trl_model_class = AutoModelForCausalLMWithValueHead if not args.use_seq2seq else AutoModelForSeq2SeqLMWithValueHead # Below is an example function to build the dataset. In our case, we use the IMDB dataset # from the `datasets` library. One should customize this function to train the model on # its own dataset. def build_dataset(config, query_dataset, input_min_text_length=2, input_max_text_length=8): """ Build dataset for training. This builds the dataset from `load_dataset`, one should customize this function to train the model on its own dataset. Args: query_dataset (`str`): The name of the dataset to be loaded. Returns: dataloader (`torch.utils.data.DataLoader`): The dataloader for the dataset. """ tokenizer = AutoTokenizer.from_pretrained(config.model_name) tokenizer.pad_token = tokenizer.eos_token # load imdb with datasets ds = load_dataset(query_dataset, split="train") ds = ds.rename_columns({"text": "review"}) ds = ds.filter(lambda x: len(x["review"]) > 200, batched=False) input_size = LengthSampler(input_min_text_length, input_max_text_length) def tokenize(sample): sample["input_ids"] = tokenizer.encode(sample["review"])[: input_size()] sample["query"] = tokenizer.decode(sample["input_ids"]) return sample ds = ds.map(tokenize, batched=False) ds.set_format(type="torch") return ds # We retrieve the dataloader by calling the `build_dataset` function. dataset = build_dataset(ppo_config, ppo_config.query_dataset) def collator(data): return {key: [d[key] for d in data] for key in data[0]} # set seed before initializing value head for deterministic eval set_seed(ppo_config.seed) # Now let's build the model, the reference model, and the tokenizer. if not args.use_peft: ref_model = trl_model_class.from_pretrained(ppo_config.model_name, trust_remote_code=args.trust_remote_code) device_map = None peft_config = None else: peft_config = LoraConfig( r=args.lora_r, lora_alpha=args.lora_alpha, bias="none", task_type="CAUSAL_LM", ) ref_model = None # Copy the model to each device device_map = {"": Accelerator().local_process_index} model = trl_model_class.from_pretrained( ppo_config.model_name, trust_remote_code=args.trust_remote_code, device_map=device_map, peft_config=peft_config, ) tokenizer = AutoTokenizer.from_pretrained(ppo_config.model_name) # Some tokenizers like GPT-2's don't have a padding token by default, so we set one here. tokenizer.pad_token_id = tokenizer.eos_token_id # We then build the PPOTrainer, passing the model, the reference model, the tokenizer ppo_trainer = PPOTrainer(ppo_config, model, ref_model, tokenizer, dataset=dataset, data_collator=collator) # We then build the sentiment analysis pipeline, passing the model name and the # sentiment analysis pipeline arguments. Let's also make sure to set the device # to the same device as the PPOTrainer. device = ppo_trainer.accelerator.device if ppo_trainer.accelerator.num_processes == 1: if is_xpu_available(): device = "xpu:0" elif is_npu_available(): device = "npu:0" else: device = 0 if torch.cuda.is_available() else "cpu" # to avoid a `pipeline` bug ds_plugin = ppo_trainer.accelerator.state.deepspeed_plugin task, model_name = ppo_config.reward_model.split(":") if ds_plugin is not None and ds_plugin.is_zero3_init_enabled(): with ds_plugin.zero3_init_context_manager(enable=False): sentiment_pipe = pipeline(task, model=model_name, device=device) else: sentiment_pipe = pipeline(task, model=model_name, device=device) # Some tokenizers like GPT-2's don't have a padding token by default, so we set one here. if sentiment_pipe.tokenizer.pad_token_id is None: sentiment_pipe.tokenizer.pad_token_id = tokenizer.pad_token_id if sentiment_pipe.model.config.pad_token_id is None: sentiment_pipe.model.config.pad_token_id = tokenizer.pad_token_id # We then define the arguments to pass to the `generate` function. These arguments # are passed to the `generate` function of the PPOTrainer, which is a wrapper around # the `generate` function of the trained model. generation_kwargs = { "min_length": -1, "top_k": 0.0, "top_p": 1.0, "do_sample": True, "pad_token_id": tokenizer.eos_token_id, "max_new_tokens": 32, } for _epoch, batch in tqdm(enumerate(ppo_trainer.dataloader)): query_tensors = batch["input_ids"] # Get response from gpt2 response_tensors, ref_response_tensors = ppo_trainer.generate( query_tensors, return_prompt=False, generate_ref_response=True, **generation_kwargs ) batch["response"] = tokenizer.batch_decode(response_tensors) batch["ref_response"] = tokenizer.batch_decode(ref_response_tensors) # Compute sentiment score texts = [q + r for q, r in zip(batch["query"], batch["response"])] pipe_outputs = sentiment_pipe(texts, **sent_kwargs) rewards = [torch.tensor(output[1]["score"]) for output in pipe_outputs] ref_texts = [q + r for q, r in zip(batch["query"], batch["ref_response"])] ref_pipe_outputs = sentiment_pipe(ref_texts, **sent_kwargs) ref_rewards = [torch.tensor(output[1]["score"]) for output in ref_pipe_outputs] batch["ref_rewards"] = ref_rewards # Run PPO step stats = ppo_trainer.step(query_tensors, response_tensors, rewards) ppo_trainer.log_stats(stats, batch, rewards, columns_to_log=["query", "response", "ref_response", "ref_rewards"])
trl/examples/scripts/ppo.py/0
{ "file_path": "trl/examples/scripts/ppo.py", "repo_id": "trl", "token_count": 2729 }
454
import unittest import torch from transformers import AutoTokenizer, GenerationConfig from trl import AutoModelForCausalLMWithValueHead from trl.core import LengthSampler from trl.extras import BestOfNSampler def queries_to_scores(list_of_strings): return [torch.rand(1).item() for _ in list_of_strings] class BestOfNSamplerTester(unittest.TestCase): """ Tests the BestOfNSampler class """ ref_model_name = "trl-internal-testing/dummy-GPT2-correct-vocab" output_length_sampler = LengthSampler(2, 6) model = AutoModelForCausalLMWithValueHead.from_pretrained(ref_model_name) tokenizer = AutoTokenizer.from_pretrained(ref_model_name) tokenizer.pad_token = tokenizer.eos_token output_length_sampler = LengthSampler(2, 6) def test_different_input_types(self): r""" Tests if the different input types normalizer works """ generation_config = GenerationConfig( min_length=-1, top_k=0.0, top_p=1.0, do_sample=True, pad_token_id=self.tokenizer.eos_token_id, ) output_length_sampler = LengthSampler(2, 6) best_of_n = BestOfNSampler( self.model, self.tokenizer, queries_to_scores, length_sampler=output_length_sampler, generation_config=generation_config, ) queries = ["hello world", "goodbye world"] tokenized_queries = [self.tokenizer.encode(query) for query in queries] various_queries_formats = [ (tokenized_queries[0], 1), (tokenized_queries, 2), (torch.tensor(tokenized_queries[1]), 1), ([torch.tensor(query) for query in tokenized_queries], 2), ] for q, expected_length in various_queries_formats: results = best_of_n.generate(q) assert isinstance(results, list) assert len(results) == expected_length def test_different_sample_sizes_and_n_candidates_values(self): r""" Tests different sample sizes and n_candidates values """ generation_config = GenerationConfig( min_length=-1, top_k=0.0, top_p=1.0, do_sample=True, pad_token_id=self.tokenizer.eos_token_id, ) output_length_sampler = LengthSampler(6, 10) for sample_value, n_candidates_values, expected in [ (4, 2, 2), (10, 3, 3), (6, 4, 4), ]: best_of_n = BestOfNSampler( self.model, self.tokenizer, queries_to_scores, length_sampler=output_length_sampler, generation_config=generation_config, sample_size=sample_value, n_candidates=n_candidates_values, ) queries = ["hello world", "troll the world"] tokenized_queries = [self.tokenizer.encode(query) for query in queries] results = best_of_n.generate(tokenized_queries) for result in results: assert len(result) == expected
trl/tests/test_best_of_n_sampler.py/0
{ "file_path": "trl/tests/test_best_of_n_sampler.py", "repo_id": "trl", "token_count": 1507 }
455
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import copy import os import tempfile import unittest import numpy as np import pytest import torch from datasets import Dataset from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments from trl import SFTTrainer from trl.import_utils import is_peft_available from trl.trainer import ConstantLengthDataset, DataCollatorForCompletionOnlyLM from .testing_utils import require_peft def formatting_prompts_func(example): text = f"### Question: {example['question']}\n ### Answer: {example['answer']}" return text def formatting_prompts_func_batched(example): output_text = [] for i, question in enumerate(example["question"]): text = f"### Question: {question}\n ### Answer: {example['answer'][i]}" output_text.append(text) return output_text if is_peft_available(): from peft import LoraConfig, PeftModel class SFTTrainerTester(unittest.TestCase): r""" """ @classmethod def setUpClass(cls): cls.model_id = "trl-internal-testing/dummy-GPT2-correct-vocab" cls.model = AutoModelForCausalLM.from_pretrained(cls.model_id) cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_id) cls.tokenizer.pad_token = cls.tokenizer.eos_token cls.dummy_dataset = Dataset.from_dict( { "question": [ "Does llamas know how to code?", "Does llamas know how to fly?", "Does llamas know how to talk?", "Does llamas know how to code?", "Does llamas know how to fly?", "Does llamas know how to talk?", "Does llamas know how to swim?", ], "answer": [ "Yes, llamas are very good at coding.", "No, llamas can't fly.", "Yes, llamas are very good at talking.", "Yes, llamas are very good at coding.", "No, llamas can't fly.", "Yes, llamas are very good at talking.", "No, llamas can't swim.", ], "text": [ "### Question: Does llamas know how to code?\n ### Answer: Yes, llamas are very good at coding.", "### Question: Does llamas know how to fly?\n ### Answer: No, llamas can't fly.", "### Question: Does llamas know how to talk?\n ### Answer: Yes, llamas are very good at talking.", "### Question: Does llamas know how to code?\n ### Answer: Yes, llamas are very good at coding.", "### Question: Does llamas know how to fly?\n ### Answer: No, llamas can't fly.", "### Question: Does llamas know how to talk?\n ### Answer: Yes, llamas are very good at talking.", "### Question: Does llamas know how to swim?\n ### Answer: No, llamas can't swim.", ], } ) cls.dummy_chatml_dataset = Dataset.from_dict( { "messages": [ [ {"role": "system", "content": "You are helpful"}, {"role": "user", "content": "Hello"}, {"role": "assistant", "content": "Hi, how can I help you?"}, {"role": "user", "content": "What is 2+2?"}, {"role": "assistant", "content": "4"}, {"role": "user", "content": "What is 3+3?"}, {"role": "assistant", "content": "6"}, ], [ {"role": "system", "content": "You are helpful"}, {"role": "user", "content": "Hello"}, {"role": "assistant", "content": "Hi, how can I help you?"}, ], ] } ) cls.dummy_instruction_dataset = Dataset.from_list( [ {"prompt": "What is 2+2?", "completion": "4"}, {"prompt": "What is 3+3?", "completion": "6"}, {"prompt": "What is 4+4?", "completion": "8"}, {"prompt": "What is 2+2?", "completion": "4"}, {"prompt": "What is 3+3?", "completion": "6"}, {"prompt": "What is 4+4?", "completion": "8"}, {"prompt": "What is 2+2?", "completion": "4"}, {"prompt": "What is 3+3?", "completion": "6"}, {"prompt": "What is 4+4?", "completion": "8"}, {"prompt": "What is 2+2?", "completion": "4"}, {"prompt": "What is 3+3?", "completion": "6"}, {"prompt": "What is 4+4?", "completion": "8"}, ] ) cls.train_dataset = ConstantLengthDataset( cls.tokenizer, cls.dummy_dataset, dataset_text_field=None, formatting_func=formatting_prompts_func, seq_length=16, num_of_sequences=16, ) cls.eval_dataset = ConstantLengthDataset( cls.tokenizer, cls.dummy_dataset, dataset_text_field=None, formatting_func=formatting_prompts_func, seq_length=16, num_of_sequences=16, ) def test_constant_length_dataset(self): formatted_dataset = ConstantLengthDataset( self.tokenizer, self.dummy_dataset, dataset_text_field=None, formatting_func=formatting_prompts_func, ) assert len(formatted_dataset) == len(self.dummy_dataset) assert len(formatted_dataset) > 0 for example in formatted_dataset: assert "input_ids" in example assert "labels" in example assert len(example["input_ids"]) == formatted_dataset.seq_length assert len(example["labels"]) == formatted_dataset.seq_length decoded_text = self.tokenizer.decode(example["input_ids"]) assert ("Question" in decoded_text) and ("Answer" in decoded_text) def test_sft_trainer(self): with tempfile.TemporaryDirectory() as tmp_dir: training_args = TrainingArguments( output_dir=tmp_dir, dataloader_drop_last=True, evaluation_strategy="steps", max_steps=4, eval_steps=2, save_steps=2, per_device_train_batch_size=2, ) trainer = SFTTrainer( model=self.model_id, args=training_args, train_dataset=self.train_dataset, eval_dataset=self.eval_dataset, packing=True, ) trainer.train() assert trainer.state.log_history[(-1)]["train_loss"] is not None assert trainer.state.log_history[0]["eval_loss"] is not None assert "model.safetensors" in os.listdir(tmp_dir + "/checkpoint-2") def test_sft_trainer_uncorrect_data(self): with tempfile.TemporaryDirectory() as tmp_dir: training_args = TrainingArguments( output_dir=tmp_dir, dataloader_drop_last=True, evaluation_strategy="steps", max_steps=2, eval_steps=1, save_steps=1, per_device_train_batch_size=2, ) with pytest.raises(ValueError): _ = SFTTrainer( model=self.model, args=training_args, train_dataset=self.dummy_dataset, packing=True, ) # this should work since the dummy chatml include the correct format _ = SFTTrainer( model=self.model, args=training_args, train_dataset=self.dummy_chatml_dataset, max_seq_length=32, # make sure there is at least 1 packed sequence num_of_sequences=32, packing=True, ) _ = SFTTrainer( model=self.model, args=training_args, train_dataset=self.dummy_chatml_dataset, packing=False, ) # this should work since the dummy instruction dataset is the correct format _ = SFTTrainer( model=self.model, args=training_args, train_dataset=self.dummy_instruction_dataset, max_seq_length=16, # make sure there is at least 1 packed sequence packing=True, ) _ = SFTTrainer( model=self.model, args=training_args, train_dataset=self.dummy_instruction_dataset, packing=False, ) # This should work _ = SFTTrainer( model=self.model, args=training_args, train_dataset=self.dummy_dataset, formatting_func=formatting_prompts_func, max_seq_length=32, # make sure there is at least 1 packed sequence packing=True, ) with pytest.raises(ValueError): # This should not work because not enough data for one sample _ = SFTTrainer( model=self.model, args=training_args, train_dataset=self.dummy_dataset, formatting_func=formatting_prompts_func, max_seq_length=1024, # make sure there is NOT at least 1 packed sequence packing=True, ) # This should not work as well with pytest.raises(ValueError): _ = SFTTrainer( model=self.model, args=training_args, train_dataset=self.dummy_dataset, formatting_func=formatting_prompts_func, packing=False, ) # but this should work _ = SFTTrainer( model=self.model, args=training_args, train_dataset=self.dummy_dataset, formatting_func=formatting_prompts_func_batched, packing=False, ) def test_sft_trainer_with_model_num_train_epochs(self): with tempfile.TemporaryDirectory() as tmp_dir: training_args = TrainingArguments( output_dir=tmp_dir, dataloader_drop_last=True, evaluation_strategy="steps", max_steps=2, eval_steps=1, save_steps=1, num_train_epochs=2, per_device_train_batch_size=2, ) trainer = SFTTrainer( model=self.model, args=training_args, train_dataset=self.train_dataset, eval_dataset=self.eval_dataset, packing=True, ) trainer.train() assert trainer.state.log_history[(-1)]["train_loss"] is not None assert trainer.state.log_history[0]["eval_loss"] is not None assert "model.safetensors" in os.listdir(tmp_dir + "/checkpoint-2") with tempfile.TemporaryDirectory() as tmp_dir: training_args = TrainingArguments( output_dir=tmp_dir, dataloader_drop_last=True, evaluation_strategy="steps", max_steps=2, save_steps=1, num_train_epochs=2, per_device_train_batch_size=2, ) trainer = SFTTrainer( model=self.model, args=training_args, train_dataset=self.dummy_dataset, dataset_text_field="text", max_seq_length=16, num_of_sequences=16, packing=True, ) trainer.train() assert trainer.state.log_history[(-1)]["train_loss"] is not None assert "model.safetensors" in os.listdir(tmp_dir + "/checkpoint-2") with tempfile.TemporaryDirectory() as tmp_dir: training_args = TrainingArguments( output_dir=tmp_dir, dataloader_drop_last=True, evaluation_strategy="steps", max_steps=2, save_steps=1, num_train_epochs=2, per_device_train_batch_size=2, ) trainer = SFTTrainer( model=self.model, args=training_args, train_dataset=self.dummy_dataset, dataset_text_field="text", max_seq_length=16, ) trainer.train() assert trainer.state.log_history[(-1)]["train_loss"] is not None assert "model.safetensors" in os.listdir(tmp_dir + "/checkpoint-1") def test_sft_trainer_with_model(self): with tempfile.TemporaryDirectory() as tmp_dir: training_args = TrainingArguments( output_dir=tmp_dir, dataloader_drop_last=True, evaluation_strategy="steps", max_steps=2, eval_steps=1, save_steps=1, per_device_train_batch_size=2, ) trainer = SFTTrainer( model=self.model, args=training_args, train_dataset=self.train_dataset, eval_dataset=self.eval_dataset, packing=True, ) trainer.train() assert trainer.state.log_history[(-1)]["train_loss"] is not None assert trainer.state.log_history[0]["eval_loss"] is not None assert "model.safetensors" in os.listdir(tmp_dir + "/checkpoint-2") with tempfile.TemporaryDirectory() as tmp_dir: training_args = TrainingArguments( output_dir=tmp_dir, dataloader_drop_last=True, evaluation_strategy="steps", max_steps=2, save_steps=1, per_device_train_batch_size=2, ) trainer = SFTTrainer( model=self.model, args=training_args, train_dataset=self.dummy_dataset, dataset_text_field="text", max_seq_length=16, num_of_sequences=16, packing=True, ) trainer.train() assert trainer.state.log_history[(-1)]["train_loss"] is not None assert "model.safetensors" in os.listdir(tmp_dir + "/checkpoint-2") # with formatting_func + packed with tempfile.TemporaryDirectory() as tmp_dir: training_args = TrainingArguments( output_dir=tmp_dir, dataloader_drop_last=True, evaluation_strategy="steps", max_steps=2, save_steps=1, per_device_train_batch_size=2, ) trainer = SFTTrainer( model=self.model, args=training_args, train_dataset=self.dummy_dataset, formatting_func=formatting_prompts_func, max_seq_length=16, num_of_sequences=16, packing=True, ) trainer.train() assert trainer.state.log_history[(-1)]["train_loss"] is not None assert "model.safetensors" in os.listdir(tmp_dir + "/checkpoint-2") # with formatting_func + packed with tempfile.TemporaryDirectory() as tmp_dir: training_args = TrainingArguments( output_dir=tmp_dir, dataloader_drop_last=True, evaluation_strategy="steps", max_steps=2, save_steps=1, per_device_train_batch_size=2, ) trainer = SFTTrainer( model=self.model, args=training_args, train_dataset=self.dummy_dataset, formatting_func=formatting_prompts_func_batched, max_seq_length=16, ) trainer.train() assert trainer.state.log_history[(-1)]["train_loss"] is not None assert "model.safetensors" in os.listdir(tmp_dir + "/checkpoint-2") with tempfile.TemporaryDirectory() as tmp_dir: training_args = TrainingArguments( output_dir=tmp_dir, dataloader_drop_last=True, evaluation_strategy="steps", max_steps=2, save_steps=1, per_device_train_batch_size=2, ) trainer = SFTTrainer( model=self.model, args=training_args, train_dataset=self.dummy_dataset, dataset_text_field="text", max_seq_length=16, ) trainer.train() assert trainer.state.log_history[(-1)]["train_loss"] is not None assert "model.safetensors" in os.listdir(tmp_dir + "/checkpoint-1") def test_sft_trainer_with_multiple_eval_datasets(self): with tempfile.TemporaryDirectory() as tmp_dir: training_args = TrainingArguments( output_dir=tmp_dir, dataloader_drop_last=True, evaluation_strategy="steps", max_steps=1, eval_steps=1, save_steps=1, per_device_train_batch_size=2, ) trainer = SFTTrainer( model=self.model_id, args=training_args, train_dataset=self.train_dataset, eval_dataset={ "data1": self.eval_dataset, "data2": self.eval_dataset, }, packing=True, ) trainer.train() assert trainer.state.log_history[(-1)]["train_loss"] is not None assert trainer.state.log_history[0]["eval_data1_loss"] is not None assert trainer.state.log_history[1]["eval_data2_loss"] is not None assert "model.safetensors" in os.listdir(tmp_dir + "/checkpoint-1") def test_data_collator_completion_lm(self): response_template = "### Response:\n" data_collator = DataCollatorForCompletionOnlyLM(response_template, tokenizer=self.tokenizer, mlm=False) text = """\n\n### Instructions:\nHello all this should be masked\n\n### Response:\nI have not been masked correctly.""" encoded_text = self.tokenizer(text) examples = [encoded_text] batch = data_collator(examples) labels = batch["labels"] last_pad_idx = np.where(labels == -100)[1][-1] result_text = self.tokenizer.decode(batch["input_ids"][0, last_pad_idx + 1 :]) assert result_text == "I have not been masked correctly." def test_data_collator_completion_lm_with_multiple_text(self): tokenizer = copy.deepcopy(self.tokenizer) tokenizer.padding_side = "left" response_template = "### Response:\n" data_collator = DataCollatorForCompletionOnlyLM(response_template, tokenizer=tokenizer, mlm=False) text1 = """\n\n### Instructions:\nHello all this should be masked\n\n### Response:\nI have not been masked correctly.""" text2 = """\n\n### Instructions:\nThis is another longer text that should also be masked. This text is significantly longer than the previous one.\n\n### Response:\nI have not been masked correctly.""" encoded_text1 = tokenizer(text1) encoded_text2 = tokenizer(text2) examples = [encoded_text1, encoded_text2] batch = data_collator(examples) for i in range(2): labels = batch["labels"][i] last_pad_idx = np.where(labels == -100)[0][-1] result_text = tokenizer.decode(batch["input_ids"][i, last_pad_idx + 1 :]) assert result_text == "I have not been masked correctly." def test_data_collator_chat_completion_lm(self): instruction_template = "### Human:" assistant_template = "### Assistant:" data_collator = DataCollatorForCompletionOnlyLM( response_template=assistant_template, instruction_template=instruction_template, tokenizer=self.tokenizer, mlm=False, ) text = """### Human: Hello all this should be masked.### Assistant: I should not be masked.### Human: All this should be masked too.### Assistant: I should not be masked too.""" encoded_text = self.tokenizer(text) examples = [encoded_text] batch = data_collator(examples) labels = batch["labels"] non_masked_tokens = batch["input_ids"][labels != -100] result_text = self.tokenizer.decode(non_masked_tokens) assert result_text == " I should not be masked. I should not be masked too." def test_data_collator_chat_completion_lm_with_multiple_text(self): tokenizer = copy.deepcopy(self.tokenizer) tokenizer.padding_side = "left" instruction_template = "### Human:" assistant_template = "### Assistant:" data_collator = DataCollatorForCompletionOnlyLM( response_template=assistant_template, instruction_template=instruction_template, tokenizer=tokenizer, mlm=False, ) text1 = """### Human: Hello all this should be masked.### Assistant: I should not be masked.""" text2 = """### Human: Hello all this should be masked.### Assistant: I should not be masked.### Human: All this should be masked too.### Assistant: I should not be masked too.""" encoded_text1 = tokenizer(text1) encoded_text2 = tokenizer(text2) examples = [encoded_text1, encoded_text2] batch = data_collator(examples) labels = batch["labels"] input_ids = batch["input_ids"] non_masked_tokens1 = input_ids[0][labels[0] != -100] result_text1 = tokenizer.decode(non_masked_tokens1) assert result_text1 == " I should not be masked." non_masked_tokens2 = input_ids[1][labels[1] != -100] result_text2 = tokenizer.decode(non_masked_tokens2) assert result_text2 == " I should not be masked. I should not be masked too." def test_sft_trainer_infinite_with_model(self): with tempfile.TemporaryDirectory() as tmp_dir: training_args = TrainingArguments( output_dir=tmp_dir, dataloader_drop_last=True, evaluation_strategy="steps", max_steps=5, eval_steps=1, save_steps=1, per_device_train_batch_size=2, ) trainer = SFTTrainer( model=self.model, args=training_args, train_dataset=self.train_dataset, eval_dataset=self.eval_dataset, packing=True, max_seq_length=500, ) assert trainer.train_dataset.infinite trainer.train() assert trainer.state.log_history[(-1)]["train_loss"] is not None assert trainer.state.log_history[0]["eval_loss"] is not None # make sure the trainer did 5 steps assert "model.safetensors" in os.listdir(tmp_dir + "/checkpoint-5") def test_sft_trainer_infinite_with_model_epochs(self): with tempfile.TemporaryDirectory() as tmp_dir: training_args = TrainingArguments( output_dir=tmp_dir, dataloader_drop_last=True, num_train_epochs=1, per_device_train_batch_size=2, save_strategy="epoch", ) trainer = SFTTrainer( model=self.model, args=training_args, train_dataset=self.train_dataset, eval_dataset=self.eval_dataset, packing=True, max_seq_length=500, ) assert not trainer.train_dataset.infinite trainer.train() assert trainer.state.log_history[(-1)]["train_loss"] is not None # make sure the trainer did 5 steps assert "model.safetensors" in os.listdir(tmp_dir + "/checkpoint-4") def test_sft_trainer_with_model_neftune(self): with tempfile.TemporaryDirectory() as tmp_dir: training_args = TrainingArguments( output_dir=tmp_dir, dataloader_drop_last=True, evaluation_strategy="steps", max_steps=2, eval_steps=1, save_steps=1, per_device_train_batch_size=2, ) trainer = SFTTrainer( model=self.model, args=training_args, train_dataset=self.train_dataset, eval_dataset=self.eval_dataset, neftune_noise_alpha=5, packing=True, ) trainer.model = trainer._trl_activate_neftune(trainer.model) device = trainer.model.get_input_embeddings().weight.device trainer.model.train() torch.random.manual_seed(42) embeds_neftune = trainer.model.get_input_embeddings()(torch.LongTensor([[1, 0, 1]]).to(device)) torch.random.manual_seed(24) embeds_neftune_2 = trainer.model.get_input_embeddings()(torch.LongTensor([[1, 0, 1]]).to(device)) assert not torch.allclose(embeds_neftune, embeds_neftune_2) assert len(trainer.model.get_input_embeddings()._forward_hooks) > 0 trainer.neftune_hook_handle.remove() trainer.train() # Make sure forward pass works fine _ = trainer.model(torch.LongTensor([[1, 0, 1]]).to(device)) assert len(trainer.model.get_input_embeddings()._forward_hooks) == 0 @require_peft def test_peft_sft_trainer_str(self): peft_config = LoraConfig( r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM", ) _ = SFTTrainer( model=self.model_id, args=None, train_dataset=self.train_dataset, eval_dataset=self.eval_dataset, peft_config=peft_config, packing=True, ) @require_peft def test_peft_sft_trainer(self): with tempfile.TemporaryDirectory() as tmp_dir: training_args = TrainingArguments( output_dir=tmp_dir, dataloader_drop_last=True, evaluation_strategy="steps", max_steps=4, eval_steps=2, save_steps=2, per_device_train_batch_size=2, ) peft_config = LoraConfig( r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM", ) trainer = SFTTrainer( model=self.model_id, args=training_args, train_dataset=self.train_dataset, eval_dataset=self.eval_dataset, peft_config=peft_config, packing=True, ) assert isinstance(trainer.model, PeftModel) trainer.train() assert trainer.state.log_history[(-1)]["train_loss"] is not None assert trainer.state.log_history[0]["eval_loss"] is not None assert "adapter_model.safetensors" in os.listdir(tmp_dir + "/checkpoint-2") assert "adapter_config.json" in os.listdir(tmp_dir + "/checkpoint-2") assert "model.safetensors" not in os.listdir(tmp_dir + "/checkpoint-2") @require_peft def test_peft_sft_trainer_gc(self): with tempfile.TemporaryDirectory() as tmp_dir: training_args = TrainingArguments( output_dir=tmp_dir, dataloader_drop_last=True, evaluation_strategy="steps", max_steps=4, eval_steps=2, save_steps=2, per_device_train_batch_size=2, gradient_checkpointing=True, ) peft_config = LoraConfig( r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM", ) trainer = SFTTrainer( model=self.model_id, args=training_args, train_dataset=self.train_dataset, eval_dataset=self.eval_dataset, peft_config=peft_config, packing=True, ) assert isinstance(trainer.model, PeftModel) trainer.train() assert trainer.state.log_history[(-1)]["train_loss"] is not None assert trainer.state.log_history[0]["eval_loss"] is not None assert "adapter_model.safetensors" in os.listdir(tmp_dir + "/checkpoint-2") assert "adapter_config.json" in os.listdir(tmp_dir + "/checkpoint-2") assert "model.safetensors" not in os.listdir(tmp_dir + "/checkpoint-2") @require_peft def test_peft_sft_trainer_neftune(self): with tempfile.TemporaryDirectory() as tmp_dir: training_args = TrainingArguments( output_dir=tmp_dir, dataloader_drop_last=True, evaluation_strategy="steps", max_steps=4, eval_steps=2, save_steps=2, per_device_train_batch_size=2, ) peft_config = LoraConfig( r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM", ) trainer = SFTTrainer( model=self.model_id, args=training_args, train_dataset=self.train_dataset, eval_dataset=self.eval_dataset, peft_config=peft_config, neftune_noise_alpha=5, packing=True, ) trainer.model = trainer._trl_activate_neftune(trainer.model) assert isinstance(trainer.model, PeftModel) device = trainer.model.get_input_embeddings().weight.device trainer.model.train() torch.random.manual_seed(42) embeds_neftune = trainer.model.get_input_embeddings()(torch.LongTensor([[1, 0, 1]]).to(device)) torch.random.manual_seed(24) embeds_neftune_2 = trainer.model.get_input_embeddings()(torch.LongTensor([[1, 0, 1]]).to(device)) assert not torch.allclose(embeds_neftune, embeds_neftune_2) assert len(trainer.model.get_input_embeddings()._forward_hooks) > 0 trainer.neftune_hook_handle.remove() trainer.train() assert trainer.state.log_history[(-1)]["train_loss"] is not None assert trainer.state.log_history[0]["eval_loss"] is not None assert "adapter_model.safetensors" in os.listdir(tmp_dir + "/checkpoint-2") assert "adapter_config.json" in os.listdir(tmp_dir + "/checkpoint-2") assert "model.safetensors" not in os.listdir(tmp_dir + "/checkpoint-2") # Make sure forward pass works fine to check if embeddings forward is not broken. _ = trainer.model(torch.LongTensor([[1, 0, 1]]).to(device)) assert len(trainer.model.get_input_embeddings()._forward_hooks) == 0 @require_peft def test_peft_sft_trainer_tag(self): with tempfile.TemporaryDirectory() as tmp_dir: training_args = TrainingArguments( output_dir=tmp_dir, dataloader_drop_last=True, evaluation_strategy="steps", max_steps=4, eval_steps=2, save_steps=2, per_device_train_batch_size=2, gradient_checkpointing=True, ) peft_config = LoraConfig( r=16, lora_alpha=32, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM", ) trainer = SFTTrainer( model=self.model_id, args=training_args, train_dataset=self.train_dataset, eval_dataset=self.eval_dataset, peft_config=peft_config, packing=True, ) assert trainer.model.model_tags == trainer._tag_names @require_peft def test_sft_trainer_tag(self): with tempfile.TemporaryDirectory() as tmp_dir: training_args = TrainingArguments( output_dir=tmp_dir, dataloader_drop_last=True, evaluation_strategy="steps", max_steps=4, eval_steps=2, save_steps=2, per_device_train_batch_size=2, gradient_checkpointing=True, ) trainer = SFTTrainer( model=self.model_id, args=training_args, train_dataset=self.train_dataset, eval_dataset=self.eval_dataset, packing=True, ) assert trainer.model.model_tags == trainer._tag_names def test_sft_trainer_eval_packing(self): with tempfile.TemporaryDirectory() as tmp_dir: training_args = TrainingArguments( output_dir=tmp_dir, dataloader_drop_last=True, evaluation_strategy="steps", max_steps=4, eval_steps=2, save_steps=2, per_device_train_batch_size=2, gradient_checkpointing=True, ) trainer = SFTTrainer( model=self.model_id, args=training_args, train_dataset=self.dummy_chatml_dataset, eval_dataset=self.dummy_chatml_dataset, packing=True, max_seq_length=32, # make sure there is at least 1 packed sequence eval_packing=False, ) assert len(trainer.train_dataset["input_ids"]) == 1 assert len(trainer.eval_dataset["input_ids"]) != 1 trainer = SFTTrainer( model=self.model_id, args=training_args, train_dataset=self.dummy_chatml_dataset, eval_dataset=self.dummy_chatml_dataset, max_seq_length=32, # make sure there is at least 1 packed sequence packing=True, ) assert len(trainer.train_dataset["input_ids"]) == 1 assert len(trainer.eval_dataset["input_ids"]) == 1 trainer = SFTTrainer( model=self.model_id, args=training_args, train_dataset=self.dummy_chatml_dataset, eval_dataset=self.dummy_chatml_dataset, max_seq_length=32, # make sure there is at least 1 packed sequence packing=False, ) assert len(trainer.train_dataset["input_ids"]) != 1 assert len(trainer.eval_dataset["input_ids"]) != 1
trl/tests/test_sft_trainer.py/0
{ "file_path": "trl/tests/test_sft_trainer.py", "repo_id": "trl", "token_count": 19255 }
456
# Copyright 2023 DDPO-pytorch authors (Kevin Black), The HuggingFace Team, metric-space. 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 os import warnings from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import numpy as np import torch from diffusers import DDIMScheduler, StableDiffusionPipeline, UNet2DConditionModel from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import rescale_noise_cfg from ..core import randn_tensor from ..import_utils import is_peft_available from .sd_utils import convert_state_dict_to_diffusers if is_peft_available(): from peft import LoraConfig from peft.utils import get_peft_model_state_dict @dataclass class DDPOPipelineOutput: """ Output class for the diffusers pipeline to be finetuned with the DDPO trainer Args: images (`torch.Tensor`): The generated images. latents (`List[torch.Tensor]`): The latents used to generate the images. log_probs (`List[torch.Tensor]`): The log probabilities of the latents. """ images: torch.Tensor latents: torch.Tensor log_probs: torch.Tensor @dataclass class DDPOSchedulerOutput: """ Output class for the diffusers scheduler to be finetuned with the DDPO trainer Args: latents (`torch.Tensor`): Predicted sample at the previous timestep. Shape: `(batch_size, num_channels, height, width)` log_probs (`torch.Tensor`): Log probability of the above mentioned sample. Shape: `(batch_size)` """ latents: torch.Tensor log_probs: torch.Tensor class DDPOStableDiffusionPipeline: """ Main class for the diffusers pipeline to be finetuned with the DDPO trainer """ def __call__(self, *args, **kwargs) -> DDPOPipelineOutput: raise NotImplementedError def scheduler_step(self, *args, **kwargs) -> DDPOSchedulerOutput: raise NotImplementedError @property def unet(self): """ Returns the 2d U-Net model used for diffusion. """ raise NotImplementedError @property def vae(self): """ Returns the Variational Autoencoder model used from mapping images to and from the latent space """ raise NotImplementedError @property def tokenizer(self): """ Returns the tokenizer used for tokenizing text inputs """ raise NotImplementedError @property def scheduler(self): """ Returns the scheduler associated with the pipeline used for the diffusion process """ raise NotImplementedError @property def text_encoder(self): """ Returns the text encoder used for encoding text inputs """ raise NotImplementedError @property def autocast(self): """ Returns the autocast context manager """ raise NotImplementedError def set_progress_bar_config(self, *args, **kwargs): """ Sets the progress bar config for the pipeline """ raise NotImplementedError def save_pretrained(self, *args, **kwargs): """ Saves all of the model weights """ raise NotImplementedError def get_trainable_layers(self, *args, **kwargs): """ Returns the trainable parameters of the pipeline """ raise NotImplementedError def save_checkpoint(self, *args, **kwargs): """ Light wrapper around accelerate's register_save_state_pre_hook which is run before saving state """ raise NotImplementedError def load_checkpoint(self, *args, **kwargs): """ Light wrapper around accelerate's register_lad_state_pre_hook which is run before loading state """ raise NotImplementedError def _left_broadcast(input_tensor, shape): """ As opposed to the default direction of broadcasting (right to left), this function broadcasts from left to right Args: input_tensor (`torch.FloatTensor`): is the tensor to broadcast shape (`Tuple[int]`): is the shape to broadcast to """ input_ndim = input_tensor.ndim if input_ndim > len(shape): raise ValueError( "The number of dimensions of the tensor to broadcast cannot be greater than the length of the shape to broadcast to" ) return input_tensor.reshape(input_tensor.shape + (1,) * (len(shape) - input_ndim)).broadcast_to(shape) def _get_variance(self, timestep, prev_timestep): alpha_prod_t = torch.gather(self.alphas_cumprod, 0, timestep.cpu()).to(timestep.device) alpha_prod_t_prev = torch.where( prev_timestep.cpu() >= 0, self.alphas_cumprod.gather(0, prev_timestep.cpu()), self.final_alpha_cumprod, ).to(timestep.device) beta_prod_t = 1 - alpha_prod_t beta_prod_t_prev = 1 - alpha_prod_t_prev variance = (beta_prod_t_prev / beta_prod_t) * (1 - alpha_prod_t / alpha_prod_t_prev) return variance def scheduler_step( self, model_output: torch.FloatTensor, timestep: int, sample: torch.FloatTensor, eta: float = 0.0, use_clipped_model_output: bool = False, generator=None, prev_sample: Optional[torch.FloatTensor] = None, ) -> DDPOSchedulerOutput: """ Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion process from the learned model outputs (most often the predicted noise). Args: model_output (`torch.FloatTensor`): direct output from learned diffusion model. timestep (`int`): current discrete timestep in the diffusion chain. sample (`torch.FloatTensor`): current instance of sample being created by diffusion process. eta (`float`): weight of noise for added noise in diffusion step. use_clipped_model_output (`bool`): if `True`, compute "corrected" `model_output` from the clipped predicted original sample. Necessary because predicted original sample is clipped to [-1, 1] when `self.config.clip_sample` is `True`. If no clipping has happened, "corrected" `model_output` would coincide with the one provided as input and `use_clipped_model_output` will have not effect. generator: random number generator. variance_noise (`torch.FloatTensor`): instead of generating noise for the variance using `generator`, we can directly provide the noise for the variance itself. This is useful for methods such as CycleDiffusion. (https://arxiv.org/abs/2210.05559) Returns: `DDPOSchedulerOutput`: the predicted sample at the previous timestep and the log probability of the sample """ if self.num_inference_steps is None: raise ValueError( "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler" ) # See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf # Ideally, read DDIM paper in-detail understanding # Notation (<variable name> -> <name in paper> # - pred_noise_t -> e_theta(x_t, t) # - pred_original_sample -> f_theta(x_t, t) or x_0 # - std_dev_t -> sigma_t # - eta -> η # - pred_sample_direction -> "direction pointing to x_t" # - pred_prev_sample -> "x_t-1" # 1. get previous step value (=t-1) prev_timestep = timestep - self.config.num_train_timesteps // self.num_inference_steps # to prevent OOB on gather prev_timestep = torch.clamp(prev_timestep, 0, self.config.num_train_timesteps - 1) # 2. compute alphas, betas alpha_prod_t = self.alphas_cumprod.gather(0, timestep.cpu()) alpha_prod_t_prev = torch.where( prev_timestep.cpu() >= 0, self.alphas_cumprod.gather(0, prev_timestep.cpu()), self.final_alpha_cumprod, ) alpha_prod_t = _left_broadcast(alpha_prod_t, sample.shape).to(sample.device) alpha_prod_t_prev = _left_broadcast(alpha_prod_t_prev, sample.shape).to(sample.device) beta_prod_t = 1 - alpha_prod_t # 3. compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf if self.config.prediction_type == "epsilon": pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5) pred_epsilon = model_output elif self.config.prediction_type == "sample": pred_original_sample = model_output pred_epsilon = (sample - alpha_prod_t ** (0.5) * pred_original_sample) / beta_prod_t ** (0.5) elif self.config.prediction_type == "v_prediction": pred_original_sample = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output pred_epsilon = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample else: raise ValueError( f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or" " `v_prediction`" ) # 4. Clip or threshold "predicted x_0" if self.config.thresholding: pred_original_sample = self._threshold_sample(pred_original_sample) elif self.config.clip_sample: pred_original_sample = pred_original_sample.clamp( -self.config.clip_sample_range, self.config.clip_sample_range ) # 5. compute variance: "sigma_t(η)" -> see formula (16) # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1) variance = _get_variance(self, timestep, prev_timestep) std_dev_t = eta * variance ** (0.5) std_dev_t = _left_broadcast(std_dev_t, sample.shape).to(sample.device) if use_clipped_model_output: # the pred_epsilon is always re-derived from the clipped x_0 in Glide pred_epsilon = (sample - alpha_prod_t ** (0.5) * pred_original_sample) / beta_prod_t ** (0.5) # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t**2) ** (0.5) * pred_epsilon # 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf prev_sample_mean = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction if prev_sample is not None and generator is not None: raise ValueError( "Cannot pass both generator and prev_sample. Please make sure that either `generator` or" " `prev_sample` stays `None`." ) if prev_sample is None: variance_noise = randn_tensor( model_output.shape, generator=generator, device=model_output.device, dtype=model_output.dtype, ) prev_sample = prev_sample_mean + std_dev_t * variance_noise # log prob of prev_sample given prev_sample_mean and std_dev_t log_prob = ( -((prev_sample.detach() - prev_sample_mean) ** 2) / (2 * (std_dev_t**2)) - torch.log(std_dev_t) - torch.log(torch.sqrt(2 * torch.as_tensor(np.pi))) ) # mean along all but batch dimension log_prob = log_prob.mean(dim=tuple(range(1, log_prob.ndim))) return DDPOSchedulerOutput(prev_sample.type(sample.dtype), log_prob) # 1. The output type for call is different as the logprobs are now returned # 2. An extra method called `scheduler_step` is added which is used to constraint the scheduler output @torch.no_grad() def pipeline_step( self, prompt: Optional[Union[str, List[str]]] = None, height: Optional[int] = None, width: Optional[int] = None, num_inference_steps: int = 50, guidance_scale: float = 7.5, negative_prompt: Optional[Union[str, List[str]]] = None, num_images_per_prompt: Optional[int] = 1, eta: float = 0.0, generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, latents: Optional[torch.FloatTensor] = None, prompt_embeds: Optional[torch.FloatTensor] = None, negative_prompt_embeds: Optional[torch.FloatTensor] = None, output_type: Optional[str] = "pil", return_dict: bool = True, callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, callback_steps: int = 1, cross_attention_kwargs: Optional[Dict[str, Any]] = None, guidance_rescale: float = 0.0, ): r""" Function invoked when calling the pipeline for generation. Args: prompt (`str` or `List[str]`, *optional*): The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`. instead. height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor): The height in pixels of the generated image. width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor): The width in pixels of the generated image. num_inference_steps (`int`, *optional*, defaults to 50): The number of denoising steps. More denoising steps usually lead to a higher quality image at the expense of slower inference. guidance_scale (`float`, *optional*, defaults to 7.5): Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598). `guidance_scale` is defined as `w` of equation 2. of [Imagen Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`, usually at the expense of lower image quality. negative_prompt (`str` or `List[str]`, *optional*): The prompt or prompts not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`). num_images_per_prompt (`int`, *optional*, defaults to 1): The number of images to generate per prompt. eta (`float`, *optional*, defaults to 0.0): Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to [`schedulers.DDIMScheduler`], will be ignored for others. generator (`torch.Generator` or `List[torch.Generator]`, *optional*): One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation deterministic. latents (`torch.FloatTensor`, *optional*): Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image generation. Can be used to tweak the same generation with different prompts. If not provided, a latents tensor will ge generated by sampling using the supplied random `generator`. prompt_embeds (`torch.FloatTensor`, *optional*): Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, text embeddings will be generated from `prompt` input argument. negative_prompt_embeds (`torch.FloatTensor`, *optional*): Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input argument. output_type (`str`, *optional*, defaults to `"pil"`): The output format of the generate image. Choose between [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`. return_dict (`bool`, *optional*, defaults to `True`): Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a plain tuple. callback (`Callable`, *optional*): A function that will be called every `callback_steps` steps during inference. The function will be called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`. callback_steps (`int`, *optional*, defaults to 1): The frequency at which the `callback` function will be called. If not specified, the callback will be called at every step. cross_attention_kwargs (`dict`, *optional*): A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under `self.processor` in [diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py). guidance_rescale (`float`, *optional*, defaults to 0.7): Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf). Guidance rescale factor should fix overexposure when using zero terminal SNR. Examples: Returns: `DDPOPipelineOutput`: The generated image, the predicted latents used to generate the image and the associated log probabilities """ # 0. Default height and width to unet height = height or self.unet.config.sample_size * self.vae_scale_factor width = width or self.unet.config.sample_size * self.vae_scale_factor # 1. Check inputs. Raise error if not correct self.check_inputs( prompt, height, width, callback_steps, negative_prompt, prompt_embeds, negative_prompt_embeds, ) # 2. Define call parameters if prompt is not None and isinstance(prompt, str): batch_size = 1 elif prompt is not None and isinstance(prompt, list): batch_size = len(prompt) else: batch_size = prompt_embeds.shape[0] device = self._execution_device # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. do_classifier_free_guidance = guidance_scale > 1.0 # 3. Encode input prompt text_encoder_lora_scale = cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None prompt_embeds = self._encode_prompt( prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt, prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds, lora_scale=text_encoder_lora_scale, ) # 4. Prepare timesteps self.scheduler.set_timesteps(num_inference_steps, device=device) timesteps = self.scheduler.timesteps # 5. Prepare latent variables num_channels_latents = self.unet.config.in_channels latents = self.prepare_latents( batch_size * num_images_per_prompt, num_channels_latents, height, width, prompt_embeds.dtype, device, generator, latents, ) # 6. Denoising loop num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order all_latents = [latents] all_log_probs = [] with self.progress_bar(total=num_inference_steps) as progress_bar: for i, t in enumerate(timesteps): # expand the latents if we are doing classifier free guidance latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents latent_model_input = self.scheduler.scale_model_input(latent_model_input, t) # predict the noise residual noise_pred = self.unet( latent_model_input, t, encoder_hidden_states=prompt_embeds, cross_attention_kwargs=cross_attention_kwargs, return_dict=False, )[0] # perform guidance if do_classifier_free_guidance: noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) if do_classifier_free_guidance and guidance_rescale > 0.0: # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale) # compute the previous noisy sample x_t -> x_t-1 scheduler_output = scheduler_step(self.scheduler, noise_pred, t, latents, eta) latents = scheduler_output.latents log_prob = scheduler_output.log_probs all_latents.append(latents) all_log_probs.append(log_prob) # call the callback, if provided if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): progress_bar.update() if callback is not None and i % callback_steps == 0: callback(i, t, latents) if not output_type == "latent": image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0] image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype) else: image = latents has_nsfw_concept = None if has_nsfw_concept is None: do_denormalize = [True] * image.shape[0] else: do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept] image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize) # Offload last model to CPU if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None: self.final_offload_hook.offload() return DDPOPipelineOutput(image, all_latents, all_log_probs) class DefaultDDPOStableDiffusionPipeline(DDPOStableDiffusionPipeline): def __init__(self, pretrained_model_name: str, *, pretrained_model_revision: str = "main", use_lora: bool = True): self.sd_pipeline = StableDiffusionPipeline.from_pretrained( pretrained_model_name, revision=pretrained_model_revision ) self.use_lora = use_lora self.pretrained_model = pretrained_model_name self.pretrained_revision = pretrained_model_revision try: self.sd_pipeline.load_lora_weights( pretrained_model_name, weight_name="pytorch_lora_weights.safetensors", revision=pretrained_model_revision, ) self.use_lora = True except OSError: if use_lora: warnings.warn( "If you are aware that the pretrained model has no lora weights to it, ignore this message. " "Otherwise please check the if `pytorch_lora_weights.safetensors` exists in the model folder." ) self.sd_pipeline.scheduler = DDIMScheduler.from_config(self.sd_pipeline.scheduler.config) self.sd_pipeline.safety_checker = None # memory optimization self.sd_pipeline.vae.requires_grad_(False) self.sd_pipeline.text_encoder.requires_grad_(False) self.sd_pipeline.unet.requires_grad_(not self.use_lora) def __call__(self, *args, **kwargs) -> DDPOPipelineOutput: return pipeline_step(self.sd_pipeline, *args, **kwargs) def scheduler_step(self, *args, **kwargs) -> DDPOSchedulerOutput: return scheduler_step(self.sd_pipeline.scheduler, *args, **kwargs) @property def unet(self): return self.sd_pipeline.unet @property def vae(self): return self.sd_pipeline.vae @property def tokenizer(self): return self.sd_pipeline.tokenizer @property def scheduler(self): return self.sd_pipeline.scheduler @property def text_encoder(self): return self.sd_pipeline.text_encoder @property def autocast(self): return contextlib.nullcontext if self.use_lora else None def save_pretrained(self, output_dir): if self.use_lora: state_dict = convert_state_dict_to_diffusers(get_peft_model_state_dict(self.sd_pipeline.unet)) self.sd_pipeline.save_lora_weights(save_directory=output_dir, unet_lora_layers=state_dict) self.sd_pipeline.save_pretrained(output_dir) def set_progress_bar_config(self, *args, **kwargs): self.sd_pipeline.set_progress_bar_config(*args, **kwargs) def get_trainable_layers(self): if self.use_lora: lora_config = LoraConfig( r=4, lora_alpha=4, init_lora_weights="gaussian", target_modules=["to_k", "to_q", "to_v", "to_out.0"], ) self.sd_pipeline.unet.add_adapter(lora_config) # To avoid accelerate unscaling problems in FP16. for param in self.sd_pipeline.unet.parameters(): # only upcast trainable parameters (LoRA) into fp32 if param.requires_grad: param.data = param.to(torch.float32) return self.sd_pipeline.unet else: return self.sd_pipeline.unet def save_checkpoint(self, models, weights, output_dir): if len(models) != 1: raise ValueError("Given how the trainable params were set, this should be of length 1") if self.use_lora and hasattr(models[0], "peft_config") and getattr(models[0], "peft_config", None) is not None: state_dict = convert_state_dict_to_diffusers(get_peft_model_state_dict(models[0])) self.sd_pipeline.save_lora_weights(save_directory=output_dir, unet_lora_layers=state_dict) elif not self.use_lora and isinstance(models[0], UNet2DConditionModel): models[0].save_pretrained(os.path.join(output_dir, "unet")) else: raise ValueError(f"Unknown model type {type(models[0])}") def load_checkpoint(self, models, input_dir): if len(models) != 1: raise ValueError("Given how the trainable params were set, this should be of length 1") if self.use_lora: lora_state_dict, network_alphas = self.sd_pipeline.lora_state_dict( input_dir, weight_name="pytorch_lora_weights.safetensors" ) self.sd_pipeline.load_lora_into_unet(lora_state_dict, network_alphas=network_alphas, unet=models[0]) elif not self.use_lora and isinstance(models[0], UNet2DConditionModel): load_model = UNet2DConditionModel.from_pretrained(input_dir, subfolder="unet") models[0].register_to_config(**load_model.config) models[0].load_state_dict(load_model.state_dict()) del load_model else: raise ValueError(f"Unknown model type {type(models[0])}")
trl/trl/models/modeling_sd_base.py/0
{ "file_path": "trl/trl/models/modeling_sd_base.py", "repo_id": "trl", "token_count": 11407 }
457
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import inspect import warnings from dataclasses import FrozenInstanceError, replace from typing import Any, Callable, Dict, List, Optional, Tuple, Union import torch import torch.nn as nn from datasets import Dataset from transformers import DataCollator, PreTrainedModel, PreTrainedTokenizerBase, Trainer, TrainingArguments from transformers.trainer_callback import TrainerCallback from transformers.trainer_pt_utils import nested_detach from transformers.trainer_utils import EvalPrediction from ..import_utils import is_peft_available from .reward_config import RewardConfig from .utils import RewardDataCollatorWithPadding, compute_accuracy if is_peft_available(): from peft import PeftModel, get_peft_model, prepare_model_for_kbit_training class RewardTrainer(Trainer): r""" The RewardTrainer can be used to train your custom Reward Model. It is a subclass of the `transformers.Trainer` class and inherits all of its attributes and methods. It is recommended to use an `AutoModelForSequenceClassification` as the reward model. The reward model should be trained on a dataset of paired examples, where each example is a tuple of two sequences. The reward model should be trained to predict which example in the pair is more relevant to the task at hand. The reward trainer expects a very specific format for the dataset. The dataset should contain two 4 entries at least if you don't use the default `RewardDataCollatorWithPadding` data collator. The entries should be named - `input_ids_chosen` - `attention_mask_chosen` - `input_ids_rejected` - `attention_mask_rejected` Optionally, you can also pass a `margin` entry to the dataset. This entry should contain the margin used to modulate the loss of the reward model as outlined in https://ai.meta.com/research/publications/llama-2-open-foundation-and-fine-tuned-chat-models/. If you don't pass a margin, no margin will be used. """ _tag_names = ["trl", "reward-trainer"] def __init__( self, model: Optional[Union[PreTrainedModel, nn.Module]] = None, args: Optional[RewardConfig] = None, data_collator: Optional[DataCollator] = None, train_dataset: Optional[Dataset] = None, eval_dataset: Optional[Union[Dataset, Dict[str, Dataset]]] = None, tokenizer: Optional[PreTrainedTokenizerBase] = None, model_init: Optional[Callable[[], PreTrainedModel]] = 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, max_length: Optional[int] = None, peft_config: Optional[Dict] = None, ): """ Initialize RewardTrainer. Args: model (`transformers.PreTrainedModel`): The model to train, preferably an `AutoModelForSequenceClassification`. args (`RewardConfig`): The arguments to use for training. data_collator (`transformers.DataCollator`): The data collator to use for training. If None is specified, the default data collator (`RewardDataCollatorWithPadding`) 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. tokenizer (`transformers.PreTrainedTokenizerBase`): The tokenizer to use for training. This argument is required if you want to use the default data collator. model_init (`Callable[[], transformers.PreTrainedModel]`): The model initializer to use for training. If None is specified, the default model initializer will be used. compute_metrics (`Callable[[transformers.EvalPrediction], Dict]`, *optional* defaults to `compute_accuracy`): The metrics to use for evaluation. If no metrics are specified, the default metric (`compute_accuracy`) 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. max_length (`int`, defaults to `None`): The maximum length of the sequences in the batch. This argument is required if you want to use the default data collator. 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. """ if type(args) == TrainingArguments: warnings.warn( "Using `transformers.TrainingArguments` for `args` is deprecated and will be removed in a future version. Please use `RewardConfig` instead.", FutureWarning, ) if max_length is not None: warnings.warn( "The `max_length` argument is deprecated and will be removed in a future version. Please use the `RewardConfig` to set `max_length` instead.", FutureWarning, ) else: if max_length is not None and args.max_length is not None: raise ValueError( "You cannot specify both `max_length` and `args.max_length`. Please use the `RewardConfig` to set `max_length` once." ) if max_length is not None and args.max_length is None: warnings.warn( "The `max_length` argument is deprecated and will be removed in a future version. Please use the `RewardConfig` to set `max_length` instead.", FutureWarning, ) 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 not isinstance(model, PeftModel): if getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_quantized", False): _supports_gc_kwargs = "gradient_checkpointing_kwargs" in list( inspect.signature(prepare_model_for_kbit_training).parameters ) prepare_model_kwargs = {"use_gradient_checkpointing": args.gradient_checkpointing} if not _supports_gc_kwargs and args.gradient_checkpointing_kwargs is not None: warnings.warn( "You passed `gradient_checkpointing_kwargs` in the trainer's kwargs, but your peft version does not support it. " "please update to the latest version of peft to use `gradient_checkpointing_kwargs`." ) elif _supports_gc_kwargs and args.gradient_checkpointing_kwargs is not None: prepare_model_kwargs["gradient_checkpointing_kwargs"] = args.gradient_checkpointing_kwargs model = prepare_model_for_kbit_training(model, **prepare_model_kwargs) model = get_peft_model(model, peft_config) if compute_metrics is None: compute_metrics = compute_accuracy if data_collator is None: if tokenizer is None: raise ValueError( "max_length or a tokenizer must be specified when using the default RewardDataCollatorWithPadding" ) if type(args) == TrainingArguments: if max_length is None: warnings.warn( "When using RewardDataCollatorWithPadding, you should set `max_length` in RewardConfig." " It will be set to `512` by default, but you should do it yourself in the future.", UserWarning, ) max_length = 512 else: if max_length is None and args.max_length is None: warnings.warn( "When using RewardDataCollatorWithPadding, you should set `max_length` in RewardConfig." " It will be set to `512` by default, but you should do it yourself in the future.", UserWarning, ) max_length = 512 if max_length is None and args.max_length is not None: max_length = args.max_length data_collator = RewardDataCollatorWithPadding(tokenizer, max_length=max_length) if args.remove_unused_columns: try: # for bc before https://github.com/huggingface/transformers/pull/25435 args.remove_unused_columns = False except FrozenInstanceError: args = replace(args, remove_unused_columns=False) # warn users warnings.warn( "When using RewardDataCollatorWithPadding, you should set `remove_unused_columns=False` in your RewardConfig" " we have set it for you, but you should do it yourself in the future.", UserWarning, ) self.use_reward_data_collator = True else: self.use_reward_data_collator = False super().__init__( model, args, data_collator, train_dataset, eval_dataset, tokenizer, model_init, compute_metrics, callbacks, optimizers, preprocess_logits_for_metrics, ) # Add tags for models that have been loaded with the correct transformers version if hasattr(self.model, "add_model_tags"): self.model.add_model_tags(self._tag_names) def compute_loss( self, model: Union[PreTrainedModel, nn.Module], inputs: Dict[str, Union[torch.Tensor, Any]], return_outputs=False, ) -> Union[torch.Tensor, Tuple[torch.Tensor, Dict[str, torch.Tensor]]]: if not self.use_reward_data_collator: warnings.warn( "The current compute_loss is implemented for RewardDataCollatorWithPadding," " if you are using a custom data collator make sure you know what you are doing or" " implement your own compute_loss method." ) rewards_chosen = model( input_ids=inputs["input_ids_chosen"], attention_mask=inputs["attention_mask_chosen"], return_dict=True, )["logits"] rewards_rejected = model( input_ids=inputs["input_ids_rejected"], attention_mask=inputs["attention_mask_rejected"], return_dict=True, )["logits"] # calculate loss, optionally modulate with margin if "margin" in inputs: loss = -nn.functional.logsigmoid(rewards_chosen - rewards_rejected - inputs["margin"]).mean() else: loss = -nn.functional.logsigmoid(rewards_chosen - rewards_rejected).mean() if return_outputs: return loss, { "rewards_chosen": rewards_chosen, "rewards_rejected": rewards_rejected, } return loss 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, ) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor]]: inputs = self._prepare_inputs(inputs) if ignore_keys is None: if hasattr(self.model, "config"): ignore_keys = getattr(self.model.config, "keys_to_ignore_at_inference", []) else: ignore_keys = [] with torch.no_grad(): loss, logits_dict = self.compute_loss(model, inputs, return_outputs=True) if prediction_loss_only: return (loss, None, None) loss = loss.detach() logits = tuple(v for k, v in logits_dict.items() if k not in ignore_keys) logits = nested_detach(logits) # Stack accepted against rejected, mean over logits # and softmax to get preferences between accepted and rejected to sum to 1 logits = torch.stack(logits).mean(dim=2).softmax(dim=0).T labels = torch.zeros(logits.shape[0]) labels = self._prepare_inputs(labels) return loss, logits, labels
trl/trl/trainer/reward_trainer.py/0
{ "file_path": "trl/trl/trainer/reward_trainer.py", "repo_id": "trl", "token_count": 5938 }
458
# Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import time import torch import transformers from measures_util import end_measure, log_measures, start_measure from transformers import AutoConfig, AutoModelForCausalLM, AutoModelForSeq2SeqLM, AutoTokenizer from accelerate.utils import compute_module_sizes DEFAULT_MODELS = { "gpt-j-6b": {"is_causal": True, "model": "sgugger/sharded-gpt-j-6B", "tokenizer": "EleutherAI/gpt-j-6B"}, "gpt-neox": {"is_causal": True, "model": "EleutherAI/gpt-neox-20b"}, "opt": {"is_causal": True, "model": "facebook/opt-30b"}, "T0pp": {"is_causal": False, "model": "bigscience/T0pp", "model_revision": "sharded"}, } PROMPTS = [ "Hello, my name is", "Are unicorns real? Unicorns are", "For the first time in several years,", "My name is Julien and I am", "The goal of life is", "Whenever I'm sad, I like to", ] def parse_args(): parser = argparse.ArgumentParser(description="Run and time generations on a big model using Accelerate.") parser.add_argument("model_name", type=str, default=None, help="The name of the model to try.") parser.add_argument( "--tokenizer_name", type=str, default=None, help="The name of the tokenizer (if different from the model." ) parser.add_argument("--is_causal", type=bool, default=None, help="Whether or not the model is causal.") parser.add_argument( "--model_revision", type=str, default=None, help="The revision to use for the model checkpoint." ) parser.add_argument("--torch_dtype", type=str, default=None, help="The dtype for the model.") parser.add_argument("--disk_offload", action="store_true") args = parser.parse_args() # Sanitize args if args.model_name in DEFAULT_MODELS: defaults = DEFAULT_MODELS[args.model_name] args.model_name = defaults["model"] if args.tokenizer_name is None: args.tokenizer_name = defaults.get("tokenizer", args.model_name) if args.is_causal is None: args.is_causal = defaults["is_causal"] if args.model_revision is None: args.model_revision = defaults.get("model_revision", "main") if args.is_causal is None: raise ValueError("Could not infer the default for `--is_causal`, pass either True or False for it.") if args.tokenizer_name is None: args.tokenizer_name = args.model_name if args.model_revision is None: args.model_revision = "main" return args def main(): transformers.utils.logging.set_verbosity_error() args = parse_args() if args.torch_dtype is None: config = AutoConfig.from_pretrained(args.model_name) torch_dtype = getattr(config, "torch_dtype", torch.float32) else: torch_dtype = getattr(torch, args.torch_dtype) model_cls = AutoModelForCausalLM if args.is_causal else AutoModelForSeq2SeqLM kwargs = { "torch_dtype": torch_dtype, "revision": args.model_revision, } if args.disk_offload: kwargs["offload_folder"] = "tmp_offload" kwargs["offload_state_dict"] = True start_measures = start_measure() model = model_cls.from_pretrained(args.model_name, device_map="auto", **kwargs) end_measures = end_measure(start_measures) log_measures(end_measures, "Model loading") module_sizes = compute_module_sizes(model) device_size = {v: 0 for v in model.hf_device_map.values()} for module, device in model.hf_device_map.items(): device_size[device] += module_sizes[module] message = "\n".join([f"- {device}: {size // 2**20}MiB" for device, size in device_size.items()]) print(f"\nTheoretical use:\n{message}") tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name) start_measures = start_measure() generation_times = [] gen_tokens = [] texts_outs = [] for prompt in PROMPTS: inputs = tokenizer(prompt, return_tensors="pt").to(0) tokens = inputs["input_ids"][0].tolist() before_generate = time.time() outputs = model.generate(inputs["input_ids"]) after_generate = time.time() outputs = outputs[0].tolist() num_gen_tokens = len(outputs) if outputs[: len(tokens)] != tokens else len(outputs) - len(tokens) generation_time = after_generate - before_generate text_out = tokenizer.decode(outputs, skip_special_tokens=True) texts_outs.append(text_out) generation_times.append(generation_time) gen_tokens.append(num_gen_tokens) print(f"Prompt: {prompt}\nGeneration {text_out}\nIn {generation_time:.2f}s for {num_gen_tokens} tokens\n") end_measures = end_measure(start_measures) log_measures(end_measures, "Model generation") generation_times_per_token = [gen / tok for gen, tok in zip(generation_times, gen_tokens)] avg_gen = sum(generation_times_per_token) / len(generation_times) print(f"Average time of generation per token: {avg_gen:.2f}s") print(f"First generation (avg time per token): {generation_times_per_token[0]:.2f}s") avg_gen = sum(generation_times_per_token[1:]) / (len(generation_times_per_token) - 1) print(f"Average time of generation per token (excluding the first): {avg_gen:.2f}s") if __name__ == "__main__": main()
accelerate/benchmarks/big_model_inference.py/0
{ "file_path": "accelerate/benchmarks/big_model_inference.py", "repo_id": "accelerate", "token_count": 2241 }
0
<!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Handling big models for inference When loading a pre-trained model in PyTorch, the usual workflow looks like this: ```py import torch my_model = ModelClass(...) state_dict = torch.load(checkpoint_file) my_model.load_state_dict(state_dict) ``` In plain English, those steps are: 1. Create the model with randomly initialized weights 2. Load the model weights (in a dictionary usually called a state dict) from the disk 3. Load those weights inside the model While this works very well for regularly sized models, this workflow has some clear limitations when we deal with a huge model: in step 1, we load a full version of the model in RAM, and spend some time randomly initializing the weights (which will be discarded in step 3). In step 2, we load another full version of the model in RAM, with the pre-trained weights. If you're loading a model with 6 billion parameters, this means you will need 24GB of RAM for each copy of the model, so 48GB in total (half of it to load the model in FP16). <Tip warning={true}> This API is quite new and still in its experimental stage. While we strive to provide a stable API, it's possible some small parts of the public API will change in the future. </Tip> ## How the Process Works: A Quick Overview <Youtube id="MWCSGj9jEAo" /> ## How the Process Works: Working with Code ### Instantiating an empty model The first tool 🤗 Accelerate introduces to help with big models is a context manager [`init_empty_weights`] that helps you initialize a model without using any RAM so that step 1 can be done on models of any size. Here is how it works: ```py from accelerate import init_empty_weights with init_empty_weights(): my_model = ModelClass(...) ``` For instance: ```py with init_empty_weights(): model = nn.Sequential(*[nn.Linear(10000, 10000) for _ in range(1000)]) ``` initializes an empty model with a bit more than 100B parameters. Behind the scenes, this relies on the meta device introduced in PyTorch 1.9. During the initialization under the context manager, each time a parameter is created, it is instantly moved to that device. <Tip warning={true}> You can't move a model initialized like this on CPU or another device directly, since it doesn't have any data. It's also very likely that a forward pass with that empty model will fail, as not all operations are supported on the meta device. </Tip> ### Sharded checkpoints It's possible your model is so big that even a single copy won't fit in RAM. That doesn't mean it can't be loaded: if you have one or several GPUs, this is more memory available to store your model. In this case, it's better if your checkpoint is split into several smaller files that we call checkpoint shards. 🤗 Accelerate will handle sharded checkpoints as long as you follow the following format: your checkpoint should be in a folder, with several files containing the partial state dicts, and there should be an index in the JSON format that contains a dictionary mapping parameter names to the file containing their weights. You can easily shard your model with [`~Accelerator.save_model`]. For instance, we could have a folder containing: ```bash first_state_dict.bin index.json second_state_dict.bin ``` with index.json being the following file: ``` { "linear1.weight": "first_state_dict.bin", "linear1.bias": "first_state_dict.bin", "linear2.weight": "second_state_dict.bin", "linear2.bias": "second_state_dict.bin" } ``` and `first_state_dict.bin` containing the weights for `"linear1.weight"` and `"linear1.bias"`, `second_state_dict.bin` the ones for `"linear2.weight"` and `"linear2.bias"` ### Loading weights The second tool 🤗 Accelerate introduces is a function [`load_checkpoint_and_dispatch`], that will allow you to load a checkpoint inside your empty model. This supports full checkpoints (a single file containing the whole state dict) as well as sharded checkpoints. It will also automatically dispatch those weights across the devices you have available (GPUs, CPU RAM), so if you are loading a sharded checkpoint, the maximum RAM usage will be the size of the biggest shard. If you want to use big model inference with 🤗 Transformers models, check out this [documentation](https://huggingface.co/docs/transformers/main/en/main_classes/model#large-model-loading). Here is how we can use this to load the [GPT2-1.5B](https://huggingface.co/marcsun13/gpt2-xl-linear-sharded) model. Let's download the sharded version of this model. ```bash pip install huggingface_hub ``` ```py from huggingface_hub import snapshot_download checkpoint = "marcsun13/gpt2-xl-linear-sharded" weights_location = snapshot_download(repo_id=checkpoint) ``` In order to initialize the model, we will use the library minGPT. ```bash git clone https://github.com/karpathy/minGPT.git pip install minGPT/ ``` ```py from accelerate import init_empty_weights from mingpt.model import GPT model_config = GPT.get_default_config() model_config.model_type = 'gpt2-xl' model_config.vocab_size = 50257 model_config.block_size = 1024 with init_empty_weights(): model = GPT(model_config) ``` Then, load the checkpoint we just downloaded with: ```py from accelerate import load_checkpoint_and_dispatch model = load_checkpoint_and_dispatch( model, checkpoint=weights_location, device_map="auto", no_split_module_classes=['Block'] ) ``` By passing `device_map="auto"`, we tell 🤗 Accelerate to determine automatically where to put each layer of the model depending on the available resources: - first, we use the maximum space available on the GPU(s) - if we still need space, we store the remaining weights on the CPU - if there is not enough RAM, we store the remaining weights on the hard drive as memory-mapped tensors #### `no_split_module_classes` This parameter will indicate that some of the modules with the name `"Block"` should not be split across different devices. You should set here all blocks that include a residual connection of some kind. #### The `device_map` You can see the `device_map` that 🤗 Accelerate picked by accessing the `hf_device_map` attribute of your model: ```py model.hf_device_map ``` ```python out {'transformer.wte': 0, 'transformer.wpe': 0, 'transformer.drop': 0, 'transformer.h.0': 0, ... 'transformer.h.21': 0, 'transformer.h.22': 1, 'transformer.h.23': 1, 'transformer.h.24': 1, ... 'transformer.h.47': 1, 'transformer.ln_f': 1, 'lm_head': 1} ``` It's fully possible to create your own device map for the layers to use as well, specifying the GPU device to use (a number), `"cpu"`, or `"disk"` and pass this in: ```python device_map = { "transformer.wte": "cpu", "transformer.wpe": 0, "transformer.drop": "cpu", "transformer.h.0": "disk" } model = load_checkpoint_and_dispatch( model, checkpoint=weights_location, device_map=device_map ) ``` ### Run the model Now that we have done this, our model lies across several devices, and maybe the hard drive. But it can still be used as a regular PyTorch model: ```py from mingpt.bpe import BPETokenizer tokenizer = BPETokenizer() inputs = tokenizer("Hello, my name is").to(0) outputs = model.generate(x1, max_new_tokens=10, do_sample=False)[0] tokenizer.decode(outputs.cpu().squeeze()) ``` Behind the scenes, 🤗 Accelerate added hooks to the model, so that: - at each layer, the inputs are put on the right device (so even if your model is spread across several GPUs, it works) - for the weights offloaded on the CPU, they are put on a GPU just before the forward pass and cleaned up just after - for the weights offloaded on the hard drive, they are loaded in RAM then put on a GPU just before the forward pass and cleaned up just after This way, your model can run for inference even if it doesn't fit on one of the GPUs or the CPU RAM! <Tip warning={true}> This only supports the inference of your model, not training. Most of the computation happens behind `torch.no_grad()` context managers to avoid spending some GPU memory with intermediate activations. </Tip> ### Designing a device map You can let 🤗 Accelerate handle the device map computation by setting `device_map` to one of the supported options (`"auto"`, `"balanced"`, `"balanced_low_0"`, `"sequential"`) or create one yourself if you want more control over where each layer should go. <Tip> You can derive all sizes of the model (and thus compute a `device_map`) on a model that is on the meta device. </Tip> All the options will produce the same result when you don't have enough GPU memory to accommodate the whole model (which is to fit everything that can on the GPU, then offload weights on the CPU or even on the disk if there is not enough RAM). When you have more GPU memory available than the model size, here is the difference between each option: - `"auto"` and `"balanced"` evenly split the model on all available GPUs, making it possible for you to use a batch size greater than 1. - `"balanced_low_0"` evenly splits the model on all GPUs except the first one, and only puts on GPU 0 what does not fit on the others. This option is great when you need to use GPU 0 for some processing of the outputs, like when using the `generate` function for Transformers models - `"sequential"` will fit what it can on GPU 0, then move on GPU 1 and so forth (so won't use the last GPUs if it doesn't need to). <Tip> The options `"auto"` and `"balanced"` produce the same results for now, but the behavior of `"auto"` might change in the future if we find a strategy that makes more sense, while `"balanced"` will stay stable. </Tip> First note that you can limit the memory used on each GPU by using the `max_memory` argument (available in [`infer_auto_device_map`] and in all functions using it). When setting `max_memory`, you should pass along a dictionary containing the GPU identifiers (for instance `0`, `1` etc.) and the `"cpu"` key for the maximum RAM you want to use for CPU offload. The values can either be an integer (in bytes) or a string representing a number with its unit, such as `"10GiB"` or `"10GB"`. Here is an example where we don't want to use more than 10GiB on each of the two GPUs and no more than 30GiB of CPU RAM for the model weights: ```python from accelerate import infer_auto_device_map device_map = infer_auto_device_map(my_model, max_memory={0: "10GiB", 1: "10GiB", "cpu": "30GiB"}) ``` <Tip warning={true}> When a first allocation happens in PyTorch, it loads CUDA kernels which take about 1-2GB of memory depending on the GPU. Therefore you always have less usable memory than the actual size of the GPU. To see how much memory is actually used do `torch.ones(1).cuda()` and look at the memory usage. Therefore when you create memory maps with `max_memory` make sure to adjust the available memory accordingly to avoid out-of-memory errors. </Tip> Additionally, if you do some additional operations with your outputs without placing them back on the CPU (for instance inside the `generate` method of Transformers) and if you placed your inputs on a GPU, that GPU will consume more memory than the others (Accelerate always place the output back to the device of the input). Therefore if you would like to optimize the maximum batch size and you have many GPUs, give the first GPU less memory. For example, with BLOOM-176B on 8x80 A100 setup, the close-to-ideal map is: ```python max_memory = {0: "30GIB", 1: "46GIB", 2: "46GIB", 3: "46GIB", 4: "46GIB", 5: "46GIB", 6: "46GIB", 7: "46GIB"} ``` as you can see we gave the remaining 7 GPUs ~50% more memory than GPU 0. If you opt to fully design the `device_map` yourself, it should be a dictionary with keys being module names of your model and values being a valid device identifier (for instance an integer for the GPUs) or `"cpu"` for CPU offload, `"disk"` for disk offload. The keys need to cover the whole model, you can then define your device map as you wish: for instance, if your model has two blocks (let's say `block1` and `block2`) which each contain three linear layers (let's say `linear1`, `linear2` and `linear3`), a valid device map can be: ```python device_map = {"block1": 0, "block2": 1} ``` another one that is valid could be: ```python device_map = {"block1": 0, "block2.linear1": 0, "block2.linear2": 1, "block2.linear3": 1} ``` On the other hand, this one is not valid as it does not cover every parameter of the model: ```python device_map = {"block1": 0, "block2.linear1": 1, "block2.linear2": 1} ``` <Tip> To be the most efficient, make sure your device map puts the parameters on the GPUs in a sequential manner (e.g. don't put one of the first weights on GPU 0, then weights on GPU 1 and the last weight back to GPU 0) to avoid making many transfers of data between the GPUs. </Tip> ## CPU offload only If you want to offload your model on CPU, you can use [`cpu_offload`]. As a result, all parameters of the model will be offloaded and only one copy of the state dict of the model will be kept. During the forward pass, parameters will be extracted from that state dict and put on the execution device and passed as they are needed, then offloaded again. ```python cpu_offload(model, execution_device) ``` You can also use [`cpu_offload_with_hook`]. This function will offloads a model on the CPU and puts it back to an execution device when executed. The difference with [`cpu_offload`] is that the model stays on the execution device after the forward and is only offloaded again when the `offload` method of the returned `hook` is called. Furthermore, [`cpu_offload_with_hook`] is more performant but less memory saving. It is useful for pipelines running a model in a loop: ```python model_1, hook_1 = cpu_offload_with_hook(model_1, execution_device) model_2, hook_2 = cpu_offload_with_hook(model_2, execution_device, prev_module_hook=hook_1) model_3, hook_3 = cpu_offload_with_hook(model_3, execution_device, prev_module_hook=hook_2) hid_1 = model_1(input) for i in range(50): # model1 is offloaded on the CPU at the first iteration, model 2 stays on the GPU for this whole loop. hid_2 = model_2(hid_1) # model2 is offloaded to the CPU just before this forward. hid_3 = model_3(hid_3) # For model3, you need to manually call the hook offload method. hook_3.offload() ``` ## Disk offload only To perform disk offload, you can use [`disk_offload`]. As a result, all parameters of the model will be offloaded as memory-mapped array in a given folder. During the forward pass, parameters will be accessed from that folder and put on the execution device passed as they are needed, then offloaded again. ```python disk_offload(model, offload_dir, execution_device) ``` ## Limits and further development We are aware of the current limitations in the API: - [`infer_auto_device_map`] (or `device_map="auto"` in [`load_checkpoint_and_dispatch`]) tries to maximize GPU and CPU RAM it sees available when you execute it. While PyTorch is very good at managing GPU RAM efficiently (and giving it back when not needed), it's not entirely true with Python and CPU RAM. Therefore, an automatically computed device map might be too intense on the CPU. Move a few modules to the disk device if you get crashes due to a lack of RAM. - [`infer_auto_device_map`] (or `device_map="auto"` in [`load_checkpoint_and_dispatch`]) attributes devices sequentially (to avoid moving things back and forth) so if your first layer is bigger than the size of the GPU you have, it will end up with everything on the CPU/Disk. - [`load_checkpoint_and_dispatch`] and [`load_checkpoint_in_model`] do not perform any check on the correctness of your state dict compared to your model at the moment (this will be fixed in a future version), so you may get some weird errors if trying to load a checkpoint with mismatched or missing keys. - The model parallelism used when your model is split on several GPUs is naive and not optimized, meaning that only one GPU works at a given time and the other sits idle. - When weights are offloaded on the CPU/hard drive, there is no pre-fetching (yet, we will work on this for future versions) which means the weights are put on the GPU when they are needed and not before. - Hard-drive offloading might be very slow if the hardware you run on does not have fast communication between disk and CPU (like NVMes).
accelerate/docs/source/concept_guides/big_model_inference.md/0
{ "file_path": "accelerate/docs/source/concept_guides/big_model_inference.md", "repo_id": "accelerate", "token_count": 4832 }
1
<!--Copyright 2022 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be rendered properly in your Markdown viewer. --> # Intel® Extension for PyTorch [IPEX](https://github.com/intel/intel-extension-for-pytorch) is optimized for CPUs with AVX-512 or above, and functionally works for CPUs with only AVX2. So, it is expected to bring performance benefit for Intel CPU generations with AVX-512 or above while CPUs with only AVX2 (e.g., AMD CPUs or older Intel CPUs) might result in a better performance under IPEX, but not guaranteed. IPEX provides performance optimizations for CPU training with both Float32 and BFloat16. The usage of BFloat16 is the main focus of the following sections. Low precision data type BFloat16 has been natively supported on the 3rd Generation Xeon® Scalable Processors (aka Cooper Lake) with AVX512 instruction set and will be supported on the next generation of Intel® Xeon® Scalable Processors with Intel® Advanced Matrix Extensions (Intel® AMX) instruction set with further boosted performance. The Auto Mixed Precision for CPU backend has been enabled since PyTorch-1.10. At the same time, the support of Auto Mixed Precision with BFloat16 for CPU and BFloat16 optimization of operators has been massively enabled in Intel® Extension for PyTorch, and partially upstreamed to PyTorch master branch. Users can get better performance and user experience with IPEX Auto Mixed Precision. ## IPEX installation: IPEX release is following PyTorch, to install via pip: | PyTorch Version | IPEX version | | :---------------: | :----------: | | 2.0 | 2.0.0 | | 1.13 | 1.13.0 | | 1.12 | 1.12.300 | | 1.11 | 1.11.200 | | 1.10 | 1.10.100 | ``` pip install intel_extension_for_pytorch==<version_name> -f https://developer.intel.com/ipex-whl-stable-cpu ``` Check more approaches for [IPEX installation](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/installation.html). ## How It Works For Training optimization in CPU 🤗 Accelerate has integrated [IPEX](https://github.com/intel/intel-extension-for-pytorch), all you need to do is enabling it through the config. **Scenario 1**: Acceleration of No distributed CPU training Run <u>accelerate config</u> on your machine: ```bash $ accelerate config ----------------------------------------------------------------------------------------------------------------------------------------------------------- In which compute environment are you running? This machine ----------------------------------------------------------------------------------------------------------------------------------------------------------- Which type of machine are you using? No distributed training Do you want to run your training on CPU only (even if a GPU / Apple Silicon device is available)? [yes/NO]:yes Do you want to use Intel PyTorch Extension (IPEX) to speed up training on CPU? [yes/NO]:yes Do you wish to optimize your script with torch dynamo?[yes/NO]:NO Do you want to use DeepSpeed? [yes/NO]: NO ----------------------------------------------------------------------------------------------------------------------------------------------------------- Do you wish to use FP16 or BF16 (mixed precision)? bf16 ``` This will generate a config file that will be used automatically to properly set the default options when doing ```bash accelerate launch my_script.py --args_to_my_script ``` For instance, here is how you would run the NLP example `examples/nlp_example.py` (from the root of the repo) with IPEX enabled. default_config.yaml that is generated after `accelerate config` ```bash compute_environment: LOCAL_MACHINE distributed_type: 'NO' downcast_bf16: 'no' ipex_config: ipex: true machine_rank: 0 main_training_function: main mixed_precision: bf16 num_machines: 1 num_processes: 1 rdzv_backend: static same_network: true tpu_env: [] tpu_use_cluster: false tpu_use_sudo: false use_cpu: true ``` ```bash accelerate launch examples/nlp_example.py ``` **Scenario 2**: Acceleration of distributed CPU training we use Intel oneCCL for communication, combined with Intel® MPI library to deliver flexible, efficient, scalable cluster messaging on Intel® architecture. you could refer the [here](https://huggingface.co/docs/transformers/perf_train_cpu_many) for the installation guide Run <u>accelerate config</u> on your machine(node0): ```bash $ accelerate config ----------------------------------------------------------------------------------------------------------------------------------------------------------- In which compute environment are you running? This machine ----------------------------------------------------------------------------------------------------------------------------------------------------------- Which type of machine are you using? multi-CPU How many different machines will you use (use more than 1 for multi-node training)? [1]: 4 ----------------------------------------------------------------------------------------------------------------------------------------------------------- What is the rank of this machine? 0 What is the IP address of the machine that will host the main process? 36.112.23.24 What is the port you will use to communicate with the main process? 29500 Are all the machines on the same local network? Answer `no` if nodes are on the cloud and/or on different network hosts [YES/no]: yes Do you want to use Intel PyTorch Extension (IPEX) to speed up training on CPU? [yes/NO]:yes Do you want accelerate to launch mpirun? [yes/NO]: yes Please enter the path to the hostfile to use with mpirun [~/hostfile]: ~/hostfile Enter the number of oneCCL worker threads [1]: 1 Do you wish to optimize your script with torch dynamo?[yes/NO]:NO How many processes should be used for distributed training? [1]:16 ----------------------------------------------------------------------------------------------------------------------------------------------------------- Do you wish to use FP16 or BF16 (mixed precision)? bf16 ``` For instance, here is how you would run the NLP example `examples/nlp_example.py` (from the root of the repo) with IPEX enabled for distributed CPU training. default_config.yaml that is generated after `accelerate config` ```bash compute_environment: LOCAL_MACHINE distributed_type: MULTI_CPU downcast_bf16: 'no' ipex_config: ipex: true machine_rank: 0 main_process_ip: 36.112.23.24 main_process_port: 29500 main_training_function: main mixed_precision: bf16 mpirun_config: mpirun_ccl: '1' mpirun_hostfile: /home/user/hostfile num_machines: 4 num_processes: 16 rdzv_backend: static same_network: true tpu_env: [] tpu_use_cluster: false tpu_use_sudo: false use_cpu: true ``` Set following env and using intel MPI to launch the training In node0, you need to create a configuration file which contains the IP addresses of each node (for example hostfile) and pass that configuration file path as an argument. If you selected to have Accelerate launch `mpirun`, ensure that the location of your hostfile matches the path in the config. ```bash $ cat hostfile xxx.xxx.xxx.xxx #node0 ip xxx.xxx.xxx.xxx #node1 ip xxx.xxx.xxx.xxx #node2 ip xxx.xxx.xxx.xxx #node3 ip ``` When Accelerate is launching `mpirun`, source the oneCCL bindings setvars.sh to get your Intel MPI environment, and then run your script using `accelerate launch`. Note that the python script and environment needs to exist on all of the machines being used for multi-CPU training. ```bash oneccl_bindings_for_pytorch_path=$(python -c "from oneccl_bindings_for_pytorch import cwd; print(cwd)") source $oneccl_bindings_for_pytorch_path/env/setvars.sh accelerate launch examples/nlp_example.py ``` Otherwise, if you selected not to have Accelerate launch `mpirun`, run the following command in node0 and **16DDP** will be enabled in node0,node1,node2,node3 with BF16 mixed precision. When using this method, the python script, python environment, and accelerate config file need to be present on all of the machines used for multi-CPU training. ```bash oneccl_bindings_for_pytorch_path=$(python -c "from oneccl_bindings_for_pytorch import cwd; print(cwd)") source $oneccl_bindings_for_pytorch_path/env/setvars.sh export CCL_WORKER_COUNT=1 export MASTER_ADDR=xxx.xxx.xxx.xxx #node0 ip export CCL_ATL_TRANSPORT=ofi mpirun -f hostfile -n 16 -ppn 4 accelerate launch examples/nlp_example.py ``` ## Related Resources - [Project's github](https://github.com/intel/intel-extension-for-pytorch) - [API docs](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/api_doc.html) - [Tuning guide](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/performance_tuning/tuning_guide.html) - [Blogs & Publications](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/blogs_publications.html)
accelerate/docs/source/usage_guides/ipex.md/0
{ "file_path": "accelerate/docs/source/usage_guides/ipex.md", "repo_id": "accelerate", "token_count": 2636 }
2
# Distributed inference examples with PiPPy This repo contains a variety of tutorials for using the [PiPPy](https://github.com/PyTorch/PiPPy) pipeline parallelism library with accelerate. You will find examples covering: 1. How to trace the model using `accelerate.prepare_pippy` 2. How to specify inputs based on what the model expects (when to use `kwargs`, `args`, and such) 3. How to gather the results at the end. ## Installation This requires the `main` branch of accelerate (or a version at least 0.27.0), `pippy` version of 0.2.0 or greater, and at least python 3.9. Please install using `pip install .` to pull from the `setup.py` in this repo, or run manually: ```bash pip install 'accelerate>=0.27.0' 'torchpippy>=0.2.0' ``` ## Running code You can either use `torchrun` or the recommended way of `accelerate launch` (without needing to run `accelerate config`) on each script: ```bash accelerate launch bert.py ``` Or: ```bash accelerate launch --num_processes {NUM_GPUS} bert.py ``` Or: ```bash torchrun --nproc-per-node {NUM_GPUS} bert.py ``` ## General speedups One can expect that PiPPy will outperform native model parallism by a multiplicative factor since all GPUs are running at all times with inputs, rather than one input being passed through a GPU at a time waiting for the prior to finish. Below are some benchmarks we have found when using the accelerate-pippy integration for a few models when running on 2x4090's: ### Bert | | Accelerate/Sequential | PiPPy + Accelerate | |---|---|---| | First batch | 0.2137s | 0.3119s | | Average of 5 batches | 0.0099s | **0.0062s** | ### GPT2 | | Accelerate/Sequential | PiPPy + Accelerate | |---|---|---| | First batch | 0.1959s | 0.4189s | | Average of 5 batches | 0.0205s | **0.0126s** | ### T5 | | Accelerate/Sequential | PiPPy + Accelerate | |---|---|---| | First batch | 0.2789s | 0.3809s | | Average of 5 batches | 0.0198s | **0.0166s** |
accelerate/examples/inference/README.md/0
{ "file_path": "accelerate/examples/inference/README.md", "repo_id": "accelerate", "token_count": 646 }
3
[tool.ruff] line-length = 119 target-version = "py38" [tool.ruff.lint] preview = true ignore-init-module-imports = true extend-select = [ "B009", # static getattr "B010", # static setattr "CPY", # Copyright "E", # PEP8 errors "F", # PEP8 formatting "I", # Import sorting "TID251", # Banned API "UP", # Pyupgrade "W", # PEP8 warnings ] ignore = [ "E501", # Line length (handled by ruff-format) "E741", # Ambiguous variable name "W605", # Invalid escape sequence "UP007", # X | Y type annotations ] [tool.ruff.lint.per-file-ignores] "__init__.py" = [ "F401", # Ignore seemingly unused imports (they're meant for re-export) ] "manim_animations/*" = ["ALL"] [tool.ruff.lint.isort] lines-after-imports = 2 known-first-party = ["accelerate"] [tool.ruff.format] exclude = [ "manim_animations/*" ] [tool.ruff.lint.flake8-tidy-imports.banned-api] "os.getenv".msg = "Use os.environ instead" "os.putenv".msg = "Use os.environ instead" "os.unsetenv".msg = "Use os.environ instead"
accelerate/pyproject.toml/0
{ "file_path": "accelerate/pyproject.toml", "repo_id": "accelerate", "token_count": 427 }
4
#!/usr/bin/env python # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import platform import numpy as np import psutil import torch from accelerate import __version__ as version from accelerate.commands.config import default_config_file, load_config_from_file from ..utils import is_mlu_available, is_npu_available, is_xpu_available def env_command_parser(subparsers=None): if subparsers is not None: parser = subparsers.add_parser("env") else: parser = argparse.ArgumentParser("Accelerate env command") parser.add_argument( "--config_file", default=None, help="The config file to use for the default values in the launching script." ) if subparsers is not None: parser.set_defaults(func=env_command) return parser def env_command(args): pt_version = torch.__version__ pt_cuda_available = torch.cuda.is_available() pt_xpu_available = is_xpu_available() pt_mlu_available = is_mlu_available() pt_npu_available = is_npu_available() accelerate_config = "Not found" # Get the default from the config file. if args.config_file is not None or os.path.isfile(default_config_file): accelerate_config = load_config_from_file(args.config_file).to_dict() info = { "`Accelerate` version": version, "Platform": platform.platform(), "Python version": platform.python_version(), "Numpy version": np.__version__, "PyTorch version (GPU?)": f"{pt_version} ({pt_cuda_available})", "PyTorch XPU available": str(pt_xpu_available), "PyTorch NPU available": str(pt_npu_available), "PyTorch MLU available": str(pt_mlu_available), "System RAM": f"{psutil.virtual_memory().total / 1024 ** 3:.2f} GB", } if pt_cuda_available: info["GPU type"] = torch.cuda.get_device_name() print("\nCopy-and-paste the text below in your GitHub issue\n") print("\n".join([f"- {prop}: {val}" for prop, val in info.items()])) print("- `Accelerate` default config:" if args.config_file is None else "- `Accelerate` config passed:") accelerate_config_str = ( "\n".join([f"\t- {prop}: {val}" for prop, val in accelerate_config.items()]) if isinstance(accelerate_config, dict) else f"\t{accelerate_config}" ) print(accelerate_config_str) info["`Accelerate` configs"] = accelerate_config return info def main() -> int: parser = env_command_parser() args = parser.parse_args() env_command(args) return 0 if __name__ == "__main__": raise SystemExit(main())
accelerate/src/accelerate/commands/env.py/0
{ "file_path": "accelerate/src/accelerate/commands/env.py", "repo_id": "accelerate", "token_count": 1140 }
5
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch from accelerate import Accelerator, DistributedType class LocalSGD: """ A helper class to support local SGD on top of Accelerator. It simply runs a given number of updates independently on each device, and averages model weights every K synchronization step. It should be used only in the multi-GPU (or multi-CPU) setup without extensions such as DeepSpeed. In particular, this is a simple implementation that cannot support scenarios such as model parallelism. Although we are not aware of the true origins of this simple approach, the idea of local SGD is quite old and goes back to at least: Zhang, J., De Sa, C., Mitliagkas, I., & Ré, C. (2016). [Parallel SGD: When does averaging help?. arXiv preprint arXiv:1606.07365.](https://arxiv.org/abs/1606.07365) We credit the term Local SGD to the following paper (but there might be earlier references we are not aware of). Stich, Sebastian Urban. ["Local SGD Converges Fast and Communicates Little." ICLR 2019-International Conference on Learning Representations. No. CONF. 2019.](https://arxiv.org/abs/1805.09767) """ def __enter__(self): if self.enabled: self.model_sync_obj = self.model.no_sync() self.model_sync_obj.__enter__() return self def __exit__(self, type, value, tb): if self.enabled: # Average all models on exit self._sync_and_avg_model_params() self.model_sync_obj.__exit__(type, value, tb) def __init__(self, accelerator: Accelerator, model: torch.nn.Module, local_sgd_steps: int, enabled: bool = True): """ Constructor. Args: model (`torch.nn.Module): The model whose parameters we need to average. accelerator (`Accelerator`): Accelerator object. local_sgd_steps (`int`): A number of local SGD steps (before model parameters are synchronized). enabled (`bool): Local SGD is disabled if this parameter set to `False`. """ if accelerator.distributed_type not in [ DistributedType.NO, DistributedType.MULTI_CPU, DistributedType.MULTI_GPU, DistributedType.MULTI_MLU, DistributedType.MULTI_NPU, ]: raise NotImplementedError("LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)") self.enabled = enabled and accelerator.distributed_type != DistributedType.NO self.num_steps = 0 if self.enabled: self.accelerator = accelerator self.model = model self.local_sgd_steps = local_sgd_steps def step(self): """ This function makes a "step" and synchronizes model parameters if necessary. """ self.num_steps += 1 if not self.enabled: return if self.num_steps % self.local_sgd_steps == 0: self._sync_and_avg_model_params() def _sync_and_avg_model_params(self): """ Synchronize + Average model parameters across all GPUs """ self.accelerator.wait_for_everyone() with self.accelerator.autocast(): for param in self.model.parameters(): param.data = self.accelerator.reduce(param.data, reduction="mean")
accelerate/src/accelerate/local_sgd.py/0
{ "file_path": "accelerate/src/accelerate/local_sgd.py", "repo_id": "accelerate", "token_count": 1531 }
6
#!/usr/bin/env python # 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 warnings from typing import List from unittest.mock import Mock import torch from torch.utils.data import DataLoader, IterableDataset, TensorDataset from accelerate.accelerator import Accelerator, DataLoaderConfiguration from accelerate.utils.dataclasses import DistributedType class DummyIterableDataset(IterableDataset): def __init__(self, data): self.data = data def __iter__(self): yield from self.data def create_accelerator(even_batches=True): dataloader_config = DataLoaderConfiguration(even_batches=even_batches) accelerator = Accelerator(dataloader_config=dataloader_config) assert accelerator.num_processes == 2, "this script expects that two GPUs are available" return accelerator def create_dataloader(accelerator: Accelerator, dataset_size: int, batch_size: int, iterable: bool = False): """ Create a simple DataLoader to use during the test cases """ if iterable: dataset = DummyIterableDataset(torch.as_tensor(range(dataset_size))) else: dataset = TensorDataset(torch.as_tensor(range(dataset_size))) dl = DataLoader(dataset, batch_size=batch_size) dl = accelerator.prepare(dl) return dl def verify_dataloader_batch_sizes( accelerator: Accelerator, dataset_size: int, batch_size: int, process_0_expected_batch_sizes: List[int], process_1_expected_batch_sizes: List[int], ): """ A helper function for verifying the batch sizes coming from a prepared dataloader in each process """ dl = create_dataloader(accelerator=accelerator, dataset_size=dataset_size, batch_size=batch_size) batch_sizes = [len(batch[0]) for batch in dl] if accelerator.process_index == 0: assert batch_sizes == process_0_expected_batch_sizes elif accelerator.process_index == 1: assert batch_sizes == process_1_expected_batch_sizes def test_default_ensures_even_batch_sizes(): accelerator = create_accelerator() # without padding, we would expect a different number of batches verify_dataloader_batch_sizes( accelerator, dataset_size=3, batch_size=1, process_0_expected_batch_sizes=[1, 1], process_1_expected_batch_sizes=[1, 1], ) # without padding, we would expect the same number of batches, but different sizes verify_dataloader_batch_sizes( accelerator, dataset_size=7, batch_size=2, process_0_expected_batch_sizes=[2, 2], process_1_expected_batch_sizes=[2, 2], ) def test_can_disable_even_batches(): accelerator = create_accelerator(even_batches=False) verify_dataloader_batch_sizes( accelerator, dataset_size=3, batch_size=1, process_0_expected_batch_sizes=[1, 1], process_1_expected_batch_sizes=[1], ) verify_dataloader_batch_sizes( accelerator, dataset_size=7, batch_size=2, process_0_expected_batch_sizes=[2, 2], process_1_expected_batch_sizes=[2, 1], ) def test_can_join_uneven_inputs(): accelerator = create_accelerator(even_batches=False) model = torch.nn.Linear(1, 1) ddp_model = accelerator.prepare(model) dl = create_dataloader(accelerator, dataset_size=3, batch_size=1) batch_idxs = [] with accelerator.join_uneven_inputs([ddp_model]): for batch_idx, batch in enumerate(dl): output = ddp_model(batch[0].float()) loss = output.sum() loss.backward() batch_idxs.append(batch_idx) accelerator.wait_for_everyone() if accelerator.process_index == 0: assert batch_idxs == [0, 1] elif accelerator.process_index == 1: assert batch_idxs == [0] def test_join_raises_warning_for_non_ddp_distributed(accelerator): with warnings.catch_warnings(record=True) as w: with accelerator.join_uneven_inputs([Mock()]): pass assert issubclass(w[-1].category, UserWarning) assert "only supported for multi-GPU" in str(w[-1].message) def test_join_can_override_even_batches(): default_even_batches = True overridden_even_batches = False accelerator = create_accelerator(even_batches=default_even_batches) model = torch.nn.Linear(1, 1) ddp_model = accelerator.prepare(model) train_dl = create_dataloader(accelerator, dataset_size=3, batch_size=1) valid_dl = create_dataloader(accelerator, dataset_size=3, batch_size=1) with accelerator.join_uneven_inputs([ddp_model], even_batches=overridden_even_batches): train_dl_overridden_value = train_dl.batch_sampler.even_batches valid_dl_overridden_value = valid_dl.batch_sampler.even_batches assert train_dl_overridden_value == overridden_even_batches assert valid_dl_overridden_value == overridden_even_batches assert train_dl.batch_sampler.even_batches == default_even_batches assert valid_dl.batch_sampler.even_batches == default_even_batches def test_join_can_override_for_mixed_type_dataloaders(): default_even_batches = True overridden_even_batches = False accelerator = create_accelerator(even_batches=default_even_batches) model = torch.nn.Linear(1, 1) ddp_model = accelerator.prepare(model) create_dataloader(accelerator, dataset_size=3, batch_size=1, iterable=True) batch_dl = create_dataloader(accelerator, dataset_size=3, batch_size=1) with warnings.catch_warnings(): warnings.filterwarnings("ignore") try: with accelerator.join_uneven_inputs([ddp_model], even_batches=overridden_even_batches): batch_dl_overridden_value = batch_dl.batch_sampler.even_batches except AttributeError: # ensure attribute error is not raised when processing iterable dl raise AssertionError assert batch_dl_overridden_value == overridden_even_batches assert batch_dl.batch_sampler.even_batches == default_even_batches def test_join_raises_warning_for_iterable_when_overriding_even_batches(): accelerator = create_accelerator() model = torch.nn.Linear(1, 1) ddp_model = accelerator.prepare(model) create_dataloader(accelerator, dataset_size=3, batch_size=1, iterable=True) with warnings.catch_warnings(record=True) as w: with accelerator.join_uneven_inputs([ddp_model], even_batches=False): pass assert issubclass(w[-1].category, UserWarning) assert "only supported for map-style datasets" in str(w[-1].message) def main(): accelerator = create_accelerator() accelerator.print("Test that even_batches variable ensures uniform batches across processes") test_default_ensures_even_batch_sizes() accelerator.print("Run tests with even_batches disabled") test_can_disable_even_batches() accelerator.print("Test joining uneven inputs") test_can_join_uneven_inputs() accelerator.print("Test overriding even_batches when joining uneven inputs") test_join_can_override_even_batches() accelerator.print("Test overriding even_batches for mixed dataloader types") test_join_can_override_for_mixed_type_dataloaders() accelerator.print("Test overriding even_batches raises a warning for iterable dataloaders") test_join_raises_warning_for_iterable_when_overriding_even_batches() accelerator.print("Test join with non DDP distributed raises warning") original_state = accelerator.state.distributed_type accelerator.state.distributed_type = DistributedType.FSDP test_join_raises_warning_for_non_ddp_distributed(accelerator) accelerator.state.distributed_type = original_state if __name__ == "__main__": main()
accelerate/src/accelerate/test_utils/scripts/test_distributed_data_loop.py/0
{ "file_path": "accelerate/src/accelerate/test_utils/scripts/test_distributed_data_loop.py", "repo_id": "accelerate", "token_count": 3115 }
7
# Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import subprocess import sys import warnings from ast import literal_eval from shutil import which from typing import Any, Dict, List, Tuple import torch from ..commands.config.config_args import SageMakerConfig from ..utils import ( DynamoBackend, PrecisionType, is_ipex_available, is_mlu_available, is_npu_available, is_torch_xla_available, is_xpu_available, ) from ..utils.constants import DEEPSPEED_MULTINODE_LAUNCHERS from ..utils.other import is_port_in_use, merge_dicts from .dataclasses import DistributedType, SageMakerDistributedType def _filter_args(args, parser, default_args=[]): """ Filters out all `accelerate` specific args """ new_args, _ = parser.parse_known_args(default_args) for key, value in vars(args).items(): if key in vars(new_args).keys(): setattr(new_args, key, value) return new_args def _get_mpirun_args(): """ Determines the executable and argument names for mpirun, based on the type of install. The supported MPI programs are: OpenMPI, Intel MPI, or MVAPICH. Returns: Program name and arg names for hostfile, num processes, and processes per node """ # Find the MPI program name mpi_apps = [x for x in ["mpirun", "mpiexec"] if which(x)] if len(mpi_apps) == 0: raise OSError("mpirun or mpiexec were not found. Ensure that Intel MPI, Open MPI, or MVAPICH are installed.") # Call the app with the --version flag to determine which MPI app is installed mpi_app = mpi_apps[0] mpirun_version = subprocess.check_output([mpi_app, "--version"]) if b"Open MPI" in mpirun_version: return mpi_app, "--hostfile", "-n", "--npernode" else: # Intel MPI and MVAPICH both use the same arg names return mpi_app, "-f", "-n", "-ppn" def prepare_simple_launcher_cmd_env(args: argparse.Namespace) -> Tuple[List[str], Dict[str, str]]: """ Prepares and returns the command list and an environment with the correct simple launcher environment variables. """ cmd = [] if args.no_python and args.module: raise ValueError("--module and --no_python cannot be used together") if args.mpirun_hostfile is not None: mpi_app_name, hostfile_arg, num_proc_arg, proc_per_node_arg = _get_mpirun_args() mpirun_ccl = getattr(args, "mpirun_ccl", None) num_machines = args.num_machines num_processes = getattr(args, "num_processes", None) nproc_per_node = str(num_processes // num_machines) if num_processes and num_machines else "1" cmd += [mpi_app_name, hostfile_arg, args.mpirun_hostfile, proc_per_node_arg, nproc_per_node] if num_processes: cmd += [num_proc_arg, str(num_processes)] if not args.no_python: cmd.append(sys.executable) if args.module: cmd.append("-m") cmd.append(args.training_script) cmd.extend(args.training_script_args) current_env = os.environ.copy() current_env["ACCELERATE_USE_CPU"] = str(args.cpu or args.use_cpu) if args.debug: current_env["ACCELERATE_DEBUG_MODE"] = "true" if args.gpu_ids != "all" and args.gpu_ids is not None: if is_xpu_available(): current_env["ZE_AFFINITY_MASK"] = args.gpu_ids elif is_mlu_available(): current_env["MLU_VISIBLE_DEVICES"] = args.gpu_ids elif is_npu_available(): current_env["ASCEND_RT_VISIBLE_DEVICES"] = args.gpu_ids else: current_env["CUDA_VISIBLE_DEVICES"] = args.gpu_ids if args.num_machines > 1: current_env["MASTER_ADDR"] = args.main_process_ip current_env["MASTER_PORT"] = str(args.main_process_port) if args.mpirun_hostfile is not None: current_env["CCL_WORKER_COUNT"] = mpirun_ccl elif args.num_processes > 1: current_env["MASTER_ADDR"] = args.main_process_ip if args.main_process_ip is not None else "127.0.0.1" current_env["MASTER_PORT"] = str(args.main_process_port) if args.main_process_port is not None else "29500" try: mixed_precision = PrecisionType(args.mixed_precision.lower()) except ValueError: raise ValueError( f"Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}." ) current_env["ACCELERATE_MIXED_PRECISION"] = str(mixed_precision) try: dynamo_backend = DynamoBackend(args.dynamo_backend.upper()) except ValueError: raise ValueError( f"Unknown dynamo backend: {args.dynamo_backend.upper()}. Choose between {DynamoBackend.list()}." ) current_env["ACCELERATE_DYNAMO_BACKEND"] = dynamo_backend.value current_env["ACCELERATE_DYNAMO_MODE"] = args.dynamo_mode current_env["ACCELERATE_DYNAMO_USE_FULLGRAPH"] = str(args.dynamo_use_fullgraph) current_env["ACCELERATE_DYNAMO_USE_DYNAMIC"] = str(args.dynamo_use_dynamic) current_env["OMP_NUM_THREADS"] = str(args.num_cpu_threads_per_process) if is_ipex_available(): current_env["ACCELERATE_USE_IPEX"] = str(args.ipex).lower() current_env["ACCELERATE_USE_XPU"] = str(args.use_xpu).lower() if args.enable_cpu_affinity: current_env["ACCELERATE_CPU_AFFINITY"] = "1" return cmd, current_env def prepare_multi_gpu_env(args: argparse.Namespace) -> Dict[str, str]: """ Prepares and returns an environment with the correct multi-GPU environment variables. """ num_processes = args.num_processes num_machines = args.num_machines main_process_ip = args.main_process_ip main_process_port = args.main_process_port if num_machines > 1: args.nproc_per_node = str(num_processes // num_machines) args.nnodes = str(num_machines) args.node_rank = int(args.machine_rank) if getattr(args, "same_network", False): args.master_addr = str(main_process_ip) args.master_port = str(main_process_port) else: args.rdzv_endpoint = f"{main_process_ip}:{main_process_port}" else: args.nproc_per_node = str(num_processes) if main_process_port is not None: args.master_port = str(main_process_port) if main_process_port is None: main_process_port = 29500 # only need to check port availability in main process, in case we have to start multiple launchers on the same machine # for some reasons like splitting log files. need_port_check = num_machines <= 1 or int(args.machine_rank) == 0 if need_port_check and is_port_in_use(main_process_port): raise ConnectionError( f"Tried to launch distributed communication on port `{main_process_port}`, but another process is utilizing it. " "Please specify a different port (such as using the `--main_process_port` flag or specifying a different `main_process_port` in your config file)" " and rerun your script. To automatically use the next open port (on a single node), you can set this to `0`." ) if args.module and args.no_python: raise ValueError("--module and --no_python cannot be used together") elif args.module: args.module = True elif args.no_python: args.no_python = True current_env = os.environ.copy() if args.debug: current_env["ACCELERATE_DEBUG_MODE"] = "true" gpu_ids = getattr(args, "gpu_ids", "all") if gpu_ids != "all" and args.gpu_ids is not None: if is_xpu_available(): current_env["ZE_AFFINITY_MASK"] = gpu_ids elif is_mlu_available(): current_env["MLU_VISIBLE_DEVICES"] = gpu_ids elif is_npu_available(): current_env["ASCEND_RT_VISIBLE_DEVICES"] = gpu_ids else: current_env["CUDA_VISIBLE_DEVICES"] = gpu_ids mixed_precision = args.mixed_precision.lower() try: mixed_precision = PrecisionType(mixed_precision) except ValueError: raise ValueError(f"Unknown mixed_precision mode: {mixed_precision}. Choose between {PrecisionType.list()}.") current_env["ACCELERATE_MIXED_PRECISION"] = str(mixed_precision) try: dynamo_backend = DynamoBackend(args.dynamo_backend.upper()) except ValueError: raise ValueError( f"Unknown dynamo backend: {args.dynamo_backend.upper()}. Choose between {DynamoBackend.list()}." ) current_env["ACCELERATE_DYNAMO_BACKEND"] = dynamo_backend.value current_env["ACCELERATE_DYNAMO_MODE"] = args.dynamo_mode current_env["ACCELERATE_DYNAMO_USE_FULLGRAPH"] = str(args.dynamo_use_fullgraph) current_env["ACCELERATE_DYNAMO_USE_DYNAMIC"] = str(args.dynamo_use_dynamic) if args.use_fsdp: current_env["ACCELERATE_USE_FSDP"] = "true" if args.fsdp_cpu_ram_efficient_loading and not args.fsdp_sync_module_states: raise ValueError("When using `--fsdp_cpu_ram_efficient_loading` set `--fsdp_sync_module_states` to `True`") current_env["FSDP_SHARDING_STRATEGY"] = str(args.fsdp_sharding_strategy) current_env["FSDP_OFFLOAD_PARAMS"] = str(args.fsdp_offload_params).lower() current_env["FSDP_MIN_NUM_PARAMS"] = str(args.fsdp_min_num_params) if args.fsdp_auto_wrap_policy is not None: current_env["FSDP_AUTO_WRAP_POLICY"] = str(args.fsdp_auto_wrap_policy) if args.fsdp_transformer_layer_cls_to_wrap is not None: current_env["FSDP_TRANSFORMER_CLS_TO_WRAP"] = str(args.fsdp_transformer_layer_cls_to_wrap) if args.fsdp_backward_prefetch_policy is not None: warnings.warn( "`fsdp_backward_prefetch_policy` is deprecated and will be removed in version 0.27.0 of 🤗 Accelerate. Use" " `fsdp_backward_prefetch` instead", FutureWarning, ) args.fsdp_backward_prefetch = args.fsdp_backward_prefetch_policy if args.fsdp_backward_prefetch is not None: current_env["FSDP_BACKWARD_PREFETCH"] = str(args.fsdp_backward_prefetch) if args.fsdp_state_dict_type is not None: current_env["FSDP_STATE_DICT_TYPE"] = str(args.fsdp_state_dict_type) current_env["FSDP_FORWARD_PREFETCH"] = str(args.fsdp_forward_prefetch).lower() current_env["FSDP_USE_ORIG_PARAMS"] = str(args.fsdp_use_orig_params).lower() current_env["FSDP_CPU_RAM_EFFICIENT_LOADING"] = str(args.fsdp_cpu_ram_efficient_loading).lower() current_env["FSDP_SYNC_MODULE_STATES"] = str(args.fsdp_sync_module_states).lower() if args.use_megatron_lm: prefix = "MEGATRON_LM_" current_env["ACCELERATE_USE_MEGATRON_LM"] = "true" current_env[prefix + "TP_DEGREE"] = str(args.megatron_lm_tp_degree) current_env[prefix + "PP_DEGREE"] = str(args.megatron_lm_pp_degree) current_env[prefix + "GRADIENT_CLIPPING"] = str(args.megatron_lm_gradient_clipping) if args.megatron_lm_num_micro_batches is not None: current_env[prefix + "NUM_MICRO_BATCHES"] = str(args.megatron_lm_num_micro_batches) if args.megatron_lm_sequence_parallelism is not None: current_env[prefix + "SEQUENCE_PARALLELISM"] = str(args.megatron_lm_sequence_parallelism) if args.megatron_lm_recompute_activations is not None: current_env[prefix + "RECOMPUTE_ACTIVATIONS"] = str(args.megatron_lm_recompute_activations) if args.megatron_lm_use_distributed_optimizer is not None: current_env[prefix + "USE_DISTRIBUTED_OPTIMIZER"] = str(args.megatron_lm_use_distributed_optimizer) current_env["OMP_NUM_THREADS"] = str(args.num_cpu_threads_per_process) if args.enable_cpu_affinity: current_env["ACCELERATE_CPU_AFFINITY"] = "1" return current_env def prepare_deepspeed_cmd_env(args: argparse.Namespace) -> Tuple[List[str], Dict[str, str]]: """ Prepares and returns the command list and an environment with the correct DeepSpeed environment variables. """ num_processes = args.num_processes num_machines = args.num_machines main_process_ip = args.main_process_ip main_process_port = args.main_process_port cmd = None # make sure launcher is not None if args.deepspeed_multinode_launcher is None: # set to default pdsh args.deepspeed_multinode_launcher = DEEPSPEED_MULTINODE_LAUNCHERS[0] if num_machines > 1 and args.deepspeed_multinode_launcher != DEEPSPEED_MULTINODE_LAUNCHERS[1]: cmd = ["deepspeed", "--no_local_rank"] cmd.extend(["--hostfile", str(args.deepspeed_hostfile), "--launcher", str(args.deepspeed_multinode_launcher)]) if args.deepspeed_exclusion_filter is not None: cmd.extend( [ "--exclude", str(args.deepspeed_exclusion_filter), ] ) elif args.deepspeed_inclusion_filter is not None: cmd.extend( [ "--include", str(args.deepspeed_inclusion_filter), ] ) else: cmd.extend(["--num_gpus", str(args.num_processes // args.num_machines)]) if main_process_ip: cmd.extend(["--master_addr", str(main_process_ip)]) cmd.extend(["--master_port", str(main_process_port)]) if args.module and args.no_python: raise ValueError("--module and --no_python cannot be used together") elif args.module: cmd.append("--module") elif args.no_python: cmd.append("--no_python") cmd.append(args.training_script) cmd.extend(args.training_script_args) elif num_machines > 1 and args.deepspeed_multinode_launcher == DEEPSPEED_MULTINODE_LAUNCHERS[1]: args.nproc_per_node = str(num_processes // num_machines) args.nnodes = str(num_machines) args.node_rank = int(args.machine_rank) if getattr(args, "same_network", False): args.master_addr = str(main_process_ip) args.master_port = str(main_process_port) else: args.rdzv_endpoint = f"{main_process_ip}:{main_process_port}" else: args.nproc_per_node = str(num_processes) if main_process_port is not None: args.master_port = str(main_process_port) if main_process_port is None: main_process_port = 29500 # only need to check port availability in main process, in case we have to start multiple launchers on the same machine # for some reasons like splitting log files. need_port_check = num_machines <= 1 or int(args.machine_rank) == 0 if need_port_check and is_port_in_use(main_process_port): raise ConnectionError( f"Tried to launch distributed communication on port `{main_process_port}`, but another process is utilizing it. " "Please specify a different port (such as using the `--main_process_port` flag or specifying a different `main_process_port` in your config file)" " and rerun your script. To automatically use the next open port (on a single node), you can set this to `0`." ) if args.module and args.no_python: raise ValueError("--module and --no_python cannot be used together") elif args.module: args.module = True elif args.no_python: args.no_python = True current_env = os.environ.copy() if args.debug: current_env["ACCELERATE_DEBUG_MODE"] = "true" gpu_ids = getattr(args, "gpu_ids", "all") if gpu_ids != "all" and args.gpu_ids is not None: if is_xpu_available(): current_env["ZE_AFFINITY_MASK"] = gpu_ids elif is_mlu_available(): current_env["MLU_VISIBLE_DEVICES"] = gpu_ids elif is_npu_available(): current_env["ASCEND_RT_VISIBLE_DEVICES"] = gpu_ids else: current_env["CUDA_VISIBLE_DEVICES"] = gpu_ids try: mixed_precision = PrecisionType(args.mixed_precision.lower()) except ValueError: raise ValueError( f"Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}." ) current_env["PYTHONPATH"] = env_var_path_add("PYTHONPATH", os.path.abspath(".")) current_env["ACCELERATE_MIXED_PRECISION"] = str(mixed_precision) current_env["ACCELERATE_CONFIG_DS_FIELDS"] = str(args.deepspeed_fields_from_accelerate_config).lower() current_env["ACCELERATE_USE_DEEPSPEED"] = "true" if args.zero_stage is not None: current_env["ACCELERATE_DEEPSPEED_ZERO_STAGE"] = str(args.zero_stage) if args.gradient_accumulation_steps is not None: current_env["ACCELERATE_GRADIENT_ACCUMULATION_STEPS"] = str(args.gradient_accumulation_steps) if args.gradient_clipping is not None: current_env["ACCELERATE_GRADIENT_CLIPPING"] = str(args.gradient_clipping).lower() if args.offload_optimizer_device is not None: current_env["ACCELERATE_DEEPSPEED_OFFLOAD_OPTIMIZER_DEVICE"] = str(args.offload_optimizer_device).lower() if args.offload_param_device is not None: current_env["ACCELERATE_DEEPSPEED_OFFLOAD_PARAM_DEVICE"] = str(args.offload_param_device).lower() if args.zero3_init_flag is not None: current_env["ACCELERATE_DEEPSPEED_ZERO3_INIT"] = str(args.zero3_init_flag).lower() if args.zero3_save_16bit_model is not None: current_env["ACCELERATE_DEEPSPEED_ZERO3_SAVE_16BIT_MODEL"] = str(args.zero3_save_16bit_model).lower() if args.deepspeed_config_file is not None: current_env["ACCELERATE_DEEPSPEED_CONFIG_FILE"] = str(args.deepspeed_config_file) if args.enable_cpu_affinity: current_env["ACCELERATE_CPU_AFFINITY"] = "1" return cmd, current_env def prepare_tpu( args: argparse.Namespace, current_env: Dict[str, str], pod: bool = False ) -> Tuple[argparse.Namespace, Dict[str, str]]: """ Prepares and returns an environment with the correct TPU environment variables. """ if args.mixed_precision == "bf16" and is_torch_xla_available(check_is_tpu=True): if args.downcast_bf16: current_env["XLA_DOWNCAST_BF16"] = "1" else: current_env["XLA_USE_BF16"] = "1" if args.debug: current_env["ACCELERATE_DEBUG_MODE"] = "true" if pod: # Take explicit args and set them up for XLA args.vm = args.tpu_vm args.tpu = args.tpu_name return args, current_env def _convert_nargs_to_dict(nargs: List[str]) -> Dict[str, str]: if len(nargs) < 0: return {} # helper function to infer type for argsparser def _infer_type(s): try: s = float(s) if s // 1 == s: return int(s) return s except ValueError: return s parser = argparse.ArgumentParser() _, unknown = parser.parse_known_args(nargs) for index, argument in enumerate(unknown): if argument.startswith(("-", "--")): action = None if index + 1 < len(unknown): # checks if next index would be in list if unknown[index + 1].startswith(("-", "--")): # checks if next element is an key # raise an error if element is store_true or store_false raise ValueError( "SageMaker doesn’t support argparse actions for `store_true` or `store_false`. Please define explicit types" ) else: # raise an error if last element is store_true or store_false raise ValueError( "SageMaker doesn’t support argparse actions for `store_true` or `store_false`. Please define explicit types" ) # adds argument to parser based on action_store true if action is None: parser.add_argument(argument, type=_infer_type) else: parser.add_argument(argument, action=action) return { key: (literal_eval(value) if value in ("True", "False") else value) for key, value in parser.parse_args(nargs).__dict__.items() } def prepare_sagemager_args_inputs( sagemaker_config: SageMakerConfig, args: argparse.Namespace ) -> Tuple[argparse.Namespace, Dict[str, Any]]: # configure environment print("Configuring Amazon SageMaker environment") os.environ["AWS_DEFAULT_REGION"] = sagemaker_config.region # configure credentials if sagemaker_config.profile is not None: os.environ["AWS_PROFILE"] = sagemaker_config.profile elif args.aws_access_key_id is not None and args.aws_secret_access_key is not None: os.environ["AWS_ACCESS_KEY_ID"] = args.aws_access_key_id os.environ["AWS_SECRET_ACCESS_KEY"] = args.aws_secret_access_key else: raise OSError("You need to provide an aws_access_key_id and aws_secret_access_key when not using aws_profile") # extract needed arguments source_dir = os.path.dirname(args.training_script) if not source_dir: # checks if string is empty source_dir = "." entry_point = os.path.basename(args.training_script) if not entry_point.endswith(".py"): raise ValueError(f'Your training script should be a python script and not "{entry_point}"') print("Converting Arguments to Hyperparameters") hyperparameters = _convert_nargs_to_dict(args.training_script_args) try: mixed_precision = PrecisionType(args.mixed_precision.lower()) except ValueError: raise ValueError( f"Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}." ) try: dynamo_backend = DynamoBackend(args.dynamo_backend.upper()) except ValueError: raise ValueError( f"Unknown dynamo backend: {args.dynamo_backend.upper()}. Choose between {DynamoBackend.list()}." ) # Environment variables to be set for use during training job environment = { "ACCELERATE_USE_SAGEMAKER": "true", "ACCELERATE_MIXED_PRECISION": str(mixed_precision), "ACCELERATE_DYNAMO_BACKEND": dynamo_backend.value, "ACCELERATE_DYNAMO_MODE": args.dynamo_mode, "ACCELERATE_DYNAMO_USE_FULLGRAPH": str(args.dynamo_use_fullgraph), "ACCELERATE_DYNAMO_USE_DYNAMIC": str(args.dynamo_use_dynamic), "ACCELERATE_SAGEMAKER_DISTRIBUTED_TYPE": sagemaker_config.distributed_type.value, } # configure distribution set up distribution = None if sagemaker_config.distributed_type == SageMakerDistributedType.DATA_PARALLEL: distribution = {"smdistributed": {"dataparallel": {"enabled": True}}} # configure sagemaker inputs sagemaker_inputs = None if sagemaker_config.sagemaker_inputs_file is not None: print(f"Loading SageMaker Inputs from {sagemaker_config.sagemaker_inputs_file} file") sagemaker_inputs = {} with open(sagemaker_config.sagemaker_inputs_file) as file: for i, line in enumerate(file): if i == 0: continue l = line.split("\t") sagemaker_inputs[l[0]] = l[1].strip() print(f"Loaded SageMaker Inputs: {sagemaker_inputs}") # configure sagemaker metrics sagemaker_metrics = None if sagemaker_config.sagemaker_metrics_file is not None: print(f"Loading SageMaker Metrics from {sagemaker_config.sagemaker_metrics_file} file") sagemaker_metrics = [] with open(sagemaker_config.sagemaker_metrics_file) as file: for i, line in enumerate(file): if i == 0: continue l = line.split("\t") metric_dict = { "Name": l[0], "Regex": l[1].strip(), } sagemaker_metrics.append(metric_dict) print(f"Loaded SageMaker Metrics: {sagemaker_metrics}") # configure session print("Creating Estimator") args = { "image_uri": sagemaker_config.image_uri, "entry_point": entry_point, "source_dir": source_dir, "role": sagemaker_config.iam_role_name, "transformers_version": sagemaker_config.transformers_version, "pytorch_version": sagemaker_config.pytorch_version, "py_version": sagemaker_config.py_version, "base_job_name": sagemaker_config.base_job_name, "instance_count": sagemaker_config.num_machines, "instance_type": sagemaker_config.ec2_instance_type, "debugger_hook_config": False, "distribution": distribution, "hyperparameters": hyperparameters, "environment": environment, "metric_definitions": sagemaker_metrics, } if sagemaker_config.additional_args is not None: args = merge_dicts(sagemaker_config.additional_args, args) return args, sagemaker_inputs def env_var_path_add(env_var_name, path_to_add): """ Extends a path-based environment variable's value with a new path and returns the updated value. It's up to the caller to set it in os.environ. """ paths = [p for p in os.environ.get(env_var_name, "").split(":") if len(p) > 0] paths.append(str(path_to_add)) return ":".join(paths) class PrepareForLaunch: """ Prepare a function that will launched in a distributed setup. Args: launcher (`Callable`): The function to launch. distributed_type ([`~state.DistributedType`]): The distributed type to prepare for. debug (`bool`, *optional*, defaults to `False`): Whether or not this is a debug launch. """ def __init__(self, launcher, distributed_type="NO", debug=False): self.launcher = launcher self.distributed_type = DistributedType(distributed_type) self.debug = debug def __call__(self, index, *args): if self.debug: world_size = int(os.environ.get("WORLD_SIZE")) rdv_file = os.environ.get("ACCELERATE_DEBUG_RDV_FILE") torch.distributed.init_process_group( "gloo", rank=index, store=torch.distributed.FileStore(rdv_file, world_size), world_size=world_size, ) elif self.distributed_type in ( DistributedType.MULTI_GPU, DistributedType.MULTI_MLU, DistributedType.MULTI_NPU, DistributedType.MULTI_XPU, DistributedType.MULTI_CPU, ): # Prepare the environment for torch.distributed os.environ["LOCAL_RANK"] = str(index) nproc = int(os.environ.get("NPROC", 1)) node_rank = int(os.environ.get("NODE_RANK", 0)) os.environ["RANK"] = str(nproc * node_rank + index) os.environ["FORK_LAUNCHED"] = str(1) self.launcher(*args)
accelerate/src/accelerate/utils/launch.py/0
{ "file_path": "accelerate/src/accelerate/utils/launch.py", "repo_id": "accelerate", "token_count": 11894 }
8
# Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import torch from transformers import AutoModel from transformers.testing_utils import mockenv_context from transformers.trainer_utils import set_seed from accelerate.accelerator import Accelerator from accelerate.state import AcceleratorState from accelerate.test_utils.testing import ( AccelerateTestCase, TempDirTestCase, execute_subprocess_async, get_launch_command, path_in_accelerate_package, require_fsdp, require_multi_device, require_non_cpu, require_non_torch_xla, slow, ) from accelerate.utils.constants import ( FSDP_AUTO_WRAP_POLICY, FSDP_BACKWARD_PREFETCH, FSDP_SHARDING_STRATEGY, FSDP_STATE_DICT_TYPE, ) from accelerate.utils.dataclasses import FullyShardedDataParallelPlugin from accelerate.utils.other import patch_environment set_seed(42) BERT_BASE_CASED = "bert-base-cased" FP16 = "fp16" BF16 = "bf16" dtypes = [FP16, BF16] @require_fsdp @require_non_cpu @require_non_torch_xla class FSDPPluginIntegration(AccelerateTestCase): def setUp(self): super().setUp() self.dist_env = dict( ACCELERATE_USE_FSDP="true", MASTER_ADDR="localhost", MASTER_PORT="10999", RANK="0", LOCAL_RANK="0", WORLD_SIZE="1", ) def test_sharding_strategy(self): from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy # check that giving enums works fine for i, strategy in enumerate(FSDP_SHARDING_STRATEGY): env = self.dist_env.copy() env["FSDP_SHARDING_STRATEGY"] = f"{i + 1}" with mockenv_context(**env): fsdp_plugin = FullyShardedDataParallelPlugin() assert fsdp_plugin.sharding_strategy == ShardingStrategy(i + 1) # check that giving names works fine for i, strategy in enumerate(FSDP_SHARDING_STRATEGY): env = self.dist_env.copy() env["FSDP_SHARDING_STRATEGY"] = strategy with mockenv_context(**env): fsdp_plugin = FullyShardedDataParallelPlugin() assert fsdp_plugin.sharding_strategy == ShardingStrategy(i + 1) def test_backward_prefetch(self): from torch.distributed.fsdp.fully_sharded_data_parallel import BackwardPrefetch for i, prefetch_policy in enumerate(FSDP_BACKWARD_PREFETCH): env = self.dist_env.copy() env["FSDP_BACKWARD_PREFETCH"] = prefetch_policy with mockenv_context(**env): fsdp_plugin = FullyShardedDataParallelPlugin() if prefetch_policy == "NO_PREFETCH": assert fsdp_plugin.backward_prefetch is None else: assert fsdp_plugin.backward_prefetch == BackwardPrefetch(i + 1) def test_state_dict_type(self): from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType for i, state_dict_type in enumerate(FSDP_STATE_DICT_TYPE): env = self.dist_env.copy() env["FSDP_STATE_DICT_TYPE"] = state_dict_type with mockenv_context(**env): fsdp_plugin = FullyShardedDataParallelPlugin() assert fsdp_plugin.state_dict_type == StateDictType(i + 1) if state_dict_type == "FULL_STATE_DICT": assert fsdp_plugin.state_dict_config.offload_to_cpu assert fsdp_plugin.state_dict_config.rank0_only def test_auto_wrap_policy(self): model = AutoModel.from_pretrained(BERT_BASE_CASED) for policy in FSDP_AUTO_WRAP_POLICY: env = self.dist_env.copy() env["FSDP_AUTO_WRAP_POLICY"] = policy if policy == "TRANSFORMER_BASED_WRAP": env["FSDP_TRANSFORMER_CLS_TO_WRAP"] = "BertLayer" elif policy == "SIZE_BASED_WRAP": env["FSDP_MIN_NUM_PARAMS"] = "2000" with mockenv_context(**env): fsdp_plugin = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(model) if policy == "NO_WRAP": assert fsdp_plugin.auto_wrap_policy is None else: assert fsdp_plugin.auto_wrap_policy is not None env = self.dist_env.copy() env["FSDP_AUTO_WRAP_POLICY"] = "TRANSFORMER_BASED_WRAP" env["FSDP_TRANSFORMER_CLS_TO_WRAP"] = "T5Layer" with mockenv_context(**env): fsdp_plugin = FullyShardedDataParallelPlugin() with self.assertRaises(Exception) as cm: fsdp_plugin.set_auto_wrap_policy(model) assert "Could not find the transformer layer class to wrap in the model." in str(cm.exception) env = self.dist_env.copy() env["FSDP_AUTO_WRAP_POLICY"] = "SIZE_BASED_WRAP" env["FSDP_MIN_NUM_PARAMS"] = "0" with mockenv_context(**env): fsdp_plugin = FullyShardedDataParallelPlugin() fsdp_plugin.set_auto_wrap_policy(model) assert fsdp_plugin.auto_wrap_policy is None def test_mixed_precision(self): from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler for mp_dtype in dtypes: env = self.dist_env.copy() env["ACCELERATE_MIXED_PRECISION"] = mp_dtype with mockenv_context(**env): accelerator = Accelerator() if mp_dtype == "fp16": dtype = torch.float16 elif mp_dtype == "bf16": dtype = torch.bfloat16 mp_policy = MixedPrecision(param_dtype=dtype, reduce_dtype=dtype, buffer_dtype=dtype) assert accelerator.state.fsdp_plugin.mixed_precision_policy == mp_policy if mp_dtype == FP16: assert isinstance(accelerator.scaler, ShardedGradScaler) elif mp_dtype == BF16: assert accelerator.scaler is None AcceleratorState._reset_state(True) def test_mixed_precision_buffer_autocast_override(self): from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler for mp_dtype in dtypes: env = self.dist_env.copy() env["ACCELERATE_MIXED_PRECISION"] = mp_dtype with mockenv_context(**env): accelerator = Accelerator() if mp_dtype == "fp16": dtype = torch.float16 elif mp_dtype == "bf16": dtype = torch.bfloat16 mp_policy = MixedPrecision(param_dtype=dtype, reduce_dtype=dtype, buffer_dtype=torch.float32) accelerator.state.fsdp_plugin.set_mixed_precision(dtype, buffer_autocast=True, override=True) assert accelerator.state.fsdp_plugin.mixed_precision_policy == mp_policy if mp_dtype == FP16: assert isinstance(accelerator.scaler, ShardedGradScaler) elif mp_dtype == BF16: assert accelerator.scaler is None AcceleratorState._reset_state(True) def test_cpu_offload(self): from torch.distributed.fsdp.fully_sharded_data_parallel import CPUOffload for flag in [True, False]: env = self.dist_env.copy() env["FSDP_OFFLOAD_PARAMS"] = str(flag).lower() with mockenv_context(**env): fsdp_plugin = FullyShardedDataParallelPlugin() assert fsdp_plugin.cpu_offload == CPUOffload(offload_params=flag) # Skip this test when TorchXLA is available because accelerate.launch does not support TorchXLA FSDP. @require_non_torch_xla @require_fsdp @require_multi_device @slow class FSDPIntegrationTest(TempDirTestCase): test_scripts_folder = path_in_accelerate_package("test_utils", "scripts", "external_deps") def setUp(self): super().setUp() self.performance_lower_bound = 0.82 self.performance_configs = [ "fsdp_shard_grad_op_transformer_based_wrap", "fsdp_full_shard_transformer_based_wrap", ] self.peak_memory_usage_upper_bound = { "multi_gpu_fp16": 3200, "fsdp_shard_grad_op_transformer_based_wrap_fp16": 2000, "fsdp_full_shard_transformer_based_wrap_fp16": 1900, # Disabling below test as it overwhelms the RAM memory usage # on CI self-hosted runner leading to tests getting killed. # "fsdp_full_shard_cpu_offload_transformer_based_wrap_fp32": 1500, # fp16 was leading to indefinite hang } self.n_train = 160 self.n_val = 160 def test_performance(self): self.test_file_path = self.test_scripts_folder / "test_performance.py" cmd = get_launch_command(num_processes=2, num_machines=1, machine_rank=0, use_fsdp=True) for config in self.performance_configs: cmd_config = cmd.copy() for i, strategy in enumerate(FSDP_SHARDING_STRATEGY): if strategy.lower() in config: cmd_config.append(f"--fsdp_sharding_strategy={strategy}") break if "fp32" in config: cmd_config.append("--mixed_precision=no") else: cmd_config.append("--mixed_precision=fp16") if "cpu_offload" in config: cmd_config.append("--fsdp_offload_params=True") for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in config: cmd_config.append(f"--fsdp_auto_wrap_policy={policy}") break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append("--fsdp_transformer_layer_cls_to_wrap=BertLayer") elif policy == "SIZE_BASED_WRAP": cmd_config.append("--fsdp_min_num_params=2000") cmd_config.extend( [ self.test_file_path, f"--output_dir={self.tmpdir}", f"--performance_lower_bound={self.performance_lower_bound}", ] ) with patch_environment(omp_num_threads=1): execute_subprocess_async(cmd_config) def test_checkpointing(self): self.test_file_path = self.test_scripts_folder / "test_checkpointing.py" cmd = get_launch_command( num_processes=2, num_machines=1, machine_rank=0, use_fsdp=True, mixed_precision="fp16", fsdp_transformer_layer_cls_to_wrap="BertLayer", ) for i, strategy in enumerate(FSDP_SHARDING_STRATEGY): cmd_config = cmd.copy() cmd_config.append(f"--fsdp_sharding_strategy={strategy}") if strategy != "FULL_SHARD": continue state_dict_config_index = len(cmd_config) for state_dict_type in FSDP_STATE_DICT_TYPE: # Todo: Currently failing for `LOCAL_STATE_DICT` with error # Unexpected key(s) in state_dict: "_fsdp_wrapped_module._flat_param". if state_dict_type == "LOCAL_STATE_DICT": continue cmd_config = cmd_config[:state_dict_config_index] cmd_config.append(f"--fsdp_state_dict_type={state_dict_type}") cmd_config.extend( [ self.test_file_path, f"--output_dir={self.tmpdir}", "--partial_train_epoch=1", ] ) with patch_environment(omp_num_threads=1): execute_subprocess_async(cmd_config) cmd_config = cmd_config[:-1] resume_from_checkpoint = os.path.join(self.tmpdir, "epoch_0") cmd_config.extend( [ f"--resume_from_checkpoint={resume_from_checkpoint}", ] ) with patch_environment(omp_num_threads=1): execute_subprocess_async(cmd_config) def test_peak_memory_usage(self): self.test_file_path = self.test_scripts_folder / "test_peak_memory_usage.py" cmd = get_launch_command(num_processes=2, num_machines=1, machine_rank=0) for spec, peak_mem_upper_bound in self.peak_memory_usage_upper_bound.items(): cmd_config = cmd.copy() if "fp16" in spec: cmd_config.extend(["--mixed_precision=fp16"]) else: cmd_config.extend(["--mixed_precision=no"]) if "multi_gpu" in spec: continue else: cmd_config.extend(["--use_fsdp"]) for i, strategy in enumerate(FSDP_SHARDING_STRATEGY): if strategy.lower() in spec: cmd_config.append(f"--fsdp_sharding_strategy={strategy}") break if "cpu_offload" in spec: cmd_config.append("--fsdp_offload_params=True") for policy in FSDP_AUTO_WRAP_POLICY: if policy.lower() in spec: cmd_config.append(f"--fsdp_auto_wrap_policy={policy}") break if policy == "TRANSFORMER_BASED_WRAP": cmd_config.append("--fsdp_transformer_layer_cls_to_wrap=BertLayer") elif policy == "SIZE_BASED_WRAP": cmd_config.append("--fsdp_min_num_params=2000") cmd_config.extend( [ self.test_file_path, f"--output_dir={self.tmpdir}", f"--peak_memory_upper_bound={peak_mem_upper_bound}", f"--n_train={self.n_train}", f"--n_val={self.n_val}", ] ) with patch_environment(omp_num_threads=1): execute_subprocess_async(cmd_config)
accelerate/tests/fsdp/test_fsdp.py/0
{ "file_path": "accelerate/tests/fsdp/test_fsdp.py", "repo_id": "accelerate", "token_count": 7367 }
9
# Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from torch import nn from accelerate.test_utils import memory_allocated_func, require_non_cpu, require_non_torch_xla, torch_device from accelerate.utils.memory import find_executable_batch_size, release_memory def raise_fake_out_of_memory(): raise RuntimeError("CUDA out of memory.") class ModelForTest(nn.Module): def __init__(self): super().__init__() self.linear1 = nn.Linear(3, 4) self.batchnorm = nn.BatchNorm1d(4) self.linear2 = nn.Linear(4, 5) def forward(self, x): return self.linear2(self.batchnorm(self.linear1(x))) class MemoryTest(unittest.TestCase): def test_memory_implicit(self): batch_sizes = [] @find_executable_batch_size(starting_batch_size=128) def mock_training_loop_function(batch_size): nonlocal batch_sizes batch_sizes.append(batch_size) if batch_size != 8: raise_fake_out_of_memory() mock_training_loop_function() assert batch_sizes == [128, 64, 32, 16, 8] def test_memory_explicit(self): batch_sizes = [] @find_executable_batch_size(starting_batch_size=128) def mock_training_loop_function(batch_size, arg1): nonlocal batch_sizes batch_sizes.append(batch_size) if batch_size != 8: raise_fake_out_of_memory() return batch_size, arg1 bs, arg1 = mock_training_loop_function("hello") assert batch_sizes == [128, 64, 32, 16, 8] assert [bs, arg1] == [8, "hello"] def test_start_zero(self): @find_executable_batch_size(starting_batch_size=0) def mock_training_loop_function(batch_size): pass with self.assertRaises(RuntimeError) as cm: mock_training_loop_function() assert "No executable batch size found, reached zero." in cm.exception.args[0] def test_approach_zero(self): @find_executable_batch_size(starting_batch_size=16) def mock_training_loop_function(batch_size): if batch_size > 0: raise_fake_out_of_memory() pass with self.assertRaises(RuntimeError) as cm: mock_training_loop_function() assert "No executable batch size found, reached zero." in cm.exception.args[0] def test_verbose_guard(self): @find_executable_batch_size(starting_batch_size=128) def mock_training_loop_function(batch_size, arg1, arg2): if batch_size != 8: raise raise_fake_out_of_memory() with self.assertRaises(TypeError) as cm: mock_training_loop_function(128, "hello", "world") assert "Batch size was passed into `f`" in cm.exception.args[0] assert "`f(arg1='hello', arg2='world')" in cm.exception.args[0] def test_any_other_error(self): @find_executable_batch_size(starting_batch_size=16) def mock_training_loop_function(batch_size): raise ValueError("Oops, we had an error!") with self.assertRaises(ValueError) as cm: mock_training_loop_function() assert "Oops, we had an error!" in cm.exception.args[0] @require_non_cpu @require_non_torch_xla def test_release_memory(self): starting_memory = memory_allocated_func() model = ModelForTest() model.to(torch_device) assert memory_allocated_func() > starting_memory model = release_memory(model) assert memory_allocated_func() == starting_memory
accelerate/tests/test_memory_utils.py/0
{ "file_path": "accelerate/tests/test_memory_utils.py", "repo_id": "accelerate", "token_count": 1740 }
10
# 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. """ A simple launcher script for TPU training Inspired by https://github.com/pytorch/pytorch/blob/master/torch/distributed/launch.py :: >>> python xla_spawn.py --num_cores=NUM_CORES_YOU_HAVE YOUR_TRAINING_SCRIPT.py (--arg1 --arg2 --arg3 and all other arguments of your training script) """ import importlib import sys from argparse import REMAINDER, ArgumentParser from pathlib import Path import torch_xla.distributed.xla_multiprocessing as xmp def parse_args(): """ Helper function parsing the command line options @retval ArgumentParser """ parser = ArgumentParser( description=( "PyTorch TPU distributed training launch " "helper utility that will spawn up " "multiple distributed processes" ) ) # Optional arguments for the launch helper parser.add_argument("--num_cores", type=int, default=1, help="Number of TPU cores to use (1 or 8).") # positional parser.add_argument( "training_script", type=str, help=( "The full path to the single TPU training " "program/script to be launched in parallel, " "followed by all the arguments for the " "training script" ), ) # rest from the training program parser.add_argument("training_script_args", nargs=REMAINDER) return parser.parse_args() def main(): args = parse_args() # Import training_script as a module. script_fpath = Path(args.training_script) sys.path.append(str(script_fpath.parent.resolve())) mod_name = script_fpath.stem mod = importlib.import_module(mod_name) # Patch sys.argv sys.argv = [args.training_script] + args.training_script_args + ["--tpu_num_cores", str(args.num_cores)] xmp.spawn(mod._mp_fn, args=(), nprocs=args.num_cores) if __name__ == "__main__": main()
accelerate/tests/xla_spawn.py/0
{ "file_path": "accelerate/tests/xla_spawn.py", "repo_id": "accelerate", "token_count": 917 }
11
# Model arguments model_name_or_path: gpt2 model_revision: main torch_dtype: bfloat16 # Data training arguments dataset_mixer: yhavinga/mc4_nl_cleaned: 1.0 dataset_splits: - train dataset_configs: - tiny preprocessing_num_workers: 12 # SFT trainer config bf16: true do_eval: False evaluation_strategy: "no" gradient_accumulation_steps: 1 gradient_checkpointing: true gradient_checkpointing_kwargs: use_reentrant: False hub_model_id: gpt2-cpt-dutch hub_strategy: every_save learning_rate: 2.0e-04 log_level: info logging_steps: 5 logging_strategy: steps lr_scheduler_type: cosine max_seq_length: 1024 max_steps: -1 num_train_epochs: 1 output_dir: data/gpt2-cpt-dutch overwrite_output_dir: true per_device_eval_batch_size: 8 per_device_train_batch_size: 16 push_to_hub: true remove_unused_columns: true report_to: - wandb save_strategy: "steps" save_steps: 100 save_total_limit: 1 seed: 42 warmup_ratio: 0.1
alignment-handbook/recipes/gpt2-nl/cpt/config_full.yaml/0
{ "file_path": "alignment-handbook/recipes/gpt2-nl/cpt/config_full.yaml", "repo_id": "alignment-handbook", "token_count": 370 }
12
# Instructions to Replicate Zephyr 7B Gemma Similar to how we trained Zephyr 7B Beta in our [technical report](https://huggingface.co/papers/2310.16944), training this model proceeds in two steps: 1. Apply SFT to fine-tune Gemma 7B on the Deita 10k dataset ([link](https://huggingface.co/datasets/HuggingFaceH4/deita-10k-v0-sft)). The result is an SFT model like [`zephyr-7b-gemma-sft`](https://huggingface.co/HuggingFaceH4/zephyr-7b-gemma-sft-v0.1). 2. Align the SFT model to AI feedback via DPO on a curated mix of 7k examples by Argilla ([link](https://huggingface.co/datasets/argilla/dpo-mix-7k)). The result is a DPO model like [`zephyr-7b-gemma`](HuggingFaceH4/zephyr-7b-gemma-v0.1). See below for commands to train these models using either DeepSpeed ZeRO-3 or LoRA. ## Full training examples You will require 8 GPUs (80GB of VRAM) to train the full model - alternatively, you can train on 1 GPU by adjusting the micro batch size and gradient accumulation steps to keep the global batch size constant. A recipe involving QLoRA will come later 🤗. ```shell # Step 1 - SFT ACCELERATE_LOG_LEVEL=info accelerate launch --config_file recipes/accelerate_configs/deepspeed_zero3.yaml scripts/run_sft.py recipes/zephyr-7b-gemma/sft/config_full.yaml # Step 2 - DPO ACCELERATE_LOG_LEVEL=info accelerate launch --config_file recipes/accelerate_configs/deepspeed_zero3.yaml scripts/run_dpo.py recipes/zephyr-7b-gemma/dpo/config_full.yaml ```
alignment-handbook/recipes/zephyr-7b-gemma/README.md/0
{ "file_path": "alignment-handbook/recipes/zephyr-7b-gemma/README.md", "repo_id": "alignment-handbook", "token_count": 505 }
13
# Model arguments model_name_or_path: alignment-handbook/zephyr-7b-sft-full # Data training arguments # For definitions, see: src/h4/training/config.py dataset_mixer: HuggingFaceH4/ultrafeedback_binarized: 1.0 dataset_splits: - train_prefs - test_prefs preprocessing_num_workers: 12 # DPOTrainer arguments bf16: true beta: 0.1 do_eval: true evaluation_strategy: steps eval_steps: 100 gradient_accumulation_steps: 1 gradient_checkpointing: true hub_model_id: zephyr-7b-dpo-full learning_rate: 5.0e-7 log_level: info logging_steps: 10 lr_scheduler_type: linear max_length: 1024 max_prompt_length: 512 num_train_epochs: 3 optim: rmsprop output_dir: data/zephyr-7b-dpo-full per_device_train_batch_size: 8 per_device_eval_batch_size: 4 push_to_hub: true save_strategy: "no" save_total_limit: null seed: 42 warmup_ratio: 0.1
alignment-handbook/tests/fixtures/config_dpo_full.yaml/0
{ "file_path": "alignment-handbook/tests/fixtures/config_dpo_full.yaml", "repo_id": "alignment-handbook", "token_count": 329 }
14
.PHONY: clean-ptx clean test clean-ptx: find target -name "*.ptx" -type f -delete echo "" > candle-kernels/src/lib.rs touch candle-kernels/build.rs touch candle-examples/build.rs touch candle-flash-attn/build.rs clean: cargo clean test: cargo test all: test
candle/Makefile/0
{ "file_path": "candle/Makefile", "repo_id": "candle", "token_count": 107 }
15
[package] name = "candle-core" version.workspace = true edition.workspace = true description.workspace = true repository.workspace = true keywords.workspace = true categories.workspace = true license.workspace = true readme = "README.md" [dependencies] accelerate-src = { workspace = true, optional = true } byteorder = { workspace = true } candle-kernels = { workspace = true, optional = true } candle-metal-kernels = { workspace = true, optional = true } metal = { workspace = true, optional = true} cudarc = { workspace = true, optional = true } gemm = { workspace = true } half = { workspace = true } intel-mkl-src = { workspace = true, optional = true } libc = { workspace = true, optional = true } memmap2 = { workspace = true } num-traits = { workspace = true } num_cpus = { workspace = true } rand = { workspace = true } rand_distr = { workspace = true } rayon = { workspace = true } safetensors = { workspace = true } thiserror = { workspace = true } yoke = { workspace = true } zip = { workspace = true } [dev-dependencies] anyhow = { workspace = true } clap = { workspace = true } criterion = { workspace = true } [features] default = [] cuda = ["cudarc", "dep:candle-kernels"] cudnn = ["cuda", "cudarc/cudnn"] mkl = ["dep:libc", "dep:intel-mkl-src"] accelerate = ["dep:libc", "dep:accelerate-src"] metal = ["dep:metal", "dep:candle-metal-kernels"] [[bench]] name = "bench_main" harness = false
candle/candle-core/Cargo.toml/0
{ "file_path": "candle/candle-core/Cargo.toml", "repo_id": "candle", "token_count": 468 }
16
use crate::{op::BackpropOp, op::Op, Error, Result, Tensor}; #[derive(Debug, Clone, PartialEq, Eq)] pub struct ParamsConv1D { pub(crate) b_size: usize, // Maybe we should have a version without l_in as this bit depends on the input and not only on // the weights. pub(crate) l_in: usize, pub(crate) c_out: usize, pub(crate) c_in: usize, pub(crate) k_size: usize, pub(crate) padding: usize, pub(crate) stride: usize, pub(crate) dilation: usize, } impl ParamsConv1D { pub(crate) fn l_out(&self) -> usize { (self.l_in + 2 * self.padding - self.dilation * (self.k_size - 1) - 1) / self.stride + 1 } pub(crate) fn out_dims(&self) -> Vec<usize> { let l_out = self.l_out(); vec![self.b_size, self.c_out, l_out] } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct ParamsConvTranspose1D { pub(crate) b_size: usize, pub(crate) l_in: usize, pub(crate) c_out: usize, pub(crate) c_in: usize, pub(crate) k_size: usize, pub(crate) padding: usize, pub(crate) output_padding: usize, pub(crate) stride: usize, pub(crate) dilation: usize, } impl ParamsConvTranspose1D { pub(crate) fn l_out(&self) -> usize { (self.l_in - 1) * self.stride - 2 * self.padding + self.dilation * (self.k_size - 1) + self.output_padding + 1 } pub(crate) fn out_dims(&self) -> Vec<usize> { let l_out = self.l_out(); vec![self.b_size, self.c_out, l_out] } } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum CudnnFwdAlgo { ImplicitGemm, ImplicitPrecompGemm, Gemm, Direct, Fft, FftTiling, Winograd, WinogradNonFused, Count, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct ParamsConv2D { pub(crate) b_size: usize, pub(crate) i_h: usize, pub(crate) i_w: usize, pub(crate) k_h: usize, pub(crate) k_w: usize, pub(crate) c_out: usize, pub(crate) c_in: usize, pub(crate) padding: usize, pub(crate) stride: usize, pub(crate) dilation: usize, pub cudnn_fwd_algo: Option<CudnnFwdAlgo>, } impl ParamsConv2D { pub(crate) fn out_h(&self) -> usize { (self.i_h + 2 * self.padding - self.dilation * (self.k_h - 1) - 1) / self.stride + 1 } pub(crate) fn out_w(&self) -> usize { (self.i_w + 2 * self.padding - self.dilation * (self.k_w - 1) - 1) / self.stride + 1 } pub(crate) fn out_dims(&self) -> Vec<usize> { vec![self.b_size, self.c_out, self.out_h(), self.out_w()] } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct ParamsConvTranspose2D { pub(crate) b_size: usize, pub(crate) i_h: usize, pub(crate) i_w: usize, pub(crate) k_h: usize, pub(crate) k_w: usize, pub(crate) c_out: usize, pub(crate) c_in: usize, pub(crate) padding: usize, pub(crate) output_padding: usize, pub(crate) stride: usize, pub(crate) dilation: usize, } impl ParamsConvTranspose2D { pub(crate) fn out_h(&self) -> usize { (self.i_h - 1) * self.stride + self.dilation * (self.k_h - 1) + self.output_padding + 1 - 2 * self.padding } pub(crate) fn out_w(&self) -> usize { (self.i_w - 1) * self.stride + self.dilation * (self.k_w - 1) + self.output_padding + 1 - 2 * self.padding } pub(crate) fn out_dims(&self) -> Vec<usize> { vec![self.b_size, self.c_out, self.out_h(), self.out_w()] } } impl Tensor { fn conv1d_single_group(&self, kernel: &Self, params: &ParamsConv1D) -> Result<Self> { let storage = self.storage() .conv1d(self.layout(), &kernel.storage(), kernel.layout(), params)?; let op = BackpropOp::new2(self, kernel, |arg, kernel| Op::Conv1D { arg, kernel, padding: params.padding, stride: params.stride, dilation: params.dilation, }); let out_dims = params.out_dims(); Ok(crate::tensor::from_storage(storage, out_dims, op, false)) } /// Applies a 1D convolution over the input tensor. pub fn conv1d( &self, kernel: &Self, padding: usize, stride: usize, dilation: usize, groups: usize, ) -> Result<Self> { let (c_out, c_in_k, k_size) = kernel.dims3()?; let (b_size, c_in, l_in) = self.dims3()?; if c_in != c_in_k * groups { Err(Error::Conv1dInvalidArgs { inp_shape: self.shape().clone(), k_shape: kernel.shape().clone(), padding, stride, msg: "the number of in-channels on the input doesn't match the kernel size", } .bt())? } let params = ParamsConv1D { b_size, l_in, c_out: c_out / groups, c_in: c_in / groups, k_size, padding, stride, dilation, }; if groups == 1 { self.conv1d_single_group(kernel, &params) } else { let blocks = self.chunk(groups, 1)?; let kernel = kernel.chunk(groups, 0)?; let blocks = blocks .iter() .zip(&kernel) .map(|(block, kernel)| block.conv1d_single_group(kernel, &params)) .collect::<Result<Vec<_>>>()?; Tensor::cat(&blocks, 1) } } fn conv_transpose1d_single_group( &self, kernel: &Self, params: &ParamsConvTranspose1D, ) -> Result<Self> { let storage = self.storage().conv_transpose1d( self.layout(), &kernel.storage(), kernel.layout(), params, )?; let op = BackpropOp::new2(self, kernel, |arg, kernel| Op::ConvTranspose1D { arg, kernel, padding: params.padding, output_padding: params.output_padding, stride: params.stride, dilation: params.dilation, }); let out_dims = params.out_dims(); Ok(crate::tensor::from_storage(storage, out_dims, op, false)) } /// Applies a 1D transposed convolution over the input tensor. pub fn conv_transpose1d( &self, kernel: &Self, padding: usize, output_padding: usize, stride: usize, dilation: usize, groups: usize, ) -> Result<Self> { let (c_in_k, c_out, k_size) = kernel.dims3()?; let (b_size, c_in, l_in) = self.dims3()?; if c_in != c_in_k { crate::bail!("in_channel mismatch between input ({c_in}) and kernel ({c_in_k})") } if c_in % groups != 0 { crate::bail!("in_channel {c_in} is not divisible by the number of groups") } let params = ParamsConvTranspose1D { b_size, l_in, k_size, c_out, c_in: c_in / groups, padding, output_padding, stride, dilation, }; if groups == 1 { self.conv_transpose1d_single_group(kernel, &params) } else { let blocks = self.chunk(groups, 1)?; let kernel = kernel.chunk(groups, 0)?; let blocks = blocks .iter() .zip(&kernel) .map(|(block, kernel)| block.conv_transpose1d_single_group(kernel, &params)) .collect::<Result<Vec<_>>>()?; Tensor::cat(&blocks, 1) } } fn conv2d_single_group(&self, kernel: &Self, params: &ParamsConv2D) -> Result<Self> { let storage = self.storage() .conv2d(self.layout(), &kernel.storage(), kernel.layout(), params)?; let op = BackpropOp::new2(self, kernel, |arg, kernel| Op::Conv2D { arg, kernel, padding: params.padding, stride: params.stride, dilation: params.dilation, }); let out_dims = params.out_dims(); Ok(crate::tensor::from_storage(storage, out_dims, op, false)) } /// Applies a 2D convolution over the input tensor. pub fn conv2d( &self, kernel: &Self, padding: usize, stride: usize, dilation: usize, groups: usize, ) -> Result<Self> { let (b_size, c_in, i_h, i_w) = self.dims4()?; let (c_out, c_in_k, k_h, k_w) = kernel.dims4()?; if c_in != c_in_k * groups { crate::bail!( "in_channel mismatch between input ({c_in}, groups {groups}) and kernel ({c_in_k})" ) } let params = ParamsConv2D { b_size, i_h, i_w, k_h, k_w, c_out: c_out / groups, c_in: c_in / groups, padding, stride, dilation, cudnn_fwd_algo: None, }; if groups == 1 { self.conv2d_single_group(kernel, &params) } else { let blocks = self.chunk(groups, 1)?; let kernel = kernel.chunk(groups, 0)?; let blocks = blocks .iter() .zip(&kernel) .map(|(block, kernel)| block.conv2d_single_group(kernel, &params)) .collect::<Result<Vec<_>>>()?; Tensor::cat(&blocks, 1) } } /// Applies a 2D transposed convolution over the input tensor. pub fn conv_transpose2d( &self, kernel: &Self, padding: usize, output_padding: usize, stride: usize, dilation: usize, ) -> Result<Self> { let (b_size, c_in, i_h, i_w) = self.dims4()?; let (c_in_k, c_out, k_h, k_w) = kernel.dims4()?; if c_in != c_in_k { crate::bail!("in_channel mismatch between input ({c_in}) and kernel ({c_in_k})") } let params = ParamsConvTranspose2D { b_size, i_h, i_w, k_h, k_w, c_out, c_in, padding, output_padding, stride, dilation, }; let storage = self.storage().conv_transpose2d( self.layout(), &kernel.storage(), kernel.layout(), &params, )?; let op = BackpropOp::new2(self, kernel, |arg, kernel| Op::ConvTranspose2D { arg, kernel, padding: params.padding, output_padding: params.output_padding, stride: params.stride, dilation: params.dilation, }); let out_dims = params.out_dims(); Ok(crate::tensor::from_storage(storage, out_dims, op, false)) } }
candle/candle-core/src/conv.rs/0
{ "file_path": "candle/candle-core/src/conv.rs", "repo_id": "candle", "token_count": 5807 }
17
use crate::{DType, DeviceLocation, Layout, MetalError, Shape}; #[derive(Debug, Clone)] pub struct MatMulUnexpectedStriding { pub lhs_l: Layout, pub rhs_l: Layout, pub bmnk: (usize, usize, usize, usize), pub msg: &'static str, } /// Main library error type. #[derive(thiserror::Error, Debug)] pub enum Error { // === DType Errors === #[error("{msg}, expected: {expected:?}, got: {got:?}")] UnexpectedDType { msg: &'static str, expected: DType, got: DType, }, #[error("dtype mismatch in {op}, lhs: {lhs:?}, rhs: {rhs:?}")] DTypeMismatchBinaryOp { lhs: DType, rhs: DType, op: &'static str, }, #[error("unsupported dtype {0:?} for op {1}")] UnsupportedDTypeForOp(DType, &'static str), // === Dimension Index Errors === #[error("{op}: dimension index {dim} out of range for shape {shape:?}")] DimOutOfRange { shape: Shape, dim: i32, op: &'static str, }, #[error("{op}: duplicate dim index {dims:?} for shape {shape:?}")] DuplicateDimIndex { shape: Shape, dims: Vec<usize>, op: &'static str, }, // === Shape Errors === #[error("unexpected rank, expected: {expected}, got: {got} ({shape:?})")] UnexpectedNumberOfDims { expected: usize, got: usize, shape: Shape, }, #[error("{msg}, expected: {expected:?}, got: {got:?}")] UnexpectedShape { msg: String, expected: Shape, got: Shape, }, #[error( "Shape mismatch, got buffer of size {buffer_size} which is compatible with shape {shape:?}" )] ShapeMismatch { buffer_size: usize, shape: Shape }, #[error("shape mismatch in {op}, lhs: {lhs:?}, rhs: {rhs:?}")] ShapeMismatchBinaryOp { lhs: Shape, rhs: Shape, op: &'static str, }, #[error("shape mismatch in cat for dim {dim}, shape for arg 1: {first_shape:?} shape for arg {n}: {nth_shape:?}")] ShapeMismatchCat { dim: usize, first_shape: Shape, n: usize, nth_shape: Shape, }, #[error("Cannot divide tensor of shape {shape:?} equally along dim {dim} into {n_parts}")] ShapeMismatchSplit { shape: Shape, dim: usize, n_parts: usize, }, #[error("{op} can only be performed on a single dimension")] OnlySingleDimension { op: &'static str, dims: Vec<usize> }, #[error("empty tensor for {op}")] EmptyTensor { op: &'static str }, // === Device Errors === #[error("device mismatch in {op}, lhs: {lhs:?}, rhs: {rhs:?}")] DeviceMismatchBinaryOp { lhs: DeviceLocation, rhs: DeviceLocation, op: &'static str, }, // === Op Specific Errors === #[error("narrow invalid args {msg}: {shape:?}, dim: {dim}, start: {start}, len:{len}")] NarrowInvalidArgs { shape: Shape, dim: usize, start: usize, len: usize, msg: &'static str, }, #[error("conv1d invalid args {msg}: inp: {inp_shape:?}, k: {k_shape:?}, pad: {padding}, stride: {stride}")] Conv1dInvalidArgs { inp_shape: Shape, k_shape: Shape, padding: usize, stride: usize, msg: &'static str, }, #[error("{op} invalid index {index} with dim size {size}")] InvalidIndex { op: &'static str, index: usize, size: usize, }, #[error("cannot broadcast {src_shape:?} to {dst_shape:?}")] BroadcastIncompatibleShapes { src_shape: Shape, dst_shape: Shape }, #[error("cannot set variable {msg}")] CannotSetVar { msg: &'static str }, // Box indirection to avoid large variant. #[error("{0:?}")] MatMulUnexpectedStriding(Box<MatMulUnexpectedStriding>), #[error("{op} only supports contiguous tensors")] RequiresContiguous { op: &'static str }, #[error("{op} expects at least one tensor")] OpRequiresAtLeastOneTensor { op: &'static str }, #[error("{op} expects at least two tensors")] OpRequiresAtLeastTwoTensors { op: &'static str }, #[error("backward is not supported for {op}")] BackwardNotSupported { op: &'static str }, // === Other Errors === #[error("the candle crate has not been built with cuda support")] NotCompiledWithCudaSupport, #[error("the candle crate has not been built with metal support")] NotCompiledWithMetalSupport, #[error("cannot find tensor {path}")] CannotFindTensor { path: String }, // === Wrapped Errors === #[error(transparent)] Cuda(Box<dyn std::error::Error + Send + Sync>), #[error("Metal error {0}")] Metal(#[from] MetalError), #[error(transparent)] TryFromIntError(#[from] core::num::TryFromIntError), #[error("npy/npz error {0}")] Npy(String), /// Zip file format error. #[error(transparent)] Zip(#[from] zip::result::ZipError), /// Integer parse error. #[error(transparent)] ParseInt(#[from] std::num::ParseIntError), /// I/O error. #[error(transparent)] Io(#[from] std::io::Error), /// SafeTensor error. #[error(transparent)] SafeTensor(#[from] safetensors::SafeTensorError), #[error("unsupported safetensor dtype {0:?}")] UnsupportedSafeTensorDtype(safetensors::Dtype), /// Arbitrary errors wrapping. #[error(transparent)] Wrapped(Box<dyn std::error::Error + Send + Sync>), /// Adding path information to an error. #[error("path: {path:?} {inner}")] WithPath { inner: Box<Self>, path: std::path::PathBuf, }, #[error("{inner}\n{backtrace}")] WithBacktrace { inner: Box<Self>, backtrace: Box<std::backtrace::Backtrace>, }, /// User generated error message, typically created via `bail!`. #[error("{0}")] Msg(String), } pub type Result<T> = std::result::Result<T, Error>; impl Error { pub fn wrap(err: impl std::error::Error + Send + Sync + 'static) -> Self { Self::Wrapped(Box::new(err)).bt() } pub fn msg(err: impl std::error::Error + Send + Sync + 'static) -> Self { Self::Msg(err.to_string()).bt() } pub fn bt(self) -> Self { let backtrace = std::backtrace::Backtrace::capture(); match backtrace.status() { std::backtrace::BacktraceStatus::Disabled | std::backtrace::BacktraceStatus::Unsupported => self, _ => Self::WithBacktrace { inner: Box::new(self), backtrace: Box::new(backtrace), }, } } pub fn with_path<P: AsRef<std::path::Path>>(self, p: P) -> Self { Self::WithPath { inner: Box::new(self), path: p.as_ref().to_path_buf(), } } } #[macro_export] macro_rules! bail { ($msg:literal $(,)?) => { return Err($crate::Error::Msg(format!($msg).into()).bt()) }; ($err:expr $(,)?) => { return Err($crate::Error::Msg(format!($err).into()).bt()) }; ($fmt:expr, $($arg:tt)*) => { return Err($crate::Error::Msg(format!($fmt, $($arg)*).into()).bt()) }; } pub fn zip<T, U>(r1: Result<T>, r2: Result<U>) -> Result<(T, U)> { match (r1, r2) { (Ok(r1), Ok(r2)) => Ok((r1, r2)), (Err(e), _) => Err(e), (_, Err(e)) => Err(e), } }
candle/candle-core/src/error.rs/0
{ "file_path": "candle/candle-core/src/error.rs", "repo_id": "candle", "token_count": 3254 }
18
use super::{GgmlDType, QStorage}; use crate::backend::BackendStorage; use crate::{DType, MetalDevice, MetalStorage, Result, Shape}; use metal::Buffer; use std::sync::Arc; pub struct QMetalStorage { dtype: GgmlDType, device: MetalDevice, buffer: Arc<Buffer>, } impl QMetalStorage { pub fn zeros(device: &MetalDevice, elem_count: usize, dtype: GgmlDType) -> Result<Self> { let size = elem_count * dtype.type_size() / dtype.block_size(); let buffer = device.allocate_zeros(size)?; Ok(Self { buffer, device: device.clone(), dtype, }) } pub fn dtype(&self) -> GgmlDType { self.dtype } pub fn device(&self) -> &MetalDevice { &self.device } pub fn buffer(&self) -> &Buffer { &self.buffer } pub fn dequantize(&self, elem_count: usize) -> Result<MetalStorage> { use crate::quantized::k_quants::GgmlType; let buffer = self.device.new_buffer_managed(self.buffer.length())?; let command_buffer = self.device.command_buffer()?; command_buffer.set_label("to_cpu"); let blit = command_buffer.new_blit_command_encoder(); blit.set_label("blit_to_cpu"); blit.copy_from_buffer(&self.buffer, 0, &buffer, 0, self.buffer.length()); blit.end_encoding(); self.device.wait_until_completed()?; let mut out = vec![0.0; elem_count]; let block_len = elem_count / self.dtype.block_size(); match self.dtype { GgmlDType::F32 => { let vec: Vec<f32> = read_to_vec(&buffer, block_len); f32::to_float(&vec, &mut out)?; } GgmlDType::F16 => { let vec: Vec<half::f16> = read_to_vec(&buffer, block_len); half::f16::to_float(&vec, &mut out)?; } GgmlDType::Q4_0 => { let vec: Vec<crate::quantized::BlockQ4_0> = read_to_vec(&buffer, block_len); crate::quantized::BlockQ4_0::to_float(&vec, &mut out)?; } GgmlDType::Q4_1 => { let vec: Vec<crate::quantized::BlockQ4_1> = read_to_vec(&buffer, block_len); crate::quantized::BlockQ4_1::to_float(&vec, &mut out)?; } GgmlDType::Q5_0 => { let vec: Vec<crate::quantized::BlockQ5_0> = read_to_vec(&buffer, block_len); crate::quantized::BlockQ5_0::to_float(&vec, &mut out)?; } GgmlDType::Q5_1 => { let vec: Vec<crate::quantized::BlockQ5_1> = read_to_vec(&buffer, block_len); crate::quantized::BlockQ5_1::to_float(&vec, &mut out)?; } GgmlDType::Q8_0 => { let vec: Vec<crate::quantized::BlockQ8_0> = read_to_vec(&buffer, block_len); crate::quantized::BlockQ8_0::to_float(&vec, &mut out)?; } GgmlDType::Q8_1 => { let vec: Vec<crate::quantized::BlockQ8_1> = read_to_vec(&buffer, block_len); crate::quantized::BlockQ8_1::to_float(&vec, &mut out)?; } GgmlDType::Q2K => { let vec: Vec<crate::quantized::BlockQ2K> = read_to_vec(&buffer, block_len); crate::quantized::BlockQ2K::to_float(&vec, &mut out)?; } GgmlDType::Q3K => { let vec: Vec<crate::quantized::BlockQ3K> = read_to_vec(&buffer, block_len); crate::quantized::BlockQ3K::to_float(&vec, &mut out)?; } GgmlDType::Q4K => { let vec: Vec<crate::quantized::BlockQ4K> = read_to_vec(&buffer, block_len); crate::quantized::BlockQ4K::to_float(&vec, &mut out)?; } GgmlDType::Q5K => { let vec: Vec<crate::quantized::BlockQ5K> = read_to_vec(&buffer, block_len); crate::quantized::BlockQ5K::to_float(&vec, &mut out)?; } GgmlDType::Q6K => { let vec: Vec<crate::quantized::BlockQ6K> = read_to_vec(&buffer, block_len); crate::quantized::BlockQ6K::to_float(&vec, &mut out)?; } GgmlDType::Q8K => { let vec: Vec<crate::quantized::BlockQ8K> = read_to_vec(&buffer, block_len); crate::quantized::BlockQ8K::to_float(&vec, &mut out)?; } } let buffer = self.device.new_buffer_with_data(&out)?; Ok(MetalStorage::new( buffer, self.device.clone(), elem_count, DType::F32, )) } pub fn quantize(&mut self, src: &MetalStorage) -> Result<()> { // Quantization only happens on CPU for now. let src = src.to_cpu::<f32>()?; let elem_count = src.len(); let src = crate::Storage::Cpu(crate::CpuStorage::F32(src)); let mut qcpu_storage = crate::Device::Cpu.qzeros(elem_count, self.dtype)?; qcpu_storage.quantize(&src)?; let buffer = self.device.new_buffer_with_data(&qcpu_storage.data()?)?; self.buffer = buffer; Ok(()) } pub fn storage_size_in_bytes(&self) -> usize { self.buffer.length() as usize } pub fn fwd( &self, self_shape: &Shape, storage: &MetalStorage, layout: &crate::Layout, ) -> Result<(MetalStorage, Shape)> { use crate::MetalError; if !layout.is_contiguous() { crate::bail!("input tensor is not contiguous {layout:?}") } let src_shape = layout.shape(); // self is transposed so n is first then k. if src_shape.rank() < 2 { crate::bail!("input tensor has only one dimension {layout:?}") } let (n, k) = self_shape.dims2()?; let mut dst_shape = src_shape.dims().to_vec(); let (b, m) = match dst_shape.len() { 3 => (dst_shape[0], dst_shape[1]), 2 => (1, dst_shape[0]), n => crate::bail!("Invalid rank {n} for quantized matmul metal"), }; let last_k = dst_shape.pop().unwrap(); if last_k != k { crate::bail!("input tensor {layout:?} incompatible with {:?}", self_shape) } dst_shape.push(n); let dst_shape = Shape::from(dst_shape); let device = storage.device().clone(); let dst = device.new_buffer(dst_shape.elem_count(), DType::F32, "qmatmul")?; let command_buffer = device.command_buffer()?; candle_metal_kernels::call_quantized_matmul_t( device.device(), &command_buffer, device.kernels(), self.dtype.into(), (b, m, n, k), storage.buffer(), layout.start_offset() * storage.dtype().size_in_bytes(), &self.buffer, &dst, ) .map_err(MetalError::from)?; let dst_storage = crate::MetalStorage::new(dst, device, dst_shape.elem_count(), DType::F32); Ok((dst_storage, dst_shape)) } } pub fn load_quantized<T: super::GgmlType + Send + Sync + 'static>( device: &MetalDevice, data: &[T], ) -> Result<QStorage> { let buffer = device.new_buffer_with_data(data)?; let device = device.clone(); Ok(QStorage::Metal(QMetalStorage { dtype: T::DTYPE, device, buffer, })) } fn read_to_vec<T: Clone>(buffer: &Buffer, n: usize) -> Vec<T> { let ptr = buffer.contents() as *const T; assert!(!ptr.is_null()); let slice = unsafe { std::slice::from_raw_parts(ptr, n) }; slice.to_vec() } impl From<GgmlDType> for candle_metal_kernels::GgmlDType { fn from(value: GgmlDType) -> Self { match value { GgmlDType::Q4_0 => candle_metal_kernels::GgmlDType::Q4_0, GgmlDType::Q4_1 => candle_metal_kernels::GgmlDType::Q4_1, GgmlDType::Q5_0 => candle_metal_kernels::GgmlDType::Q5_0, GgmlDType::Q5_1 => candle_metal_kernels::GgmlDType::Q5_1, GgmlDType::Q8_0 => candle_metal_kernels::GgmlDType::Q8_0, GgmlDType::Q8_1 => candle_metal_kernels::GgmlDType::Q8_1, GgmlDType::Q2K => candle_metal_kernels::GgmlDType::Q2K, GgmlDType::Q3K => candle_metal_kernels::GgmlDType::Q3K, GgmlDType::Q4K => candle_metal_kernels::GgmlDType::Q4K, GgmlDType::Q5K => candle_metal_kernels::GgmlDType::Q5K, GgmlDType::Q6K => candle_metal_kernels::GgmlDType::Q6K, GgmlDType::Q8K => candle_metal_kernels::GgmlDType::Q8K, GgmlDType::F16 => candle_metal_kernels::GgmlDType::F16, GgmlDType::F32 => candle_metal_kernels::GgmlDType::F32, } } }
candle/candle-core/src/quantized/metal.rs/0
{ "file_path": "candle/candle-core/src/quantized/metal.rs", "repo_id": "candle", "token_count": 4488 }
19
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)), (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)), (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(()) }
candle/candle-core/tests/custom_op_tests.rs/0
{ "file_path": "candle/candle-core/tests/custom_op_tests.rs", "repo_id": "candle", "token_count": 1542 }
20
# candle-starcoder: code generation model [StarCoder/BigCode](https://huggingface.co/bigcode/starcoderbase-1b) is a LLM model specialized to code generation. The initial model was trained on 80 programming languages. ## Running some example ```bash cargo run --example bigcode --release -- --prompt "fn fact(n: u64) -> u64 " > fn fact(n: u64) -> u64 { > if n == 0 { > 1 > } else { > n * fact(n - 1) > } > } ```
candle/candle-examples/examples/bigcode/README.md/0
{ "file_path": "candle/candle-examples/examples/bigcode/README.md", "repo_id": "candle", "token_count": 180 }
21
//! EfficientNet implementation. //! //! https://arxiv.org/abs/1905.11946 #[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; use candle::{DType, IndexOp, D}; use candle_nn::{Module, VarBuilder}; use candle_transformers::models::efficientnet::{EfficientNet, MBConvConfig}; use clap::{Parser, ValueEnum}; #[derive(Clone, Copy, Debug, ValueEnum)] enum Which { B0, B1, B2, B3, B4, B5, B6, B7, } #[derive(Parser)] struct Args { #[arg(long)] model: Option<String>, #[arg(long)] image: String, /// Run on CPU rather than on GPU. #[arg(long)] cpu: bool, /// Variant of the model to use. #[arg(value_enum, long, default_value_t = Which::B2)] 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 api = hf_hub::api::sync::Api::new()?; let api = api.model("lmz/candle-efficientnet".into()); let filename = match args.which { Which::B0 => "efficientnet-b0.safetensors", Which::B1 => "efficientnet-b1.safetensors", Which::B2 => "efficientnet-b2.safetensors", Which::B3 => "efficientnet-b3.safetensors", Which::B4 => "efficientnet-b4.safetensors", Which::B5 => "efficientnet-b5.safetensors", Which::B6 => "efficientnet-b6.safetensors", Which::B7 => "efficientnet-b7.safetensors", }; api.get(filename)? } Some(model) => model.into(), }; let vb = unsafe { VarBuilder::from_mmaped_safetensors(&[model_file], DType::F32, &device)? }; let cfg = match args.which { Which::B0 => MBConvConfig::b0(), Which::B1 => MBConvConfig::b1(), Which::B2 => MBConvConfig::b2(), Which::B3 => MBConvConfig::b3(), Which::B4 => MBConvConfig::b4(), Which::B5 => MBConvConfig::b5(), Which::B6 => MBConvConfig::b6(), Which::B7 => MBConvConfig::b7(), }; let model = EfficientNet::new(vb, cfg, candle_examples::imagenet::CLASS_COUNT as usize)?; 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/efficientnet/main.rs/0
{ "file_path": "candle/candle-examples/examples/efficientnet/main.rs", "repo_id": "candle", "token_count": 1421 }
22
// An implementation of LLaMA https://github.com/facebookresearch/llama // // This is based on nanoGPT in a similar way to: // https://github.com/Lightning-AI/lit-llama/blob/main/lit_llama/model.py // // The tokenizer config can be retrieved from: // https://huggingface.co/hf-internal-testing/llama-tokenizer/raw/main/tokenizer.json #[cfg(feature = "mkl")] extern crate intel_mkl_src; use anyhow::{bail, Error as E, Result}; use clap::Parser; use candle::{DType, Device, Tensor}; use candle_transformers::generation::LogitsProcessor; use cudarc::driver::safe::CudaDevice; use cudarc::nccl::safe::{Comm, Id}; use hf_hub::{api::sync::Api, Repo, RepoType}; use std::io::Write; use std::rc::Rc; mod model; use model::{Config, Llama}; const MAX_SEQ_LEN: usize = 4096; const DEFAULT_PROMPT: &str = r" EDWARD: I wonder how our princely father 'scaped, Or whether he be 'scaped away or no From Clifford's and Northumberland's pursuit: Had he been ta'en, we should have heard the news; Had he been slain, we should have heard the news; Or had he 'scaped, methinks we should have heard The happy tidings of his good escape. How fares my brother? why is he so sad? RICHARD: I cannot joy, until I be resolved Where our right valiant father is become. I saw him in the battle range about; And watch'd him how he singled Clifford forth. Methought he bore him in the thickest troop As doth a lion in a herd of neat; Or as a bear, encompass'd round with dogs, Who having pinch'd a few and made them cry, The rest stand all aloof, and bark at him. So fared our father with his enemies; So fled his enemies my warlike father: Methinks, 'tis prize enough to be his son. See how the morning opes her golden gates, And takes her farewell of the glorious sun! How well resembles it the prime of youth, Trimm'd like a younker prancing to his love! EDWARD: Dazzle mine eyes, or do I see three suns? RICHARD: Three glorious suns, each one a perfect sun; Not separated with the racking clouds, But sever'd in a pale clear-shining sky. See, see! they join, embrace, and seem to kiss, As if they vow'd some league inviolable: Now are they but one lamp, one light, one sun. In this the heaven figures some event. EDWARD: 'Tis wondrous strange, the like yet never heard of. I think it cites us, brother, to the field, That we, the sons of brave Plantagenet, Each one already blazing by our meeds, Should notwithstanding join our lights together And over-shine the earth as this the world. Whate'er it bodes, henceforward will I bear Upon my target three fair-shining suns. "; #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] struct Args { #[arg(long)] num_shards: usize, #[arg(long)] rank: Option<usize>, /// The temperature used to generate samples. #[arg(long)] temperature: Option<f64>, /// Nucleus sampling probability cutoff. #[arg(long)] top_p: Option<f64>, /// The seed to use when generating random samples. #[arg(long, default_value_t = 299792458)] seed: u64, /// The length of the sample to generate (in tokens). #[arg(long, default_value_t = 100)] sample_len: usize, /// Disable the key-value cache. #[arg(long)] no_kv_cache: bool, /// The initial prompt. #[arg(long)] prompt: Option<String>, #[arg(long)] model_id: Option<String>, #[arg(long)] revision: Option<String>, #[arg(long)] dtype: Option<String>, } fn main() -> Result<()> { use tokenizers::Tokenizer; let args = Args::parse(); let dtype = match args.dtype.as_deref() { Some("f16") => DType::F16, Some("bf16") => DType::BF16, Some("f32") => DType::F32, Some(dtype) => bail!("Unsupported dtype {dtype}"), None => DType::F16, }; let api = Api::new()?; let model_id = args .model_id .unwrap_or_else(|| "meta-llama/Llama-2-7b-hf".to_string()); println!("loading the model weights from {model_id}"); let revision = args.revision.unwrap_or("main".to_string()); let api = api.repo(Repo::with_revision(model_id, RepoType::Model, revision)); let config_filename = api.get("config.json")?; let config: Config = serde_json::from_slice(&std::fs::read(config_filename)?)?; let tokenizer_filename = api.get("tokenizer.json")?; let filenames = candle_examples::hub_load_safetensors(&api, "model.safetensors.index.json")?; if args.rank.is_none() { let children: Vec<_> = (0..args.num_shards) .map(|rank| { let mut args: std::collections::VecDeque<_> = std::env::args().collect(); args.push_back("--rank".to_string()); args.push_back(format!("{rank}")); let name = args.pop_front().unwrap(); std::process::Command::new(name).args(args).spawn().unwrap() }) .collect(); for mut child in children { child.wait().unwrap(); } return Ok(()); } let i = args.rank.unwrap(); let num_shards = args.num_shards; let rank = i; // Primitive IPC let id = if rank == 0 { let id = Id::new().unwrap(); std::fs::File::create("nccl_id.txt.tmp")? .write_all(&id.internal().iter().map(|&i| i as u8).collect::<Vec<_>>()) .unwrap(); std::fs::rename("nccl_id.txt.tmp", "nccl_id.txt")?; id } else { let path = std::path::PathBuf::from("nccl_id.txt"); while !path.exists() { std::thread::sleep(std::time::Duration::from_secs(1)); } let data = std::fs::read("nccl_id.txt")?; let internal: [i8; 128] = data .into_iter() .map(|i| i as i8) .collect::<Vec<_>>() .try_into() .unwrap(); let id: Id = Id::uninit(internal); id }; let device = CudaDevice::new(i)?; let comm = Rc::new(Comm::from_rank(device, i, num_shards, id).unwrap()); if rank == 0 { std::fs::remove_file("nccl_id.txt")?; } println!("Rank {rank:?} spawned"); let device = Device::new_cuda(i)?; let cache = model::Cache::new(dtype, &config, &device)?; println!("building the model"); let vb = unsafe { candle_nn::var_builder::ShardedSafeTensors::var_builder(&filenames, dtype, &device)? }; let llama = Llama::load(vb, &cache, &config, comm)?; let tokenizer = Tokenizer::from_file(tokenizer_filename).map_err(E::msg)?; let prompt = args.prompt.as_ref().map_or(DEFAULT_PROMPT, |p| p.as_str()); let mut tokens = tokenizer .encode(prompt, true) .map_err(E::msg)? .get_ids() .to_vec(); println!("starting the inference loop"); let mut logits_processor = LogitsProcessor::new(args.seed, args.temperature, args.top_p); let mut new_tokens = vec![]; let start_gen = std::time::Instant::now(); let mut index_pos = 0; for index in 0..args.sample_len { let start_gen = std::time::Instant::now(); let context_size = if index > 0 { 1 } else { tokens.len() }; let ctxt = &tokens[tokens.len().saturating_sub(context_size)..]; let input = Tensor::new(ctxt, &device)?.unsqueeze(0)?; let logits = llama.forward(&input, index_pos)?; let logits = logits.squeeze(0)?; index_pos += ctxt.len(); let next_token = logits_processor.sample(&logits)?; tokens.push(next_token); new_tokens.push(next_token); if rank == 0 { println!("> {:?}", start_gen.elapsed()); println!( "{} token: {} '{}'", index + 1, next_token, tokenizer.decode(&[next_token], true).map_err(E::msg)? ); } } let dt = start_gen.elapsed(); if rank == 0 { println!( "{} tokens generated ({} token/s)\n----\n{}\n----", args.sample_len, args.sample_len as f64 / dt.as_secs_f64(), tokenizer .decode(new_tokens.as_slice(), true) .map_err(E::msg)? ); } Ok(()) }
candle/candle-examples/examples/llama_multiprocess/main.rs/0
{ "file_path": "candle/candle-examples/examples/llama_multiprocess/main.rs", "repo_id": "candle", "token_count": 3470 }
23
// This should reach 91.5% accuracy. #[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; use clap::{Parser, ValueEnum}; use rand::prelude::*; use candle::{DType, Result, Tensor, D}; use candle_nn::{loss, ops, Conv2d, Linear, Module, ModuleT, Optimizer, VarBuilder, VarMap}; const IMAGE_DIM: usize = 784; const LABELS: usize = 10; fn linear_z(in_dim: usize, out_dim: usize, vs: VarBuilder) -> Result<Linear> { let ws = vs.get_with_hints((out_dim, in_dim), "weight", candle_nn::init::ZERO)?; let bs = vs.get_with_hints(out_dim, "bias", candle_nn::init::ZERO)?; Ok(Linear::new(ws, Some(bs))) } trait Model: Sized { fn new(vs: VarBuilder) -> Result<Self>; fn forward(&self, xs: &Tensor) -> Result<Tensor>; } struct LinearModel { linear: Linear, } impl Model for LinearModel { fn new(vs: VarBuilder) -> Result<Self> { let linear = linear_z(IMAGE_DIM, LABELS, vs)?; Ok(Self { linear }) } fn forward(&self, xs: &Tensor) -> Result<Tensor> { self.linear.forward(xs) } } struct Mlp { ln1: Linear, ln2: Linear, } impl Model for Mlp { fn new(vs: VarBuilder) -> Result<Self> { let ln1 = candle_nn::linear(IMAGE_DIM, 100, vs.pp("ln1"))?; let ln2 = candle_nn::linear(100, LABELS, vs.pp("ln2"))?; Ok(Self { ln1, ln2 }) } fn forward(&self, xs: &Tensor) -> Result<Tensor> { let xs = self.ln1.forward(xs)?; let xs = xs.relu()?; self.ln2.forward(&xs) } } #[derive(Debug)] struct ConvNet { conv1: Conv2d, conv2: Conv2d, fc1: Linear, fc2: Linear, dropout: candle_nn::Dropout, } impl ConvNet { fn new(vs: VarBuilder) -> Result<Self> { let conv1 = candle_nn::conv2d(1, 32, 5, Default::default(), vs.pp("c1"))?; let conv2 = candle_nn::conv2d(32, 64, 5, Default::default(), vs.pp("c2"))?; let fc1 = candle_nn::linear(1024, 1024, vs.pp("fc1"))?; let fc2 = candle_nn::linear(1024, LABELS, vs.pp("fc2"))?; let dropout = candle_nn::Dropout::new(0.5); Ok(Self { conv1, conv2, fc1, fc2, dropout, }) } fn forward(&self, xs: &Tensor, train: bool) -> Result<Tensor> { let (b_sz, _img_dim) = xs.dims2()?; let xs = xs .reshape((b_sz, 1, 28, 28))? .apply(&self.conv1)? .max_pool2d(2)? .apply(&self.conv2)? .max_pool2d(2)? .flatten_from(1)? .apply(&self.fc1)? .relu()?; self.dropout.forward_t(&xs, train)?.apply(&self.fc2) } } struct TrainingArgs { learning_rate: f64, load: Option<String>, save: Option<String>, epochs: usize, } fn training_loop_cnn( m: candle_datasets::vision::Dataset, args: &TrainingArgs, ) -> anyhow::Result<()> { const BSIZE: usize = 64; let dev = candle::Device::cuda_if_available(0)?; let train_labels = m.train_labels; let train_images = m.train_images.to_device(&dev)?; let train_labels = train_labels.to_dtype(DType::U32)?.to_device(&dev)?; let mut varmap = VarMap::new(); let vs = VarBuilder::from_varmap(&varmap, DType::F32, &dev); let model = ConvNet::new(vs.clone())?; if let Some(load) = &args.load { println!("loading weights from {load}"); varmap.load(load)? } let adamw_params = candle_nn::ParamsAdamW { lr: args.learning_rate, ..Default::default() }; let mut opt = candle_nn::AdamW::new(varmap.all_vars(), adamw_params)?; let test_images = m.test_images.to_device(&dev)?; let test_labels = m.test_labels.to_dtype(DType::U32)?.to_device(&dev)?; let n_batches = train_images.dim(0)? / BSIZE; let mut batch_idxs = (0..n_batches).collect::<Vec<usize>>(); for epoch in 1..args.epochs { let mut sum_loss = 0f32; batch_idxs.shuffle(&mut thread_rng()); for batch_idx in batch_idxs.iter() { let train_images = train_images.narrow(0, batch_idx * BSIZE, BSIZE)?; let train_labels = train_labels.narrow(0, batch_idx * BSIZE, BSIZE)?; let logits = model.forward(&train_images, true)?; let log_sm = ops::log_softmax(&logits, D::Minus1)?; let loss = loss::nll(&log_sm, &train_labels)?; opt.backward_step(&loss)?; sum_loss += loss.to_vec0::<f32>()?; } let avg_loss = sum_loss / n_batches as f32; let test_logits = model.forward(&test_images, false)?; let sum_ok = test_logits .argmax(D::Minus1)? .eq(&test_labels)? .to_dtype(DType::F32)? .sum_all()? .to_scalar::<f32>()?; let test_accuracy = sum_ok / test_labels.dims1()? as f32; println!( "{epoch:4} train loss {:8.5} test acc: {:5.2}%", avg_loss, 100. * test_accuracy ); } if let Some(save) = &args.save { println!("saving trained weights in {save}"); varmap.save(save)? } Ok(()) } fn training_loop<M: Model>( m: candle_datasets::vision::Dataset, args: &TrainingArgs, ) -> anyhow::Result<()> { let dev = candle::Device::cuda_if_available(0)?; let train_labels = m.train_labels; let train_images = m.train_images.to_device(&dev)?; let train_labels = train_labels.to_dtype(DType::U32)?.to_device(&dev)?; let mut varmap = VarMap::new(); let vs = VarBuilder::from_varmap(&varmap, DType::F32, &dev); let model = M::new(vs.clone())?; if let Some(load) = &args.load { println!("loading weights from {load}"); varmap.load(load)? } let mut sgd = candle_nn::SGD::new(varmap.all_vars(), args.learning_rate)?; let test_images = m.test_images.to_device(&dev)?; let test_labels = m.test_labels.to_dtype(DType::U32)?.to_device(&dev)?; for epoch in 1..args.epochs { let logits = model.forward(&train_images)?; let log_sm = ops::log_softmax(&logits, D::Minus1)?; let loss = loss::nll(&log_sm, &train_labels)?; sgd.backward_step(&loss)?; let test_logits = model.forward(&test_images)?; let sum_ok = test_logits .argmax(D::Minus1)? .eq(&test_labels)? .to_dtype(DType::F32)? .sum_all()? .to_scalar::<f32>()?; let test_accuracy = sum_ok / test_labels.dims1()? as f32; println!( "{epoch:4} train loss: {:8.5} test acc: {:5.2}%", loss.to_scalar::<f32>()?, 100. * test_accuracy ); } if let Some(save) = &args.save { println!("saving trained weights in {save}"); varmap.save(save)? } Ok(()) } #[derive(ValueEnum, Clone)] enum WhichModel { Linear, Mlp, Cnn, } #[derive(Parser)] struct Args { #[clap(value_enum, default_value_t = WhichModel::Linear)] model: WhichModel, #[arg(long)] learning_rate: Option<f64>, #[arg(long, default_value_t = 200)] epochs: usize, /// The file where to save the trained weights, in safetensors format. #[arg(long)] save: Option<String>, /// The file where to load the trained weights from, in safetensors format. #[arg(long)] load: Option<String>, /// The directory where to load the dataset from, in ubyte format. #[arg(long)] local_mnist: Option<String>, } pub fn main() -> anyhow::Result<()> { let args = Args::parse(); // Load the dataset let m = if let Some(directory) = args.local_mnist { candle_datasets::vision::mnist::load_dir(directory)? } else { candle_datasets::vision::mnist::load()? }; println!("train-images: {:?}", m.train_images.shape()); println!("train-labels: {:?}", m.train_labels.shape()); println!("test-images: {:?}", m.test_images.shape()); println!("test-labels: {:?}", m.test_labels.shape()); let default_learning_rate = match args.model { WhichModel::Linear => 1., WhichModel::Mlp => 0.05, WhichModel::Cnn => 0.001, }; let training_args = TrainingArgs { epochs: args.epochs, learning_rate: args.learning_rate.unwrap_or(default_learning_rate), load: args.load, save: args.save, }; match args.model { WhichModel::Linear => training_loop::<LinearModel>(m, &training_args), WhichModel::Mlp => training_loop::<Mlp>(m, &training_args), WhichModel::Cnn => training_loop_cnn(m, &training_args), } }
candle/candle-examples/examples/mnist-training/main.rs/0
{ "file_path": "candle/candle-examples/examples/mnist-training/main.rs", "repo_id": "candle", "token_count": 4094 }
24
# candle-reinforcement-learning Reinforcement Learning examples for candle. This has been tested with `gymnasium` version `0.29.1`. You can install the Python package with: ```bash pip install "gymnasium[accept-rom-license]" ``` In order to run the examples, use the following commands. Note the additional `--package` flag to ensure that there is no conflict with the `candle-pyo3` crate. For the Policy Gradient example: ```bash cargo run --example reinforcement-learning --features=pyo3 --package candle-examples -- pg ``` For the Deep Deterministic Policy Gradient example: ```bash cargo run --example reinforcement-learning --features=pyo3 --package candle-examples -- ddpg ```
candle/candle-examples/examples/reinforcement-learning/README.md/0
{ "file_path": "candle/candle-examples/examples/reinforcement-learning/README.md", "repo_id": "candle", "token_count": 198 }
25
#[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; use anyhow::Result; use clap::{Parser, ValueEnum}; use candle_transformers::models::quantized_rwkv_v5::Model as Q5; use candle_transformers::models::quantized_rwkv_v6::Model as Q6; use candle_transformers::models::rwkv_v5::{Config, Model as M5, State, Tokenizer}; use candle_transformers::models::rwkv_v6::Model as M6; use candle::{DType, Device, Tensor}; use candle_nn::VarBuilder; use candle_transformers::generation::LogitsProcessor; use hf_hub::{api::sync::Api, Repo, RepoType}; const EOS_TOKEN_ID: u32 = 261; enum Model { M5(M5), Q5(Q5), M6(M6), Q6(Q6), } impl Model { fn forward(&self, xs: &Tensor, state: &mut State) -> candle::Result<Tensor> { match self { Self::M5(m) => m.forward(xs, state), Self::Q5(m) => m.forward(xs, state), Self::M6(m) => m.forward(xs, state), Self::Q6(m) => m.forward(xs, state), } } } struct TextGeneration { model: Model, config: Config, device: Device, tokenizer: Tokenizer, logits_processor: LogitsProcessor, repeat_penalty: f32, repeat_last_n: usize, } impl TextGeneration { #[allow(clippy::too_many_arguments)] fn new( model: Model, config: Config, 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, config, 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; let mut tokens = self.tokenizer.encode(prompt)?; let mut generated_tokens = 0usize; let mut state = State::new(1, &self.config, &self.device)?; let mut next_logits = None; for &t in tokens.iter() { let input = Tensor::new(&[[t]], &self.device)?; let logits = self.model.forward(&input, &mut state)?; next_logits = Some(logits); print!("{}", self.tokenizer.decode(&[t])?) } std::io::stdout().flush()?; let start_gen = std::time::Instant::now(); for _ in 0..sample_len { let logits = match next_logits.as_ref() { Some(logits) => logits, None => anyhow::bail!("cannot work on an empty prompt"), }; 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_ID || next_token == 0 { break; } print!("{}", self.tokenizer.decode(&[next_token])?); std::io::stdout().flush()?; let input = Tensor::new(&[[next_token]], &self.device)?; next_logits = Some(self.model.forward(&input, &mut state)?) } let dt = start_gen.elapsed(); println!( "\n{generated_tokens} tokens generated ({:.2} token/s)", generated_tokens as f64 / dt.as_secs_f64(), ); Ok(()) } } #[derive(Parser, ValueEnum, Clone, Copy, PartialEq, Eq, Debug)] enum Which { Eagle7b, World1b5, World3b, World6_1b6, } impl std::fmt::Display for Which { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:?}", self) } } impl Which { fn model_id(&self) -> &'static str { match self { Self::Eagle7b => "RWKV/v5-Eagle-7B-HF", Self::World1b5 => "RWKV/rwkv-5-world-1b5", Self::World3b => "RWKV/rwkv-5-world-3b", Self::World6_1b6 => "paperfun/rwkv", } } fn revision(&self) -> &'static str { match self { Self::Eagle7b => "refs/pr/1", Self::World1b5 | Self::World3b => "refs/pr/2", Self::World6_1b6 => "main", } } } #[derive(Parser, Debug)] #[command(author, version, about, long_about = None)] struct Args { /// Run on CPU rather than on GPU. #[arg(long)] cpu: bool, /// Enable tracing (generates a trace-timestamp.json file). #[arg(long)] tracing: bool, #[arg(long)] prompt: String, /// The temperature used to generate samples. #[arg(long)] temperature: Option<f64>, /// Nucleus sampling probability cutoff. #[arg(long)] top_p: Option<f64>, /// The seed to use when generating random samples. #[arg(long, default_value_t = 299792458)] seed: u64, /// The length of the sample to generate (in tokens). #[arg(long, short = 'n', default_value_t = 5000)] sample_len: usize, #[arg(long, default_value = "world1b5")] which: Which, #[arg(long)] model_id: Option<String>, #[arg(long)] revision: Option<String>, #[arg(long)] tokenizer: Option<String>, #[arg(long)] weight_files: Option<String>, #[arg(long)] config_file: Option<String>, #[arg(long)] quantized: bool, /// Penalty to be applied for repeating tokens, 1. means no penalty. #[arg(long, default_value_t = 1.1)] repeat_penalty: f32, /// The context size to consider for the repeat penalty. #[arg(long, default_value_t = 64)] repeat_last_n: usize, } fn main() -> Result<()> { use tracing_chrome::ChromeLayerBuilder; use tracing_subscriber::prelude::*; let args = Args::parse(); let _guard = if args.tracing { let (chrome_layer, guard) = ChromeLayerBuilder::new().build(); tracing_subscriber::registry().with(chrome_layer).init(); Some(guard) } else { None }; println!( "avx: {}, neon: {}, simd128: {}, f16c: {}", candle::utils::with_avx(), candle::utils::with_neon(), candle::utils::with_simd128(), candle::utils::with_f16c() ); println!( "temp: {:.2} repeat-penalty: {:.2} repeat-last-n: {}", args.temperature.unwrap_or(0.), args.repeat_penalty, args.repeat_last_n ); let start = std::time::Instant::now(); let api = Api::new()?; let repo = api.repo(Repo::with_revision( args.model_id .unwrap_or_else(|| args.which.model_id().to_string()), RepoType::Model, args.revision .unwrap_or_else(|| args.which.revision().to_string()), )); let tokenizer = match args.tokenizer { Some(file) => std::path::PathBuf::from(file), None => api .model("lmz/candle-rwkv".to_string()) .get("rwkv_vocab_v20230424.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 => { if args.quantized { vec![match args.which { Which::World1b5 => api .model("lmz/candle-rwkv".to_string()) .get("world1b5-q4k.gguf")?, Which::World3b => api .model("lmz/candle-rwkv".to_string()) .get("world3b-q4k.gguf")?, Which::Eagle7b => api .model("lmz/candle-rwkv".to_string()) .get("eagle7b-q4k.gguf")?, Which::World6_1b6 => repo.get("rwkv-6-world-1b6-q4k.gguf")?, }] } else { vec![match args.which { Which::World1b5 | Which::World3b | Which::Eagle7b => { repo.get("model.safetensors")? } Which::World6_1b6 => repo.get("rwkv-6-world-1b6.safetensors")?, }] } } }; println!("retrieved the files in {:?}", start.elapsed()); let tokenizer = Tokenizer::new(tokenizer)?; let start = std::time::Instant::now(); let config: Config = serde_json::from_slice(&std::fs::read(config_filename)?)?; let device = candle_examples::device(args.cpu)?; let model = if args.quantized { let filename = &filenames[0]; let vb = candle_transformers::quantized_var_builder::VarBuilder::from_gguf(filename, &device)?; match args.which { Which::World1b5 | Which::World3b | Which::Eagle7b => Model::Q5(Q5::new(&config, vb)?), Which::World6_1b6 => Model::Q6(Q6::new(&config, vb)?), } } else { let vb = unsafe { VarBuilder::from_mmaped_safetensors(&filenames, DType::F32, &device)? }; match args.which { Which::World1b5 | Which::World3b | Which::Eagle7b => Model::M5(M5::new(&config, vb)?), Which::World6_1b6 => Model::M6(M6::new(&config, vb)?), } }; println!("loaded the model in {:?}", start.elapsed()); let mut pipeline = TextGeneration::new( model, config, tokenizer, args.seed, args.temperature, args.top_p, args.repeat_penalty, args.repeat_last_n, &device, ); pipeline.run(&args.prompt, args.sample_len)?; Ok(()) }
candle/candle-examples/examples/rwkv/main.rs/0
{ "file_path": "candle/candle-examples/examples/rwkv/main.rs", "repo_id": "candle", "token_count": 5059 }
26
#[cfg(feature = "mkl")] extern crate intel_mkl_src; #[cfg(feature = "accelerate")] extern crate accelerate_src; use std::io::Write; use std::path::PathBuf; use candle_transformers::models::t5; use anyhow::{Error as E, Result}; use candle::{DType, Device, Tensor}; use candle_nn::VarBuilder; use candle_transformers::generation::LogitsProcessor; use clap::Parser; use hf_hub::{api::sync::Api, Repo, RepoType}; use tokenizers::Tokenizer; const DTYPE: DType = DType::F32; #[derive(Parser, Debug, Clone)] #[command(author, version, about, long_about = None)] struct Args { /// Run on CPU rather than on GPU. #[arg(long)] cpu: bool, /// Enable tracing (generates a trace-timestamp.json file). #[arg(long)] tracing: bool, /// The model repository to use on the HuggingFace hub. #[arg(long)] model_id: Option<String>, #[arg(long)] revision: Option<String>, /// Enable decoding. #[arg(long)] decode: bool, // Enable/disable decoding. #[arg(long, default_value = "false")] disable_cache: bool, /// Use this prompt, otherwise compute sentence similarities. #[arg(long)] prompt: Option<String>, /// If set along with --decode, will use this prompt to initialize the decoder. #[arg(long)] decoder_prompt: Option<String>, /// L2 normalization for embeddings. #[arg(long, default_value = "true")] normalize_embeddings: bool, /// The temperature used to generate samples. #[arg(long, default_value_t = 0.8)] temperature: f64, /// Nucleus sampling probability cutoff. #[arg(long)] top_p: Option<f64>, /// 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, } struct T5ModelBuilder { device: Device, config: t5::Config, weights_filename: Vec<PathBuf>, } impl T5ModelBuilder { pub fn load(args: &Args) -> Result<(Self, Tokenizer)> { let device = candle_examples::device(args.cpu)?; let default_model = "t5-small".to_string(); let default_revision = "refs/pr/15".to_string(); let (model_id, revision) = match (args.model_id.to_owned(), args.revision.to_owned()) { (Some(model_id), Some(revision)) => (model_id, revision), (Some(model_id), None) => (model_id, "main".to_string()), (None, Some(revision)) => (default_model, revision), (None, None) => (default_model, default_revision), }; let repo = Repo::with_revision(model_id.clone(), RepoType::Model, revision); let api = Api::new()?; let api = api.repo(repo); let config_filename = api.get("config.json")?; let tokenizer_filename = api.get("tokenizer.json")?; let weights_filename = if model_id == "google/flan-t5-xxl" || model_id == "google/flan-ul2" { candle_examples::hub_load_safetensors(&api, "model.safetensors.index.json")? } else { vec![api.get("model.safetensors")?] }; let config = std::fs::read_to_string(config_filename)?; let mut config: t5::Config = serde_json::from_str(&config)?; config.use_cache = !args.disable_cache; let tokenizer = Tokenizer::from_file(tokenizer_filename).map_err(E::msg)?; Ok(( Self { device, config, weights_filename, }, tokenizer, )) } pub fn build_encoder(&self) -> Result<t5::T5EncoderModel> { let vb = unsafe { VarBuilder::from_mmaped_safetensors(&self.weights_filename, DTYPE, &self.device)? }; Ok(t5::T5EncoderModel::load(vb, &self.config)?) } pub fn build_conditional_generation(&self) -> Result<t5::T5ForConditionalGeneration> { let vb = unsafe { VarBuilder::from_mmaped_safetensors(&self.weights_filename, DTYPE, &self.device)? }; Ok(t5::T5ForConditionalGeneration::load(vb, &self.config)?) } } 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 }; let (builder, mut tokenizer) = T5ModelBuilder::load(&args)?; let device = &builder.device; let tokenizer = tokenizer .with_padding(None) .with_truncation(None) .map_err(E::msg)?; match args.prompt { Some(prompt) => { let tokens = tokenizer .encode(prompt, true) .map_err(E::msg)? .get_ids() .to_vec(); let input_token_ids = Tensor::new(&tokens[..], device)?.unsqueeze(0)?; if !args.decode { let mut model = builder.build_encoder()?; let start = std::time::Instant::now(); let ys = model.forward(&input_token_ids)?; println!("{ys}"); println!("Took {:?}", start.elapsed()); } else { let mut model = builder.build_conditional_generation()?; let mut output_token_ids = [builder .config .decoder_start_token_id .unwrap_or(builder.config.pad_token_id) as u32] .to_vec(); if let Some(decoder_prompt) = &args.decoder_prompt { print!("{decoder_prompt}"); output_token_ids.extend( tokenizer .encode(decoder_prompt.to_string(), false) .map_err(E::msg)? .get_ids() .to_vec(), ); } let temperature = if args.temperature <= 0. { None } else { Some(args.temperature) }; let mut logits_processor = LogitsProcessor::new(299792458, temperature, args.top_p); let encoder_output = model.encode(&input_token_ids)?; let start = std::time::Instant::now(); for index in 0.. { if output_token_ids.len() > 512 { break; } let decoder_token_ids = if index == 0 || !builder.config.use_cache { Tensor::new(output_token_ids.as_slice(), device)?.unsqueeze(0)? } else { let last_token = *output_token_ids.last().unwrap(); Tensor::new(&[last_token], device)?.unsqueeze(0)? }; let logits = model .decode(&decoder_token_ids, &encoder_output)? .squeeze(0)?; let logits = if args.repeat_penalty == 1. { logits } else { let start_at = output_token_ids.len().saturating_sub(args.repeat_last_n); candle_transformers::utils::apply_repeat_penalty( &logits, args.repeat_penalty, &output_token_ids[start_at..], )? }; let next_token_id = logits_processor.sample(&logits)?; if next_token_id as usize == builder.config.eos_token_id { break; } output_token_ids.push(next_token_id); if let Some(text) = tokenizer.id_to_token(next_token_id) { let text = text.replace('▁', " ").replace("<0x0A>", "\n"); print!("{text}"); std::io::stdout().flush()?; } } let dt = start.elapsed(); println!( "\n{} tokens generated ({:.2} token/s)\n", output_token_ids.len(), output_token_ids.len() as f64 / dt.as_secs_f64(), ); } } None => { let mut model = builder.build_encoder()?; let sentences = [ "The cat sits outside", "A man is playing guitar", "I love pasta", "The new movie is awesome", "The cat plays in the garden", "A woman watches TV", "The new movie is so great", "Do you like pizza?", ]; let n_sentences = sentences.len(); let mut all_embeddings = Vec::with_capacity(n_sentences); for sentence in sentences { let tokens = tokenizer .encode(sentence, true) .map_err(E::msg)? .get_ids() .to_vec(); let token_ids = Tensor::new(&tokens[..], model.device())?.unsqueeze(0)?; let embeddings = model.forward(&token_ids)?; println!("generated embeddings {:?}", embeddings.shape()); // Apply some avg-pooling by taking the mean embedding value for all tokens (including padding) let (_n_sentence, n_tokens, _hidden_size) = embeddings.dims3()?; let embeddings = (embeddings.sum(1)? / (n_tokens as f64))?; let embeddings = if args.normalize_embeddings { normalize_l2(&embeddings)? } else { embeddings }; println!("pooled embeddings {:?}", embeddings.shape()); all_embeddings.push(embeddings) } let mut similarities = vec![]; for (i, e_i) in all_embeddings.iter().enumerate() { for (j, e_j) in all_embeddings .iter() .enumerate() .take(n_sentences) .skip(i + 1) { let sum_ij = (e_i * e_j)?.sum_all()?.to_scalar::<f32>()?; let sum_i2 = (e_i * e_i)?.sum_all()?.to_scalar::<f32>()?; let sum_j2 = (e_j * e_j)?.sum_all()?.to_scalar::<f32>()?; let cosine_similarity = sum_ij / (sum_i2 * sum_j2).sqrt(); similarities.push((cosine_similarity, i, j)) } } similarities.sort_by(|u, v| v.0.total_cmp(&u.0)); for &(score, i, j) in similarities[..5].iter() { println!("score: {score:.2} '{}' '{}'", sentences[i], sentences[j]) } } } Ok(()) } pub fn normalize_l2(v: &Tensor) -> Result<Tensor> { Ok(v.broadcast_div(&v.sqr()?.sum_keepdim(1)?.sqrt()?)?) }
candle/candle-examples/examples/t5/main.rs/0
{ "file_path": "candle/candle-examples/examples/t5/main.rs", "repo_id": "candle", "token_count": 5920 }
27
use candle::{DType, IndexOp, Result, Tensor, D}; use candle_nn::{batch_norm, conv2d, conv2d_no_bias, Conv2d, Conv2dConfig, Module, VarBuilder}; #[derive(Clone, Copy, PartialEq, Debug)] pub struct Multiples { depth: f64, width: f64, ratio: f64, } impl Multiples { pub fn n() -> Self { Self { depth: 0.33, width: 0.25, ratio: 2.0, } } pub fn s() -> Self { Self { depth: 0.33, width: 0.50, ratio: 2.0, } } pub fn m() -> Self { Self { depth: 0.67, width: 0.75, ratio: 1.5, } } pub fn l() -> Self { Self { depth: 1.00, width: 1.00, ratio: 1.0, } } pub fn x() -> Self { Self { depth: 1.00, width: 1.25, ratio: 1.0, } } fn filters(&self) -> (usize, usize, usize) { let f1 = (256. * self.width) as usize; let f2 = (512. * self.width) as usize; let f3 = (512. * self.width * self.ratio) as usize; (f1, f2, f3) } } #[derive(Debug)] struct Upsample { scale_factor: usize, } impl Upsample { fn new(scale_factor: usize) -> Result<Self> { Ok(Upsample { scale_factor }) } } impl Module for Upsample { fn forward(&self, xs: &Tensor) -> candle::Result<Tensor> { let (_b_size, _channels, h, w) = xs.dims4()?; xs.upsample_nearest2d(self.scale_factor * h, self.scale_factor * w) } } #[derive(Debug)] struct ConvBlock { conv: Conv2d, span: tracing::Span, } impl ConvBlock { fn load( vb: VarBuilder, c1: usize, c2: usize, k: usize, stride: usize, padding: Option<usize>, ) -> Result<Self> { let padding = padding.unwrap_or(k / 2); let cfg = Conv2dConfig { padding, stride, groups: 1, dilation: 1, }; let bn = batch_norm(c2, 1e-3, vb.pp("bn"))?; let conv = conv2d_no_bias(c1, c2, k, cfg, vb.pp("conv"))?.absorb_bn(&bn)?; Ok(Self { conv, span: tracing::span!(tracing::Level::TRACE, "conv-block"), }) } } impl Module for ConvBlock { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let xs = self.conv.forward(xs)?; candle_nn::ops::silu(&xs) } } #[derive(Debug)] struct Bottleneck { cv1: ConvBlock, cv2: ConvBlock, residual: bool, span: tracing::Span, } impl Bottleneck { fn load(vb: VarBuilder, c1: usize, c2: usize, shortcut: bool) -> Result<Self> { let channel_factor = 1.; let c_ = (c2 as f64 * channel_factor) as usize; let cv1 = ConvBlock::load(vb.pp("cv1"), c1, c_, 3, 1, None)?; let cv2 = ConvBlock::load(vb.pp("cv2"), c_, c2, 3, 1, None)?; let residual = c1 == c2 && shortcut; Ok(Self { cv1, cv2, residual, span: tracing::span!(tracing::Level::TRACE, "bottleneck"), }) } } impl Module for Bottleneck { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let ys = self.cv2.forward(&self.cv1.forward(xs)?)?; if self.residual { xs + ys } else { Ok(ys) } } } #[derive(Debug)] struct C2f { cv1: ConvBlock, cv2: ConvBlock, bottleneck: Vec<Bottleneck>, span: tracing::Span, } impl C2f { fn load(vb: VarBuilder, c1: usize, c2: usize, n: usize, shortcut: bool) -> Result<Self> { let c = (c2 as f64 * 0.5) as usize; let cv1 = ConvBlock::load(vb.pp("cv1"), c1, 2 * c, 1, 1, None)?; let cv2 = ConvBlock::load(vb.pp("cv2"), (2 + n) * c, c2, 1, 1, None)?; let mut bottleneck = Vec::with_capacity(n); for idx in 0..n { let b = Bottleneck::load(vb.pp(&format!("bottleneck.{idx}")), c, c, shortcut)?; bottleneck.push(b) } Ok(Self { cv1, cv2, bottleneck, span: tracing::span!(tracing::Level::TRACE, "c2f"), }) } } impl Module for C2f { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let ys = self.cv1.forward(xs)?; let mut ys = ys.chunk(2, 1)?; for m in self.bottleneck.iter() { ys.push(m.forward(ys.last().unwrap())?) } let zs = Tensor::cat(ys.as_slice(), 1)?; self.cv2.forward(&zs) } } #[derive(Debug)] struct Sppf { cv1: ConvBlock, cv2: ConvBlock, k: usize, span: tracing::Span, } impl Sppf { fn load(vb: VarBuilder, c1: usize, c2: usize, k: usize) -> Result<Self> { let c_ = c1 / 2; let cv1 = ConvBlock::load(vb.pp("cv1"), c1, c_, 1, 1, None)?; let cv2 = ConvBlock::load(vb.pp("cv2"), c_ * 4, c2, 1, 1, None)?; Ok(Self { cv1, cv2, k, span: tracing::span!(tracing::Level::TRACE, "sppf"), }) } } impl Module for Sppf { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let (_, _, _, _) = xs.dims4()?; let xs = self.cv1.forward(xs)?; let xs2 = xs .pad_with_zeros(2, self.k / 2, self.k / 2)? .pad_with_zeros(3, self.k / 2, self.k / 2)? .max_pool2d_with_stride(self.k, 1)?; let xs3 = xs2 .pad_with_zeros(2, self.k / 2, self.k / 2)? .pad_with_zeros(3, self.k / 2, self.k / 2)? .max_pool2d_with_stride(self.k, 1)?; let xs4 = xs3 .pad_with_zeros(2, self.k / 2, self.k / 2)? .pad_with_zeros(3, self.k / 2, self.k / 2)? .max_pool2d_with_stride(self.k, 1)?; self.cv2.forward(&Tensor::cat(&[&xs, &xs2, &xs3, &xs4], 1)?) } } #[derive(Debug)] struct Dfl { conv: Conv2d, num_classes: usize, span: tracing::Span, } impl Dfl { fn load(vb: VarBuilder, num_classes: usize) -> Result<Self> { let conv = conv2d_no_bias(num_classes, 1, 1, Default::default(), vb.pp("conv"))?; Ok(Self { conv, num_classes, span: tracing::span!(tracing::Level::TRACE, "dfl"), }) } } impl Module for Dfl { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let (b_sz, _channels, anchors) = xs.dims3()?; let xs = xs .reshape((b_sz, 4, self.num_classes, anchors))? .transpose(2, 1)?; let xs = candle_nn::ops::softmax(&xs, 1)?; self.conv.forward(&xs)?.reshape((b_sz, 4, anchors)) } } #[derive(Debug)] struct DarkNet { b1_0: ConvBlock, b1_1: ConvBlock, b2_0: C2f, b2_1: ConvBlock, b2_2: C2f, b3_0: ConvBlock, b3_1: C2f, b4_0: ConvBlock, b4_1: C2f, b5: Sppf, span: tracing::Span, } impl DarkNet { fn load(vb: VarBuilder, m: Multiples) -> Result<Self> { let (w, r, d) = (m.width, m.ratio, m.depth); let b1_0 = ConvBlock::load(vb.pp("b1.0"), 3, (64. * w) as usize, 3, 2, Some(1))?; let b1_1 = ConvBlock::load( vb.pp("b1.1"), (64. * w) as usize, (128. * w) as usize, 3, 2, Some(1), )?; let b2_0 = C2f::load( vb.pp("b2.0"), (128. * w) as usize, (128. * w) as usize, (3. * d).round() as usize, true, )?; let b2_1 = ConvBlock::load( vb.pp("b2.1"), (128. * w) as usize, (256. * w) as usize, 3, 2, Some(1), )?; let b2_2 = C2f::load( vb.pp("b2.2"), (256. * w) as usize, (256. * w) as usize, (6. * d).round() as usize, true, )?; let b3_0 = ConvBlock::load( vb.pp("b3.0"), (256. * w) as usize, (512. * w) as usize, 3, 2, Some(1), )?; let b3_1 = C2f::load( vb.pp("b3.1"), (512. * w) as usize, (512. * w) as usize, (6. * d).round() as usize, true, )?; let b4_0 = ConvBlock::load( vb.pp("b4.0"), (512. * w) as usize, (512. * w * r) as usize, 3, 2, Some(1), )?; let b4_1 = C2f::load( vb.pp("b4.1"), (512. * w * r) as usize, (512. * w * r) as usize, (3. * d).round() as usize, true, )?; let b5 = Sppf::load( vb.pp("b5.0"), (512. * w * r) as usize, (512. * w * r) as usize, 5, )?; Ok(Self { b1_0, b1_1, b2_0, b2_1, b2_2, b3_0, b3_1, b4_0, b4_1, b5, span: tracing::span!(tracing::Level::TRACE, "darknet"), }) } fn forward(&self, xs: &Tensor) -> Result<(Tensor, Tensor, Tensor)> { let _enter = self.span.enter(); let x1 = self.b1_1.forward(&self.b1_0.forward(xs)?)?; let x2 = self .b2_2 .forward(&self.b2_1.forward(&self.b2_0.forward(&x1)?)?)?; let x3 = self.b3_1.forward(&self.b3_0.forward(&x2)?)?; let x4 = self.b4_1.forward(&self.b4_0.forward(&x3)?)?; let x5 = self.b5.forward(&x4)?; Ok((x2, x3, x5)) } } #[derive(Debug)] struct YoloV8Neck { up: Upsample, n1: C2f, n2: C2f, n3: ConvBlock, n4: C2f, n5: ConvBlock, n6: C2f, span: tracing::Span, } impl YoloV8Neck { fn load(vb: VarBuilder, m: Multiples) -> Result<Self> { let up = Upsample::new(2)?; let (w, r, d) = (m.width, m.ratio, m.depth); let n = (3. * d).round() as usize; let n1 = C2f::load( vb.pp("n1"), (512. * w * (1. + r)) as usize, (512. * w) as usize, n, false, )?; let n2 = C2f::load( vb.pp("n2"), (768. * w) as usize, (256. * w) as usize, n, false, )?; let n3 = ConvBlock::load( vb.pp("n3"), (256. * w) as usize, (256. * w) as usize, 3, 2, Some(1), )?; let n4 = C2f::load( vb.pp("n4"), (768. * w) as usize, (512. * w) as usize, n, false, )?; let n5 = ConvBlock::load( vb.pp("n5"), (512. * w) as usize, (512. * w) as usize, 3, 2, Some(1), )?; let n6 = C2f::load( vb.pp("n6"), (512. * w * (1. + r)) as usize, (512. * w * r) as usize, n, false, )?; Ok(Self { up, n1, n2, n3, n4, n5, n6, span: tracing::span!(tracing::Level::TRACE, "neck"), }) } fn forward(&self, p3: &Tensor, p4: &Tensor, p5: &Tensor) -> Result<(Tensor, Tensor, Tensor)> { let _enter = self.span.enter(); let x = self .n1 .forward(&Tensor::cat(&[&self.up.forward(p5)?, p4], 1)?)?; let head_1 = self .n2 .forward(&Tensor::cat(&[&self.up.forward(&x)?, p3], 1)?)?; let head_2 = self .n4 .forward(&Tensor::cat(&[&self.n3.forward(&head_1)?, &x], 1)?)?; let head_3 = self .n6 .forward(&Tensor::cat(&[&self.n5.forward(&head_2)?, p5], 1)?)?; Ok((head_1, head_2, head_3)) } } #[derive(Debug)] struct DetectionHead { dfl: Dfl, cv2: [(ConvBlock, ConvBlock, Conv2d); 3], cv3: [(ConvBlock, ConvBlock, Conv2d); 3], ch: usize, no: usize, span: tracing::Span, } #[derive(Debug)] struct PoseHead { detect: DetectionHead, cv4: [(ConvBlock, ConvBlock, Conv2d); 3], kpt: (usize, usize), span: tracing::Span, } fn make_anchors( xs0: &Tensor, xs1: &Tensor, xs2: &Tensor, (s0, s1, s2): (usize, usize, usize), grid_cell_offset: f64, ) -> Result<(Tensor, Tensor)> { let dev = xs0.device(); let mut anchor_points = vec![]; let mut stride_tensor = vec![]; for (xs, stride) in [(xs0, s0), (xs1, s1), (xs2, s2)] { // xs is only used to extract the h and w dimensions. let (_, _, h, w) = xs.dims4()?; let sx = (Tensor::arange(0, w as u32, dev)?.to_dtype(DType::F32)? + grid_cell_offset)?; let sy = (Tensor::arange(0, h as u32, dev)?.to_dtype(DType::F32)? + grid_cell_offset)?; let sx = sx .reshape((1, sx.elem_count()))? .repeat((h, 1))? .flatten_all()?; let sy = sy .reshape((sy.elem_count(), 1))? .repeat((1, w))? .flatten_all()?; anchor_points.push(Tensor::stack(&[&sx, &sy], D::Minus1)?); stride_tensor.push((Tensor::ones(h * w, DType::F32, dev)? * stride as f64)?); } let anchor_points = Tensor::cat(anchor_points.as_slice(), 0)?; let stride_tensor = Tensor::cat(stride_tensor.as_slice(), 0)?.unsqueeze(1)?; Ok((anchor_points, stride_tensor)) } fn dist2bbox(distance: &Tensor, anchor_points: &Tensor) -> Result<Tensor> { let chunks = distance.chunk(2, 1)?; let lt = &chunks[0]; let rb = &chunks[1]; let x1y1 = anchor_points.sub(lt)?; let x2y2 = anchor_points.add(rb)?; let c_xy = ((&x1y1 + &x2y2)? * 0.5)?; let wh = (&x2y2 - &x1y1)?; Tensor::cat(&[c_xy, wh], 1) } struct DetectionHeadOut { pred: Tensor, anchors: Tensor, strides: Tensor, } impl DetectionHead { fn load(vb: VarBuilder, nc: usize, filters: (usize, usize, usize)) -> Result<Self> { let ch = 16; let dfl = Dfl::load(vb.pp("dfl"), ch)?; let c1 = usize::max(filters.0, nc); let c2 = usize::max(filters.0 / 4, ch * 4); let cv3 = [ Self::load_cv3(vb.pp("cv3.0"), c1, nc, filters.0)?, Self::load_cv3(vb.pp("cv3.1"), c1, nc, filters.1)?, Self::load_cv3(vb.pp("cv3.2"), c1, nc, filters.2)?, ]; let cv2 = [ Self::load_cv2(vb.pp("cv2.0"), c2, ch, filters.0)?, Self::load_cv2(vb.pp("cv2.1"), c2, ch, filters.1)?, Self::load_cv2(vb.pp("cv2.2"), c2, ch, filters.2)?, ]; let no = nc + ch * 4; Ok(Self { dfl, cv2, cv3, ch, no, span: tracing::span!(tracing::Level::TRACE, "detection-head"), }) } fn load_cv3( vb: VarBuilder, c1: usize, nc: usize, filter: usize, ) -> Result<(ConvBlock, ConvBlock, Conv2d)> { let block0 = ConvBlock::load(vb.pp("0"), filter, c1, 3, 1, None)?; let block1 = ConvBlock::load(vb.pp("1"), c1, c1, 3, 1, None)?; let conv = conv2d(c1, nc, 1, Default::default(), vb.pp("2"))?; Ok((block0, block1, conv)) } fn load_cv2( vb: VarBuilder, c2: usize, ch: usize, filter: usize, ) -> Result<(ConvBlock, ConvBlock, Conv2d)> { let block0 = ConvBlock::load(vb.pp("0"), filter, c2, 3, 1, None)?; let block1 = ConvBlock::load(vb.pp("1"), c2, c2, 3, 1, None)?; let conv = conv2d(c2, 4 * ch, 1, Default::default(), vb.pp("2"))?; Ok((block0, block1, conv)) } fn forward(&self, xs0: &Tensor, xs1: &Tensor, xs2: &Tensor) -> Result<DetectionHeadOut> { let _enter = self.span.enter(); let forward_cv = |xs, i: usize| { let xs_2 = self.cv2[i].0.forward(xs)?; let xs_2 = self.cv2[i].1.forward(&xs_2)?; let xs_2 = self.cv2[i].2.forward(&xs_2)?; let xs_3 = self.cv3[i].0.forward(xs)?; let xs_3 = self.cv3[i].1.forward(&xs_3)?; let xs_3 = self.cv3[i].2.forward(&xs_3)?; Tensor::cat(&[&xs_2, &xs_3], 1) }; let xs0 = forward_cv(xs0, 0)?; let xs1 = forward_cv(xs1, 1)?; let xs2 = forward_cv(xs2, 2)?; let (anchors, strides) = make_anchors(&xs0, &xs1, &xs2, (8, 16, 32), 0.5)?; let anchors = anchors.transpose(0, 1)?.unsqueeze(0)?; let strides = strides.transpose(0, 1)?; let reshape = |xs: &Tensor| { let d = xs.dim(0)?; let el = xs.elem_count(); xs.reshape((d, self.no, el / (d * self.no))) }; let ys0 = reshape(&xs0)?; let ys1 = reshape(&xs1)?; let ys2 = reshape(&xs2)?; let x_cat = Tensor::cat(&[ys0, ys1, ys2], 2)?; let box_ = x_cat.i((.., ..self.ch * 4))?; let cls = x_cat.i((.., self.ch * 4..))?; let dbox = dist2bbox(&self.dfl.forward(&box_)?, &anchors)?; let dbox = dbox.broadcast_mul(&strides)?; let pred = Tensor::cat(&[dbox, candle_nn::ops::sigmoid(&cls)?], 1)?; Ok(DetectionHeadOut { pred, anchors, strides, }) } } impl PoseHead { // kpt: keypoints, (17, 3) // nc: num-classes, 80 fn load( vb: VarBuilder, nc: usize, kpt: (usize, usize), filters: (usize, usize, usize), ) -> Result<Self> { let detect = DetectionHead::load(vb.clone(), nc, filters)?; let nk = kpt.0 * kpt.1; let c4 = usize::max(filters.0 / 4, nk); let cv4 = [ Self::load_cv4(vb.pp("cv4.0"), c4, nk, filters.0)?, Self::load_cv4(vb.pp("cv4.1"), c4, nk, filters.1)?, Self::load_cv4(vb.pp("cv4.2"), c4, nk, filters.2)?, ]; Ok(Self { detect, cv4, kpt, span: tracing::span!(tracing::Level::TRACE, "pose-head"), }) } fn load_cv4( vb: VarBuilder, c1: usize, nc: usize, filter: usize, ) -> Result<(ConvBlock, ConvBlock, Conv2d)> { let block0 = ConvBlock::load(vb.pp("0"), filter, c1, 3, 1, None)?; let block1 = ConvBlock::load(vb.pp("1"), c1, c1, 3, 1, None)?; let conv = conv2d(c1, nc, 1, Default::default(), vb.pp("2"))?; Ok((block0, block1, conv)) } fn forward(&self, xs0: &Tensor, xs1: &Tensor, xs2: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let d = self.detect.forward(xs0, xs1, xs2)?; let forward_cv = |xs: &Tensor, i: usize| { let (b_sz, _, h, w) = xs.dims4()?; let xs = self.cv4[i].0.forward(xs)?; let xs = self.cv4[i].1.forward(&xs)?; let xs = self.cv4[i].2.forward(&xs)?; xs.reshape((b_sz, self.kpt.0 * self.kpt.1, h * w)) }; let xs0 = forward_cv(xs0, 0)?; let xs1 = forward_cv(xs1, 1)?; let xs2 = forward_cv(xs2, 2)?; let xs = Tensor::cat(&[xs0, xs1, xs2], D::Minus1)?; let (b_sz, _nk, hw) = xs.dims3()?; let xs = xs.reshape((b_sz, self.kpt.0, self.kpt.1, hw))?; let ys01 = ((xs.i((.., .., 0..2))? * 2.)?.broadcast_add(&d.anchors)? - 0.5)? .broadcast_mul(&d.strides)?; let ys2 = candle_nn::ops::sigmoid(&xs.i((.., .., 2..3))?)?; let ys = Tensor::cat(&[ys01, ys2], 2)?.flatten(1, 2)?; Tensor::cat(&[d.pred, ys], 1) } } #[derive(Debug)] pub struct YoloV8 { net: DarkNet, fpn: YoloV8Neck, head: DetectionHead, span: tracing::Span, } impl YoloV8 { pub fn load(vb: VarBuilder, m: Multiples, num_classes: usize) -> Result<Self> { let net = DarkNet::load(vb.pp("net"), m)?; let fpn = YoloV8Neck::load(vb.pp("fpn"), m)?; let head = DetectionHead::load(vb.pp("head"), num_classes, m.filters())?; Ok(Self { net, fpn, head, span: tracing::span!(tracing::Level::TRACE, "yolo-v8"), }) } } impl Module for YoloV8 { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let (xs1, xs2, xs3) = self.net.forward(xs)?; let (xs1, xs2, xs3) = self.fpn.forward(&xs1, &xs2, &xs3)?; Ok(self.head.forward(&xs1, &xs2, &xs3)?.pred) } } #[derive(Debug)] pub struct YoloV8Pose { net: DarkNet, fpn: YoloV8Neck, head: PoseHead, span: tracing::Span, } impl YoloV8Pose { pub fn load( vb: VarBuilder, m: Multiples, num_classes: usize, kpt: (usize, usize), ) -> Result<Self> { let net = DarkNet::load(vb.pp("net"), m)?; let fpn = YoloV8Neck::load(vb.pp("fpn"), m)?; let head = PoseHead::load(vb.pp("head"), num_classes, kpt, m.filters())?; Ok(Self { net, fpn, head, span: tracing::span!(tracing::Level::TRACE, "yolo-v8-pose"), }) } } impl Module for YoloV8Pose { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let (xs1, xs2, xs3) = self.net.forward(xs)?; let (xs1, xs2, xs3) = self.fpn.forward(&xs1, &xs2, &xs3)?; self.head.forward(&xs1, &xs2, &xs3) } }
candle/candle-examples/examples/yolo-v8/model.rs/0
{ "file_path": "candle/candle-examples/examples/yolo-v8/model.rs", "repo_id": "candle", "token_count": 12422 }
28
/****************************************************************************** * Copyright (c) 2023, Tri Dao. ******************************************************************************/ #pragma once #include <cute/algorithm/copy.hpp> #include <cutlass/cutlass.h> #include <cutlass/array.h> #include <cutlass/numeric_types.h> #include "block_info.h" #include "kernel_traits.h" #include "utils.h" #include "softmax.h" #include "alibi.h" namespace flash { using namespace cute; //////////////////////////////////////////////////////////////////////////////////////////////////// template<bool Is_first, bool Check_inf=false, typename Tensor0, typename Tensor1, typename Tensor2> inline __device__ void softmax_rescale_o(Tensor0 &scores, Tensor1 &scores_max, Tensor1 &scores_sum, Tensor2 &acc_o, float softmax_scale_log2) { if (Is_first) { flash::template reduce_max</*zero_init=*/true>(scores, scores_max); flash::scale_apply_exp2(scores, scores_max, softmax_scale_log2); flash::reduce_sum(scores, scores_sum); } else { Tensor scores_max_prev = make_fragment_like(scores_max); cute::copy(scores_max, scores_max_prev); flash::template reduce_max</*zero_init=*/false>(scores, scores_max); // Reshape acc_o from (MMA=4, MMA_M, MMA_K) to (nrow=(2, MMA_M), ncol=(2, MMA_K)) Tensor acc_o_rowcol = make_tensor(acc_o.data(), flash::convert_layout_acc_rowcol(acc_o.layout())); #pragma unroll for (int mi = 0; mi < size(scores_max); ++mi) { float scores_max_cur = !Check_inf ? scores_max(mi) : (scores_max(mi) == -INFINITY ? 0.0f : scores_max(mi)); float scores_scale = exp2f((scores_max_prev(mi) - scores_max_cur) * softmax_scale_log2); scores_sum(mi) *= scores_scale; #pragma unroll for (int ni = 0; ni < size<1>(acc_o_rowcol); ++ni) { acc_o_rowcol(mi, ni) *= scores_scale; } } flash::scale_apply_exp2(scores, scores_max, softmax_scale_log2); Tensor scores_sum_cur = make_fragment_like(scores_sum); flash::reduce_sum(scores, scores_sum_cur); #pragma unroll for (int mi = 0; mi < size(scores_sum); ++mi) { scores_sum(mi) += scores_sum_cur(mi); } } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<typename Engine0, typename Layout0, typename Engine1, typename Layout1, typename TiledCopy> inline __device__ void write_softmax_to_gmem( Tensor<Engine0, Layout0> const &tOrP, Tensor<Engine1, Layout1> &tPgP, TiledCopy gmem_tiled_copy_P ) { // Reshape tOrP from (8, MMA_M, MMA_N) to (8, MMA_M * MMA_N) Layout l = tOrP.layout(); Tensor tPrP = make_tensor(tOrP.data(), make_layout(get<0>(l), make_layout(get<1>(l), get<2>(l)))); CUTE_STATIC_ASSERT_V(size<2>(tPgP) == _1{}); CUTE_STATIC_ASSERT_V(size<1>(tPrP) == size<1>(tPgP)); #pragma unroll for (int mi = 0; mi < size<1>(tPrP); ++mi) { cute::copy(gmem_tiled_copy_P, tPrP(_, mi), tPgP(_, mi, 0)); } }; //////////////////////////////////////////////////////////////////////////////////////////////////// template<typename Kernel_traits, bool Is_dropout, bool Is_causal, bool Is_local, bool Has_alibi, bool Is_even_MN, bool Is_even_K, bool Return_softmax, typename Params> inline __device__ void compute_attn_1rowblock(const Params &params, const int bidb, const int bidh, const int m_block) { using Element = typename Kernel_traits::Element; using ElementAccum = typename Kernel_traits::ElementAccum; using index_t = typename Kernel_traits::index_t; // Shared memory. extern __shared__ char smem_[]; // The thread index. const int tidx = threadIdx.x; constexpr int kBlockM = Kernel_traits::kBlockM; constexpr int kBlockN = Kernel_traits::kBlockN; constexpr int kHeadDim = Kernel_traits::kHeadDim; constexpr int kNWarps = Kernel_traits::kNWarps; constexpr int MMA_M = kBlockM / decltype(size<0>(typename Kernel_traits::TiledMma::TiledShape_MNK{}))::value; const BlockInfo</*Varlen=*/!Is_even_MN> binfo(params, bidb); if (m_block * kBlockM >= binfo.actual_seqlen_q) return; const int n_block_min = !Is_local ? 0 : std::max(0, (m_block * kBlockM + binfo.actual_seqlen_k - binfo.actual_seqlen_q - params.window_size_left) / kBlockN); int n_block_max = cute::ceil_div(binfo.actual_seqlen_k, kBlockN); if (Is_causal || Is_local) { n_block_max = std::min(n_block_max, cute::ceil_div((m_block + 1) * kBlockM + binfo.actual_seqlen_k - binfo.actual_seqlen_q + params.window_size_right, kBlockN)); // if (threadIdx.x == 0 && blockIdx.y == 0 && blockIdx.z == 0) { // printf("m_block = %d, n_block_max = %d\n", m_block, n_block_max); // } } // We exit early and write 0 to gO and gLSE. This also covers the case where actual_seqlen_k == 0. // Otherwise we might read OOB elements from gK and gV. if ((Is_causal || Is_local || !Is_even_MN) && n_block_max <= n_block_min) { // Save seed and offset for backward. If we don't have this here, the 0-th thread block might // exit early and no one saves the rng state. // if (Is_dropout && blockIdx.x == 0 && blockIdx.y == 0 && blockIdx.z == 0 && tidx == 0) { // auto seeds = at::cuda::philox::unpack(params.philox_args); // params.rng_state[0] = std::get<0>(seeds); // params.rng_state[1] = std::get<1>(seeds); // params.rng_state[0] = 0; // params.rng_state[1] = 0; // } const index_t row_offset_o = binfo.q_offset(params.o_batch_stride, params.o_row_stride, bidb) + m_block * kBlockM * params.o_row_stride + bidh * params.o_head_stride; const index_t row_offset_lse = (bidb * params.h + bidh) * params.seqlen_q + m_block * kBlockM; Tensor gO = make_tensor(make_gmem_ptr(reinterpret_cast<Element *>(params.o_ptr) + row_offset_o), Shape<Int<kBlockM>, Int<kHeadDim>>{}, make_stride(params.o_row_stride, _1{})); Tensor gLSE = make_tensor(make_gmem_ptr(reinterpret_cast<ElementAccum *>(params.softmax_lse_ptr) + row_offset_lse), Shape<Int<kBlockM>>{}, Stride<_1>{}); typename Kernel_traits::GmemTiledCopyO gmem_tiled_copy_O; auto gmem_thr_copy_O = gmem_tiled_copy_O.get_thread_slice(tidx); Tensor tOgO = gmem_thr_copy_O.partition_D(gO); Tensor tOrO = make_tensor<Element>(shape(tOgO)); clear(tOrO); // Construct identity layout for sO Tensor cO = make_identity_tensor(make_shape(size<0>(gO), size<1>(gO))); // (BLK_M,BLK_K) -> (blk_m,blk_k) // Repeat the partitioning with identity layouts Tensor tOcO = gmem_thr_copy_O.partition_D(cO); Tensor tOpO = make_tensor<bool>(make_shape(size<2>(tOgO))); if (!Is_even_K) { #pragma unroll for (int k = 0; k < size(tOpO); ++k) { tOpO(k) = get<1>(tOcO(0, 0, k)) < params.d; } } // Clear_OOB_K must be false since we don't want to write zeros to gmem flash::copy<Is_even_MN, Is_even_K, /*Clear_OOB_MN=*/false, /*Clear_OOB_K=*/false>( gmem_tiled_copy_O, tOrO, tOgO, tOcO, tOpO, binfo.actual_seqlen_q - m_block * kBlockM ); #pragma unroll for (int m = 0; m < size<1>(tOgO); ++m) { const int row = get<0>(tOcO(0, m, 0)); if (row < binfo.actual_seqlen_q - m_block * kBlockM && get<1>(tOcO(0, m, 0)) == 0) { gLSE(row) = INFINITY; } } return; } // if (tidx == 0) { printf("m_block = %d, n_block_min = %d, n_block_max = %d\n", m_block, n_block_min, n_block_max); } // We iterate over the blocks in reverse order. This is because the last block is the only one // that needs masking when we read K and V from global memory. Moreover, iterating in reverse // might save us 1 register (we just need n_block instead of both n_block and n_block_max). const index_t row_offset_q = binfo.q_offset(params.q_batch_stride, params.q_row_stride, bidb) + m_block * kBlockM * params.q_row_stride + bidh * params.q_head_stride; // We move K and V to the last block. const index_t row_offset_k = binfo.k_offset(params.k_batch_stride, params.k_row_stride, bidb) + (n_block_max - 1) * kBlockN * params.k_row_stride + (bidh / params.h_h_k_ratio) * params.k_head_stride; const index_t row_offset_v = binfo.k_offset(params.v_batch_stride, params.v_row_stride, bidb) + (n_block_max - 1) * kBlockN * params.v_row_stride + (bidh / params.h_h_k_ratio) * params.v_head_stride; const index_t row_offset_p = ((bidb * params.h + bidh) * params.seqlen_q_rounded + m_block * kBlockM) * params.seqlen_k_rounded + (n_block_max - 1) * kBlockN; Tensor gQ = make_tensor(make_gmem_ptr(reinterpret_cast<Element *>(params.q_ptr) + row_offset_q), Shape<Int<kBlockM>, Int<kHeadDim>>{}, make_stride(params.q_row_stride, _1{})); Tensor gK = make_tensor(make_gmem_ptr(reinterpret_cast<Element *>(params.k_ptr) + row_offset_k), Shape<Int<kBlockN>, Int<kHeadDim>>{}, make_stride(params.k_row_stride, _1{})); Tensor gV = make_tensor(make_gmem_ptr(reinterpret_cast<Element *>(params.v_ptr) + row_offset_v), Shape<Int<kBlockN>, Int<kHeadDim>>{}, make_stride(params.v_row_stride, _1{})); Tensor gP = make_tensor(make_gmem_ptr(reinterpret_cast<Element *>(params.p_ptr) + row_offset_p), Shape<Int<kBlockM>, Int<kBlockN>>{}, make_stride(params.seqlen_k_rounded, _1{})); Tensor sQ = make_tensor(make_smem_ptr(reinterpret_cast<Element *>(smem_)), typename Kernel_traits::SmemLayoutQ{}); // Careful we're using the same smem for sQ and sK | sV if Share_Q_K_smem; Tensor sK = make_tensor(sQ.data() + (Kernel_traits::Share_Q_K_smem ? 0 : size(sQ)), typename Kernel_traits::SmemLayoutKV{}); Tensor sV = make_tensor(sK.data() + size(sK), typename Kernel_traits::SmemLayoutKV{}); Tensor sVt = make_tensor(sV.data(), typename Kernel_traits::SmemLayoutVtransposed{}); Tensor sVtNoSwizzle = make_tensor(sV.data(), typename Kernel_traits::SmemLayoutVtransposedNoSwizzle{}); typename Kernel_traits::GmemTiledCopyQKV gmem_tiled_copy_QKV; auto gmem_thr_copy_QKV = gmem_tiled_copy_QKV.get_thread_slice(tidx); typename Kernel_traits::GmemTiledCopyP gmem_tiled_copy_P; auto gmem_thr_copy_P = gmem_tiled_copy_P.get_thread_slice(tidx); Tensor tQgQ = gmem_thr_copy_QKV.partition_S(gQ); Tensor tQsQ = gmem_thr_copy_QKV.partition_D(sQ); Tensor tKgK = gmem_thr_copy_QKV.partition_S(gK); // (KCPY, KCPY_N, KCPY_K) Tensor tKsK = gmem_thr_copy_QKV.partition_D(sK); Tensor tVgV = gmem_thr_copy_QKV.partition_S(gV); // (VCPY, VCPY_N, VCPY_K) Tensor tVsV = gmem_thr_copy_QKV.partition_D(sV); Tensor tPgP = gmem_thr_copy_P.partition_D(gP); typename Kernel_traits::TiledMma tiled_mma; auto thr_mma = tiled_mma.get_thread_slice(tidx); Tensor tSrQ = thr_mma.partition_fragment_A(sQ); // (MMA,MMA_M,MMA_K) Tensor tSrK = thr_mma.partition_fragment_B(sK); // (MMA,MMA_N,MMA_K) Tensor tOrVt = thr_mma.partition_fragment_B(sVtNoSwizzle); // (MMA, MMA_K,MMA_N) Tensor acc_o = partition_fragment_C(tiled_mma, Shape<Int<kBlockM>, Int<kHeadDim>>{}); // MMA, MMA_M, MMA_K // // Copy Atom retiling // auto smem_tiled_copy_Q = make_tiled_copy_A(typename Kernel_traits::SmemCopyAtom{}, tiled_mma); auto smem_thr_copy_Q = smem_tiled_copy_Q.get_thread_slice(tidx); // if (cute::thread0()) {smem_thr_copy_Q.print_all();} Tensor tSsQ = smem_thr_copy_Q.partition_S(sQ); // if (cute::thread0()) {print(tSsQ.layout()); printf("\n");} auto smem_tiled_copy_K = make_tiled_copy_B(typename Kernel_traits::SmemCopyAtom{}, tiled_mma); auto smem_thr_copy_K = smem_tiled_copy_K.get_thread_slice(tidx); Tensor tSsK = smem_thr_copy_K.partition_S(sK); auto smem_tiled_copy_V = make_tiled_copy_B(typename Kernel_traits::SmemCopyAtomTransposed{}, tiled_mma); auto smem_thr_copy_V = smem_tiled_copy_V.get_thread_slice(tidx); Tensor tOsVt = smem_thr_copy_V.partition_S(sVt); // TODO: this might need to change if we change the mma instruction in SM70 Tensor scores_max = make_tensor<ElementAccum>(Shape<Int<2 * size<1>(acc_o)>>{}); Tensor scores_sum = make_fragment_like(scores_max); // // PREDICATES // // // Allocate predicate tensors for m and n // Tensor tQpQ = make_tensor<bool>(make_shape(size<1>(tQsQ), size<2>(tQsQ)), Stride<_1,_0>{}); // Tensor tKVpKV = make_tensor<bool>(make_shape(size<1>(tKsK), size<2>(tKsK)), Stride<_1,_0>{}); // Construct identity layout for sQ and sK Tensor cQ = make_identity_tensor(make_shape(size<0>(sQ), size<1>(sQ))); // (BLK_M,BLK_K) -> (blk_m,blk_k) Tensor cKV = make_identity_tensor(make_shape(size<0>(sK), size<1>(sK))); // (BLK_N,BLK_K) -> (blk_n,blk_k) // Tensor tScQ = thr_mma.partition_A(cQ); // (MMA,MMA_M,MMA_K) // if (cute::thread0()) { // print(tScQ.layout()); printf("\n"); // for (int i = 0; i < size(tScQ); ++i) { // printf("%d ", get<0>(tScQ(i))); // } // printf("\n"); // for (int i = 0; i < size(tScQ); ++i) { // printf("%d ", get<1>(tScQ(i))); // } // printf("\n"); // } // Repeat the partitioning with identity layouts Tensor tQcQ = gmem_thr_copy_QKV.partition_S(cQ); // (ACPY,ACPY_M,ACPY_K) -> (blk_m,blk_k) Tensor tKVcKV = gmem_thr_copy_QKV.partition_S(cKV); // (BCPY,BCPY_N,BCPY_K) -> (blk_n,blk_k) // Allocate predicate tensors for k Tensor tQpQ = make_tensor<bool>(make_shape(size<2>(tQsQ))); Tensor tKVpKV = make_tensor<bool>(make_shape(size<2>(tKsK))); // Set predicates for k bounds if (!Is_even_K) { #pragma unroll for (int k = 0; k < size(tQpQ); ++k) { tQpQ(k) = get<1>(tQcQ(0, 0, k)) < params.d; } #pragma unroll for (int k = 0; k < size(tKVpKV); ++k) { tKVpKV(k) = get<1>(tKVcKV(0, 0, k)) < params.d; } } // Prologue Tensor tQrQ = make_fragment_like(tQgQ); // We don't need to clear the sQ smem tiles since we'll only write out the valid outputs flash::copy<Is_even_MN, Is_even_K>(gmem_tiled_copy_QKV, tQgQ, tQsQ, tQcQ, tQpQ, binfo.actual_seqlen_q - m_block * kBlockM); if (Kernel_traits::Is_Q_in_regs) { cute::cp_async_fence(); } // // Copy rmem to smem // // copy(tQrQ, tQsQ); // flash::cp_async_wait<0>(); // __syncthreads(); // // if (cute::thread(1, 0)) { print(tQsQ); } // // Tensor sQNoSwizzle = make_tensor(make_smem_ptr(reinterpret_cast<Element *>(smem_)), typename Kernel_traits::SmemLayoutQNoSwizzle{}); // // if (cute::thread0()) { print(sQNoSwizzle); } if (Kernel_traits::Share_Q_K_smem) { flash::cp_async_wait<0>(); __syncthreads(); Tensor tSrQ_copy_view = smem_thr_copy_Q.retile_D(tSrQ); CUTE_STATIC_ASSERT_V(size<1>(tSsQ) == size<1>(tSrQ_copy_view)); // M cute::copy(smem_tiled_copy_Q, tSsQ, tSrQ_copy_view); __syncthreads(); } int n_block = n_block_max - 1; // We don't need to clear the sK smem tiles since we'll mask out the scores anyway. flash::copy<Is_even_MN, Is_even_K>(gmem_tiled_copy_QKV, tKgK, tKsK, tKVcKV, tKVpKV, binfo.actual_seqlen_k - n_block * kBlockN); cute::cp_async_fence(); // if (threadIdx.x == 0 && blockIdx.y == 0 && blockIdx.z < 2) { print(tKgK); } // __syncthreads(); if (Kernel_traits::Is_Q_in_regs && !Kernel_traits::Share_Q_K_smem) { flash::cp_async_wait<1>(); __syncthreads(); Tensor tSrQ_copy_view = smem_thr_copy_Q.retile_D(tSrQ); CUTE_STATIC_ASSERT_V(size<1>(tSsQ) == size<1>(tSrQ_copy_view)); // M cute::copy(smem_tiled_copy_Q, tSsQ, tSrQ_copy_view); } // auto seeds = at::cuda::philox::unpack(params.philox_args); // unsigned long long seed = std::get<0>(seeds); // unsigned long long offset = std::get<1>(seeds) + (bidb * params.h + bidh) * 32 + tidx % 32; unsigned long long seed = 0; unsigned long long offset = 0; clear(acc_o); float alibi_slope = !Has_alibi ? 0.0f : reinterpret_cast<float *>(params.alibi_slopes_ptr)[bidb * params.alibi_slopes_batch_stride + bidh] / params.scale_softmax; // For performance reason, we separate out two kinds of iterations: // those that need masking on S, and those that don't. // We need masking on S for the very last block when K and V has length not multiple of kBlockN. // We also need masking on S if it's causal, for the last ceil_div(kBlockM, kBlockN) blocks. // We will have at least 1 "masking" iteration. // If not even_N, then seqlen_k might end in the middle of a block. In that case we need to // mask 2 blocks (e.g. when kBlockM == kBlockN), not just 1. constexpr int n_masking_steps = (!Is_causal && !Is_local) ? 1 : ((Is_even_MN && Is_causal) ? cute::ceil_div(kBlockM, kBlockN) : cute::ceil_div(kBlockM, kBlockN) + 1); #pragma unroll for (int masking_step = 0; masking_step < n_masking_steps; ++masking_step, --n_block) { Tensor acc_s = partition_fragment_C(tiled_mma, Shape<Int<kBlockM>, Int<kBlockN>>{}); // (MMA=4, MMA_M, MMA_N) clear(acc_s); flash::cp_async_wait<0>(); __syncthreads(); // Advance gV if (masking_step > 0) { tVgV.data() = tVgV.data() + (-int(kBlockN * params.v_row_stride)); flash::copy</*Is_even_MN=*/true, Is_even_K>(gmem_tiled_copy_QKV, tVgV, tVsV, tKVcKV, tKVpKV); } else { // Clear the smem tiles to account for predicated off loads flash::copy<Is_even_MN, Is_even_K, /*Clear_OOB_MN=*/true>( gmem_tiled_copy_QKV, tVgV, tVsV, tKVcKV, tKVpKV, binfo.actual_seqlen_k - n_block * kBlockN ); } cute::cp_async_fence(); flash::gemm</*A_in_regs=*/Kernel_traits::Is_Q_in_regs>( acc_s, tSrQ, tSrK, tSsQ, tSsK, tiled_mma, smem_tiled_copy_Q, smem_tiled_copy_K, smem_thr_copy_Q, smem_thr_copy_K ); // if (cute::thread0()) { print(acc_s); } // Reshape acc_s from (MMA=4, MMA_M, MMA_N) to (nrow=(2, MMA_M), ncol=(2, MMA_N)) Tensor scores = make_tensor(acc_s.data(), flash::convert_layout_acc_rowcol(acc_s.layout())); // if (cute::thread0()) { print_tensor(scores); } // We don't put the masking before the matmul S = Q K^T because we don't clear sK // for rows outside actual_seqlen_k. So those rows could have Inf / NaN, and the matmul // can produce Inf / NaN. if (Has_alibi) { flash::apply_alibi<Is_causal>( scores, n_block * kBlockN, binfo.actual_seqlen_k, m_block * kBlockM + (tidx / 32) * 16 + (tidx % 32) / 4, binfo.actual_seqlen_q, kNWarps * 16, alibi_slope ); } if (!Is_causal && !Is_local) { if (!Is_even_MN) { flash::apply_mask(scores, binfo.actual_seqlen_k - n_block * kBlockN); } } else { // Tensor caccS = make_identity_tensor(Shape<Int<kBlockM>, Int<kBlockN>>{}); // (BLK_M,BLK_N) -> (blk_m,blk_n) // Tensor taccScS = thr_mma.partition_C(caccS); // (MMA,MMA_M,MMA_N) // static_assert(decltype(size<0>(taccScS))::value == 4); // // Convert to ((2, 2), MMA_M, MMA_N) then take only the row indices. // Tensor idx_row = logical_divide(taccScS, Shape<_2>{})(make_coord(0, _), _, 0); // Tensor idx_rowcol = make_tensor(taccScS.data(), flash::convert_layout_acc_rowcol(taccScS.layout())); // flash::apply_mask_causal_w_idx(scores, idx_rowcol, n_block * kBlockN, binfo.actual_seqlen_k, // m_block * kBlockM); // Idk why it's get<1> and not get<0> of the stride. // if (cute::thread0()) { print(idx_row.layout()); print(stride<1>(idx_row)); printf("stride = %d \n", get<1>(stride<1>(idx_row))); } // I can't get the stride from idx_row flash::apply_mask_local</*HasWSLeft=*/Is_local>( scores, n_block * kBlockN, binfo.actual_seqlen_k, // m_block * kBlockM + get<0>(idx_row(0)), m_block * kBlockM + (tidx / 32) * 16 + (tidx % 32) / 4, binfo.actual_seqlen_q, kNWarps * 16, params.window_size_left, params.window_size_right // m_block * kBlockM + (tidx / 32) * 16, kNWarps * 16 // m_block * kBlockM + (tidx / 32) * (kBlockM / kNWarps), 16 ); // if (cute::thread0()) { print_tensor(scores); } } flash::cp_async_wait<0>(); __syncthreads(); if (n_block > n_block_min) { // Advance gK tKgK.data() = tKgK.data() + (-int(kBlockN * params.k_row_stride)); flash::copy</*Is_even_MN=*/true, Is_even_K>(gmem_tiled_copy_QKV, tKgK, tKsK, tKVcKV, tKVpKV); // This cp_async_fence needs to be in the if block, otherwise the synchronization // isn't right and we get race conditions. cute::cp_async_fence(); } // TODO: when we have key_padding_mask we'll need to Check_inf masking_step == 0 ? softmax_rescale_o</*Is_first=*/true, /*Check_inf=*/Is_causal || Is_local>(scores, scores_max, scores_sum, acc_o, params.scale_softmax_log2) : softmax_rescale_o</*Is_first=*/false, /*Check_inf=*/Is_causal || Is_local>(scores, scores_max, scores_sum, acc_o, params.scale_softmax_log2); // Convert scores from fp32 to fp16/bf16 Tensor rP = flash::convert_type<Element>(scores); // Reshape rP from (nrow=(2, MMA_M), ncol=(2, MMA_N)) to ((2, 2, 2), MMA_M, MMA_N / 2) // if using m16n8k16 or ((2, 2, 1), MMA_M, MMA_N) if using m16n8k8. Tensor tOrP = make_tensor(rP.data(), flash::convert_layout_rowcol_Aregs<Kernel_traits::TiledMma>(rP.layout())); int block_row_idx = m_block * (kBlockM / 16) + tidx / 32; int block_col_idx = n_block * (kBlockN / 32); if (Return_softmax) { Tensor tOrP_copy = make_fragment_like(tOrP); cute::copy(tOrP, tOrP_copy); flash::apply_dropout</*encode_dropout_in_sign_bit=*/true>( tOrP_copy, params.p_dropout_in_uint8_t, seed, offset, block_row_idx, block_col_idx, kNWarps ); flash::write_softmax_to_gmem(tOrP_copy, tPgP, gmem_tiled_copy_P); tPgP.data() = tPgP.data() + (-kBlockN); } if (Is_dropout) { flash::apply_dropout(tOrP, params.p_dropout_in_uint8_t, seed, offset, block_row_idx, block_col_idx, kNWarps); } // if (cute::thread0()) { print(tOrP); } flash::gemm_A_in_regs(acc_o, tOrP, tOrVt, tOsVt, tiled_mma, smem_tiled_copy_V, smem_thr_copy_V); // if (cute::thread0()) { print(scores); } // This check is at the end of the loop since we always have at least 1 iteration if (n_masking_steps > 1 && n_block <= n_block_min) { --n_block; break; } } // These are the iterations where we don't need masking on S for (; n_block >= n_block_min; --n_block) { Tensor acc_s = partition_fragment_C(tiled_mma, Shape<Int<kBlockM>, Int<kBlockN>>{}); // (MMA=4, MMA_M, MMA_N) clear(acc_s); flash::cp_async_wait<0>(); __syncthreads(); // Advance gV tVgV.data() = tVgV.data() + (-int(kBlockN * params.v_row_stride)); flash::copy</*Is_even_MN=*/true, Is_even_K>(gmem_tiled_copy_QKV, tVgV, tVsV, tKVcKV, tKVpKV); cute::cp_async_fence(); flash::gemm</*A_in_regs=*/Kernel_traits::Is_Q_in_regs>( acc_s, tSrQ, tSrK, tSsQ, tSsK, tiled_mma, smem_tiled_copy_Q, smem_tiled_copy_K, smem_thr_copy_Q, smem_thr_copy_K ); flash::cp_async_wait<0>(); __syncthreads(); if (n_block > n_block_min) { // Advance gK tKgK.data() = tKgK.data() + (-int(kBlockN * params.k_row_stride)); flash::copy</*Is_even_MN=*/true, Is_even_K>(gmem_tiled_copy_QKV, tKgK, tKsK, tKVcKV, tKVpKV); // This cp_async_fence needs to be in the if block, otherwise the synchronization // isn't right and we get race conditions. cute::cp_async_fence(); } // Reshape acc_s from (MMA=4, MMA_M, MMA_N) to (nrow=(2, MMA_M), ncol=(2, MMA_N)) Tensor scores = make_tensor(acc_s.data(), flash::convert_layout_acc_rowcol(acc_s.layout())); if (Has_alibi) { flash::apply_alibi<Is_causal>( scores, n_block * kBlockN, binfo.actual_seqlen_k, m_block * kBlockM + (tidx / 32) * 16 + (tidx % 32) / 4, binfo.actual_seqlen_q, kNWarps * 16, alibi_slope ); } if (Is_local && n_block * kBlockN < (m_block + 1) * kBlockM + binfo.actual_seqlen_k - binfo.actual_seqlen_q + params.window_size_right) { flash::apply_mask_local( scores, n_block * kBlockN, binfo.actual_seqlen_k, m_block * kBlockM + (tidx / 32) * 16 + (tidx % 32) / 4, binfo.actual_seqlen_q, kNWarps * 16, params.window_size_left, params.window_size_right ); } softmax_rescale_o</*Is_first=*/false, /*Check_inf=*/Is_local>(scores, scores_max, scores_sum, acc_o, params.scale_softmax_log2); Tensor rP = flash::convert_type<Element>(scores); // Reshape rP from (nrow=(2, MMA_M), ncol=(2, MMA_N)) to ((2, 2, 2), MMA_M, MMA_N / 2) // if using m16n8k16 or ((2, 2, 1), MMA_M, MMA_N) if using m16n8k8. Tensor tOrP = make_tensor(rP.data(), flash::convert_layout_rowcol_Aregs<Kernel_traits::TiledMma>(rP.layout())); int block_row_idx = m_block * (kBlockM / 16) + tidx / 32; int block_col_idx = n_block * (kBlockN / 32); if (Return_softmax) { Tensor tOrP_copy = make_fragment_like(tOrP); cute::copy(tOrP, tOrP_copy); flash::apply_dropout</*encode_dropout_in_sign_bit=*/true>( tOrP_copy, params.p_dropout_in_uint8_t, seed, offset, block_row_idx, block_col_idx, kNWarps ); flash::write_softmax_to_gmem(tOrP_copy, tPgP, gmem_tiled_copy_P); tPgP.data() = tPgP.data() + (-kBlockN); } if (Is_dropout) { flash::apply_dropout(tOrP, params.p_dropout_in_uint8_t, seed, offset, block_row_idx, block_col_idx, kNWarps); } flash::gemm_A_in_regs(acc_o, tOrP, tOrVt, tOsVt, tiled_mma, smem_tiled_copy_V, smem_thr_copy_V); } // Epilogue // Reshape acc_o from (MMA=4, MMA_M, MMA_K) to (nrow=(2, MMA_M), ncol=(2, MMA_K)) Tensor acc_o_rowcol = make_tensor(acc_o.data(), flash::convert_layout_acc_rowcol(acc_o.layout())); Tensor lse = make_fragment_like(scores_sum); #pragma unroll for (int mi = 0; mi < size<0>(acc_o_rowcol); ++mi) { float sum = scores_sum(mi); float inv_sum = (sum == 0.f || sum != sum) ? 1.f : 1.f / sum; lse(mi) = (sum == 0.f || sum != sum) ? INFINITY : scores_max(mi) * params.scale_softmax + __logf(sum); float scale = !Is_dropout ? inv_sum : inv_sum * params.rp_dropout; #pragma unroll for (int ni = 0; ni < size<1>(acc_o_rowcol); ++ni) { acc_o_rowcol(mi, ni) *= scale; } } // if (cute::thread0()) { print(acc_o_rowcol); } // Convert acc_o from fp32 to fp16/bf16 Tensor rO = flash::convert_type<Element>(acc_o); Tensor sO = make_tensor(sQ.data(), typename Kernel_traits::SmemLayoutO{}); // (SMEM_M,SMEM_N) // Partition sO to match the accumulator partitioning auto smem_tiled_copy_O = make_tiled_copy_C(typename Kernel_traits::SmemCopyAtomO{}, tiled_mma); auto smem_thr_copy_O = smem_tiled_copy_O.get_thread_slice(tidx); Tensor taccOrO = smem_thr_copy_O.retile_S(rO); // ((Atom,AtomNum), MMA_M, MMA_N) Tensor taccOsO = smem_thr_copy_O.partition_D(sO); // ((Atom,AtomNum),PIPE_M,PIPE_N) // sO has the same size as sQ, so we don't need to sync here. if (Kernel_traits::Share_Q_K_smem) { __syncthreads(); } cute::copy(smem_tiled_copy_O, taccOrO, taccOsO); const index_t row_offset_o = binfo.q_offset(params.o_batch_stride, params.o_row_stride, bidb) + m_block * kBlockM * params.o_row_stride + bidh * params.o_head_stride; const index_t row_offset_lse = (bidb * params.h + bidh) * params.seqlen_q + m_block * kBlockM; Tensor gO = make_tensor(make_gmem_ptr(reinterpret_cast<Element *>(params.o_ptr) + row_offset_o), Shape<Int<kBlockM>, Int<kHeadDim>>{}, make_stride(params.o_row_stride, _1{})); Tensor gLSE = make_tensor(make_gmem_ptr(reinterpret_cast<ElementAccum *>(params.softmax_lse_ptr) + row_offset_lse), Shape<Int<kBlockM>>{}, Stride<_1>{}); typename Kernel_traits::GmemTiledCopyO gmem_tiled_copy_O; auto gmem_thr_copy_O = gmem_tiled_copy_O.get_thread_slice(tidx); Tensor tOsO = gmem_thr_copy_O.partition_S(sO); // ((Atom,AtomNum),ATOM_M,ATOM_N) Tensor tOgO = gmem_thr_copy_O.partition_D(gO); __syncthreads(); Tensor tOrO = make_tensor<Element>(shape(tOgO)); cute::copy(gmem_tiled_copy_O, tOsO, tOrO); Tensor caccO = make_identity_tensor(Shape<Int<kBlockM>, Int<kHeadDim>>{}); // (BLK_M,BLK_K) -> (blk_m,blk_k) Tensor taccOcO = thr_mma.partition_C(caccO); // (MMA,MMA_M,MMA_K) static_assert(decltype(size<0>(taccOcO))::value == 4); // Convert to ((2, 2), MMA_M, MMA_K) then take only the row indices. Tensor taccOcO_row = logical_divide(taccOcO, Shape<_2>{})(make_coord(0, _), _, 0); CUTE_STATIC_ASSERT_V(size(lse) == size(taccOcO_row)); // MMA_M if (get<1>(taccOcO_row(0)) == 0) { #pragma unroll for (int mi = 0; mi < size(lse); ++mi) { const int row = get<0>(taccOcO_row(mi)); if (row < binfo.actual_seqlen_q - m_block * kBlockM) { gLSE(row) = lse(mi); } } } // Construct identity layout for sO Tensor cO = make_identity_tensor(make_shape(size<0>(sO), size<1>(sO))); // (BLK_M,BLK_K) -> (blk_m,blk_k) // Repeat the partitioning with identity layouts Tensor tOcO = gmem_thr_copy_O.partition_D(cO); // (ACPY,ACPY_M,ACPY_K) -> (blk_m,blk_k) Tensor tOpO = make_tensor<bool>(make_shape(size<2>(tOgO))); if (!Is_even_K) { #pragma unroll for (int k = 0; k < size(tOpO); ++k) { tOpO(k) = get<1>(tOcO(0, 0, k)) < params.d; } } // Clear_OOB_K must be false since we don't want to write zeros to gmem flash::copy<Is_even_MN, Is_even_K, /*Clear_OOB_MN=*/false, /*Clear_OOB_K=*/false>( gmem_tiled_copy_O, tOrO, tOgO, tOcO, tOpO, binfo.actual_seqlen_q - m_block * kBlockM ); } //////////////////////////////////////////////////////////////////////////////////////////////////// template<typename Kernel_traits, bool Is_dropout, bool Is_causal, bool Is_local, bool Has_alibi, bool Is_even_MN, bool Is_even_K, bool Return_softmax, typename Params> inline __device__ void compute_attn(const Params &params) { const int m_block = blockIdx.x; // The block index for the batch. const int bidb = blockIdx.y; // The block index for the head. const int bidh = blockIdx.z; // We want the fwd and bwd to generate the same dropout pattern (RNG), without restricting // them to have the same number of threads or have to traverse the attention matrix // in the same order. // In the Philox RNG, we use the offset to store the batch, head, and the lane id // (within a warp). We use the subsequence to store the location of the 16 x 32 blocks within // the attention matrix. This way, as long as we have the batch, head, and the location of // the 16 x 32 block within the attention matrix, we can generate the exact same dropout pattern. flash::compute_attn_1rowblock<Kernel_traits, Is_dropout, Is_causal, Is_local, Has_alibi, Is_even_MN, Is_even_K, Return_softmax>(params, bidb, bidh, m_block); } //////////////////////////////////////////////////////////////////////////////////////////////////// } // namespace flash
candle/candle-flash-attn/kernels/flash_fwd_kernel.h/0
{ "file_path": "candle/candle-flash-attn/kernels/flash_fwd_kernel.h", "repo_id": "candle", "token_count": 16384 }
29
#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 }
30
#include <metal_stdlib> METAL_FUNC uint get_strided_index( uint idx, constant size_t &num_dims, constant size_t *dims, constant size_t *strides ) { uint strided_i = 0; for (uint d = 0; d < num_dims; d++) { uint dim_idx = num_dims - 1 - d; strided_i += (idx % dims[dim_idx]) * strides[dim_idx]; idx /= dims[dim_idx]; } return strided_i; } using namespace metal; #define CAST(FN_NAME, FN_NAME_STRIDED, LEFT_TYPENAME, RIGHT_TYPENAME) \ kernel void FN_NAME( \ constant size_t &dim, \ device const LEFT_TYPENAME *input, \ device RIGHT_TYPENAME *output, \ uint tid [[ thread_position_in_grid ]] \ ) { \ if (tid >= dim) { \ return; \ } \ output[tid] = static_cast<RIGHT_TYPENAME>(input[tid]); \ } \ kernel void FN_NAME_STRIDED( \ constant size_t &dim, \ constant size_t &num_dims, \ constant size_t *dims, \ constant size_t *strides, \ device const LEFT_TYPENAME *input, \ device RIGHT_TYPENAME *output, \ uint tid [[ thread_position_in_grid ]] \ ) { \ if (tid >= dim) { \ return; \ } \ output[tid] = static_cast<RIGHT_TYPENAME>(input[get_strided_index(tid, num_dims, dims, strides)]); \ } \ #define CAST_THROUGH(FN_NAME, FN_NAME_STRIDED, LEFT_TYPENAME, RIGHT_TYPENAME, IR_TYPENAME) \ kernel void FN_NAME( \ constant size_t &dim, \ device const LEFT_TYPENAME *input, \ device RIGHT_TYPENAME *output, \ uint tid [[ thread_position_in_grid ]] \ ) { \ if (tid >= dim) { \ return; \ } \ output[tid] = static_cast<RIGHT_TYPENAME>(static_cast<IR_TYPENAME>(input[tid])); \ } \ kernel void FN_NAME_STRIDED( \ constant size_t &dim, \ constant size_t &num_dims, \ constant size_t *dims, \ constant size_t *strides, \ device const LEFT_TYPENAME *input, \ device RIGHT_TYPENAME *output, \ uint tid [[ thread_position_in_grid ]] \ ) { \ if (tid >= dim) { \ return; \ } \ output[tid] = static_cast<RIGHT_TYPENAME>(static_cast<IR_TYPENAME>(input[get_strided_index(tid, num_dims, dims, strides)])); \ } \ // u32 CAST(cast_u32_f32, cast_u32_f32_strided, uint32_t, float) CAST(cast_u32_u8, cast_u32_u8_strided, uint32_t, uint8_t) CAST(cast_u32_f16, cast_u32_f16_strided, uint32_t, half) #if __METAL_VERSION__ >= 220 CAST(cast_u32_i64, cast_u32_i64_strided, uint32_t, int64_t) #endif #if defined(__HAVE_BFLOAT__) CAST(cast_u32_bf16, cast_u32_bf16_strided, uint32_t, bfloat) #endif // u8 CAST(cast_u8_u32, cast_u8_u32_strided, uint8_t, uint32_t) CAST(cast_u8_f32, cast_u8_f32_strided, uint8_t, float) CAST(cast_u8_f16, cast_u8_f16_strided, uint8_t, half) #if __METAL_VERSION__ >= 220 CAST(cast_u8_i64, cast_u8_i64_strided, uint8_t, int64_t) #endif #if defined(__HAVE_BFLOAT__) CAST(cast_u8_bf16, cast_u8_bf16_strided, uint8_t, bfloat) #endif // f16 CAST(cast_f16_f32, cast_f16_f32_strided, half, float) CAST(cast_f16_u8, cast_f16_u8_strided, half, uint8_t) CAST(cast_f16_u32, cast_f16_u32_strided, half, uint32_t) CAST(cast_f16_i64, cast_f16_i64_strided, half, int64_t) #if defined(__HAVE_BFLOAT__) CAST_THROUGH(cast_f16_bf16, cast_f16_bf16_strided, half, bfloat, float) #endif // i64 CAST(cast_i64_f32, cast_i64_f32_strided, int64_t, float) CAST(cast_i64_u8, cast_i64_u8_strided, int64_t, uint8_t) CAST(cast_i64_u32, cast_i64_u32_strided, int64_t, uint32_t) CAST(cast_i64_f16, cast_i64_f16_strided, int64_t, half) #if defined(__HAVE_BFLOAT__) CAST_THROUGH(cast_i64_bf16, cast_i64_bf16_strided, int64_t, bfloat, float) #endif // f32 CAST(cast_f32_f16, cast_f32_f16_strided, float, half) CAST(cast_f32_u32, cast_f32_u32_strided, float, uint32_t) CAST(cast_f32_u8, cast_f32_u8_strided, float, uint8_t) CAST(cast_f32_i64, cast_f32_i64_strided, float, int64_t) #if defined(__HAVE_BFLOAT__) CAST(cast_f32_bf16, cast_f32_bf16_strided, float, bfloat) #endif // bf16 #if defined(__HAVE_BFLOAT__) CAST(cast_bf16_u32, cast_bf16_u32_strided, bfloat, uint32_t) CAST(cast_bf16_i64, cast_bf16_i64_strided, bfloat, int64_t) CAST(cast_bf16_f32, cast_bf16_f32_strided, bfloat, float) CAST_THROUGH(cast_bf16_u8, cast_bf16_u8_strided, bfloat, uint8_t, float) CAST_THROUGH(cast_bf16_f16, cast_bf16_f16_strided, bfloat, half, float) #endif
candle/candle-metal-kernels/src/cast.metal/0
{ "file_path": "candle/candle-metal-kernels/src/cast.metal", "repo_id": "candle", "token_count": 2045 }
31
# candle-nn
candle/candle-nn/README.md/0
{ "file_path": "candle/candle-nn/README.md", "repo_id": "candle", "token_count": 5 }
32
//! Various optimization algorithms. use candle::{Result, Tensor, Var}; /// The interface optimizers should implement. pub trait Optimizer: Sized { type Config: Sized; fn new(vars: Vec<Var>, config: Self::Config) -> Result<Self>; fn step(&mut self, grads: &candle::backprop::GradStore) -> Result<()>; fn learning_rate(&self) -> f64; fn set_learning_rate(&mut self, lr: f64); fn empty(config: Self::Config) -> Result<Self> { Self::new(vec![], config) } fn backward_step(&mut self, loss: &Tensor) -> Result<()> { let grads = loss.backward()?; self.step(&grads) } fn from_slice(vars: &[&Var], config: Self::Config) -> Result<Self> { let vars: Vec<_> = vars.iter().map(|&v| v.clone()).collect(); Self::new(vars, config) } } /// Optimizer for Stochastic Gradient Descent. /// /// Contrary to the PyTorch implementation of SGD, this version does not support momentum. #[derive(Debug)] pub struct SGD { vars: Vec<Var>, learning_rate: f64, } impl Optimizer for SGD { type Config = f64; fn new(vars: Vec<Var>, learning_rate: f64) -> Result<Self> { let vars = vars .into_iter() .filter(|var| var.dtype().is_float()) .collect(); Ok(Self { vars, learning_rate, }) } fn learning_rate(&self) -> f64 { self.learning_rate } fn step(&mut self, grads: &candle::backprop::GradStore) -> Result<()> { for var in self.vars.iter() { if let Some(grad) = grads.get(var) { var.set(&var.sub(&(grad * self.learning_rate)?)?)?; } } Ok(()) } fn set_learning_rate(&mut self, lr: f64) { self.learning_rate = lr } } impl SGD { pub fn into_inner(self) -> Vec<Var> { self.vars } pub fn push(&mut self, var: &Var) { self.vars.push(var.clone()) } } #[derive(Clone, Debug)] pub struct ParamsAdamW { pub lr: f64, pub beta1: f64, pub beta2: f64, pub eps: f64, pub weight_decay: f64, } impl Default for ParamsAdamW { fn default() -> Self { Self { lr: 0.001, beta1: 0.9, beta2: 0.999, eps: 1e-8, weight_decay: 0.01, } } } #[derive(Debug)] struct VarAdamW { var: Var, first_moment: Var, second_moment: Var, } #[derive(Debug)] pub struct AdamW { vars: Vec<VarAdamW>, step_t: usize, params: ParamsAdamW, } impl Optimizer for AdamW { type Config = ParamsAdamW; fn new(vars: Vec<Var>, params: ParamsAdamW) -> Result<Self> { let vars = vars .into_iter() .filter(|var| var.dtype().is_float()) .map(|var| { let dtype = var.dtype(); let shape = var.shape(); let device = var.device(); let first_moment = Var::zeros(shape, dtype, device)?; let second_moment = Var::zeros(shape, dtype, device)?; Ok(VarAdamW { var, first_moment, second_moment, }) }) .collect::<Result<Vec<_>>>()?; Ok(Self { vars, params, step_t: 0, }) } fn learning_rate(&self) -> f64 { self.params.lr } fn set_learning_rate(&mut self, lr: f64) { self.params.lr = lr } fn step(&mut self, grads: &candle::backprop::GradStore) -> Result<()> { self.step_t += 1; let lr = self.params.lr; let lambda = self.params.weight_decay; let lr_lambda = lr * lambda; let beta1 = self.params.beta1; let beta2 = self.params.beta2; let scale_m = 1f64 / (1f64 - beta1.powi(self.step_t as i32)); let scale_v = 1f64 / (1f64 - beta2.powi(self.step_t as i32)); for var in self.vars.iter() { let theta = &var.var; let m = &var.first_moment; let v = &var.second_moment; if let Some(g) = grads.get(theta) { // This involves locking 3 RWLocks per params, if the parameters are large this // should not be an issue but this may be problematic with models with lots of // small parameters. let next_m = ((m.as_tensor() * beta1)? + (g * (1.0 - beta1))?)?; let next_v = ((v.as_tensor() * beta2)? + (g.sqr()? * (1.0 - beta2))?)?; let m_hat = (&next_m * scale_m)?; let v_hat = (&next_v * scale_v)?; let next_theta = (theta.as_tensor() * (1f64 - lr_lambda))?; let adjusted_grad = (m_hat / (v_hat.sqrt()? + self.params.eps)?)?; let next_theta = (next_theta - (adjusted_grad * lr)?)?; m.set(&next_m)?; v.set(&next_v)?; theta.set(&next_theta)?; } } Ok(()) } } impl AdamW { pub fn new_lr(vars: Vec<Var>, learning_rate: f64) -> Result<Self> { let params = ParamsAdamW { lr: learning_rate, ..ParamsAdamW::default() }; Self::new(vars, params) } pub fn params(&self) -> &ParamsAdamW { &self.params } pub fn set_params(&mut self, params: ParamsAdamW) { self.params = params; } }
candle/candle-nn/src/optim.rs/0
{ "file_path": "candle/candle-nn/src/optim.rs", "repo_id": "candle", "token_count": 2798 }
33
use crate::onnx; use crate::onnx::attribute_proto::AttributeType; use crate::onnx::tensor_proto::DataType; use candle::{bail, DType, Device, Result, Tensor}; use std::collections::HashMap; pub type Value = Tensor; pub fn dtype(dt: DataType) -> Option<DType> { match dt { DataType::Uint8 => Some(DType::U8), DataType::Uint32 => Some(DType::U32), DataType::Int64 => Some(DType::I64), DataType::Float16 => Some(DType::F16), DataType::Float => Some(DType::F32), DataType::Double => Some(DType::F64), _ => None, } } trait Attr { const TYPE: AttributeType; fn get(attr: &onnx::AttributeProto) -> Result<&Self>; } impl Attr for i64 { const TYPE: AttributeType = AttributeType::Int; fn get(attr: &onnx::AttributeProto) -> Result<&Self> { Ok(&attr.i) } } impl Attr for f32 { const TYPE: AttributeType = AttributeType::Float; fn get(attr: &onnx::AttributeProto) -> Result<&Self> { Ok(&attr.f) } } impl Attr for [i64] { const TYPE: AttributeType = AttributeType::Ints; fn get(attr: &onnx::AttributeProto) -> Result<&Self> { Ok(attr.ints.as_slice()) } } impl Attr for str { const TYPE: AttributeType = AttributeType::String; fn get(attr: &onnx::AttributeProto) -> Result<&Self> { std::str::from_utf8(&attr.s).map_err(candle::Error::wrap) } } fn get_attr_<'a>(node: &'a onnx::NodeProto, name: &str) -> Result<&'a onnx::AttributeProto> { match node.attribute.iter().find(|attr| attr.name == name) { None => { bail!( "cannot find the '{name}' attribute in '{}' for {}", node.op_type, node.name ) } Some(dt) => Ok(dt), } } fn get_attr<'a, T: Attr + ?Sized>(node: &'a onnx::NodeProto, name: &str) -> Result<&'a T> { let attr = get_attr_(node, name)?; if attr.r#type() != T::TYPE { bail!( "unsupported type {:?} for '{name}' attribute in '{}' for {}", attr.r#type, node.op_type, node.name ) } T::get(attr) } fn get_attr_opt<'a, T: Attr + ?Sized>( node: &'a onnx::NodeProto, name: &str, ) -> Result<Option<&'a T>> { match node.attribute.iter().find(|attr| attr.name == name) { None => Ok(None), Some(attr) => { if attr.r#type() != T::TYPE { bail!( "unsupported type {:?} for '{name}' attribute in '{}' for {}", attr.r#type, node.op_type, node.name ) } let val = T::get(attr)?; Ok(Some(val)) } } } pub fn get_tensor(t: &onnx::TensorProto, name: &str) -> Result<Tensor> { let dims: Vec<usize> = t.dims.iter().map(|&x| x as usize).collect(); match DataType::try_from(t.data_type) { Ok(DataType::Int32) => { if t.int32_data.is_empty() { let len = t.raw_data.len() / 4; let data: &[i32] = unsafe { std::slice::from_raw_parts(t.raw_data.as_ptr() as *const i32, len) }; let data = data.iter().map(|v| *v as i64).collect::<Vec<_>>(); Tensor::from_vec(data, len, &Device::Cpu) } else { let data = t.int32_data.iter().map(|v| *v as i64).collect::<Vec<_>>(); Tensor::from_vec(data, t.int32_data.len(), &Device::Cpu) } } Ok(dt) => match dtype(dt) { Some(dt) => { if dt == DType::F32 && !t.float_data.is_empty() { Tensor::from_slice(&t.float_data, dims.as_slice(), &Device::Cpu) } else if dt == DType::F64 && !t.double_data.is_empty() { Tensor::from_slice(&t.double_data, dims.as_slice(), &Device::Cpu) } else if dt == DType::I64 && !t.int64_data.is_empty() { Tensor::from_slice(&t.int64_data, dims.as_slice(), &Device::Cpu) } else { Tensor::from_raw_buffer( t.raw_data.as_slice(), dt, dims.as_slice(), &Device::Cpu, ) } } None => { bail!("unsupported 'value' data-type {dt:?} for {name}") } }, Err(_) => { bail!("unsupported 'value' data-type {} for {name}", t.data_type,) } } } // This function provides a direct evaluation of the proto. // Longer-term, we should first convert the proto to an intermediate representation of the compute // graph so as to make multiple evaluations more efficient. // An example upside of this would be to remove intermediary values when they are not needed // anymore. pub fn simple_eval( model: &onnx::ModelProto, inputs: HashMap<String, Value>, ) -> Result<HashMap<String, Value>> { let graph = match &model.graph { None => bail!("no graph defined in proto"), Some(graph) => graph, }; let mut values = inputs; for t in graph.initializer.iter() { let tensor = get_tensor(t, t.name.as_str())?; values.insert(t.name.to_string(), tensor); } for input in graph.input.iter() { let input_type = match &input.r#type { Some(input_type) => input_type, None => continue, }; let input_type = match &input_type.value { Some(input_type) => input_type, None => continue, }; let tensor_type = match input_type { onnx::type_proto::Value::TensorType(tt) => tt, _ => continue, }; let tensor = match values.get(&input.name) { None => bail!("missing input {}", input.name), Some(tensor) => tensor, }; let dt = match DataType::try_from(tensor_type.elem_type) { Ok(dt) => match dtype(dt) { Some(dt) => dt, None => { bail!("unsupported 'value' data-type {dt:?} for {}", input.name) } }, type_ => bail!("unsupported input type {type_:?}"), }; match &tensor_type.shape { None => continue, Some(shape) => { if shape.dim.len() != tensor.rank() { bail!( "unexpected rank for {}, got {:?}, expected {:?}", input.name, shape.dim, tensor.shape() ) } for (idx, (d, &dim)) in shape.dim.iter().zip(tensor.dims().iter()).enumerate() { match &d.value { Some(onnx::tensor_shape_proto::dimension::Value::DimValue(v)) => { if *v as usize != dim { bail!( "unexpected dim {idx} for {}, got {:?}, expected {:?}", input.name, shape.dim, tensor.shape() ) } } // We do not check equality constraints for the DimParam dimensions for now. Some(onnx::tensor_shape_proto::dimension::Value::DimParam(_)) | None => (), } } } }; if dt != tensor.dtype() { bail!( "unexpected dtype for {}, got {:?}, expected {dt:?}", input.name, tensor.dtype() ) } } // The nodes are topologically sorted so we can just process them in order. for node in graph.node.iter() { let get = |input_name: &str| match values.get(input_name) { Some(value) => Ok(value), None => bail!("cannot find {input_name} for op {}", node.name), }; // TODO: Validate node.input for each operator. match node.op_type.as_str() { "Add" => { let input0 = get(&node.input[0])?; let input1 = get(&node.input[1])?; let output = input0.broadcast_add(input1)?; values.insert(node.output[0].clone(), output); } "Sub" => { let input0 = get(&node.input[0])?; let input1 = get(&node.input[1])?; let output = input0.broadcast_sub(input1)?; values.insert(node.output[0].clone(), output); } "Mul" => { let input0 = get(&node.input[0])?; let input1 = get(&node.input[1])?; let output = input0.broadcast_mul(input1)?; values.insert(node.output[0].clone(), output); } "Div" => { let input0 = get(&node.input[0])?; let input1 = get(&node.input[1])?; let output = input0.broadcast_div(input1)?; values.insert(node.output[0].clone(), output); } "Pow" => { let input0 = get(&node.input[0])?; let input1 = get(&node.input[1])?; let output = input0.broadcast_pow(input1)?; values.insert(node.output[0].clone(), output); } "Equal" => { let input0 = get(&node.input[0])?; let input1 = get(&node.input[1])?; let output = input0.broadcast_eq(input1)?; values.insert(node.output[0].clone(), output); } "Not" => { let xs = get(&node.input[0])?; let xs = xs.eq(&xs.zeros_like()?)?; values.insert(node.output[0].clone(), xs); } "MatMul" => { let input0 = get(&node.input[0])?; let input1 = get(&node.input[1])?; let output = input0.broadcast_matmul(input1)?; values.insert(node.output[0].clone(), output); } "Reshape" => { let input0 = get(&node.input[0])?; let input1 = get(&node.input[1])?.to_vec1::<i64>()?; // TODO: Check that there is at most a single -1 or 0, handle other neg values. let mut other_than_minus1 = 1usize; for &v in input1.iter() { if v != -1 && v != 0 { other_than_minus1 *= v as usize } } let input1 = input1 .iter() .enumerate() .map(|(idx, &v)| match v { -1 => Ok(input0.elem_count() / other_than_minus1), 0 => input0.dim(idx), _ => Ok(v as usize), }) .collect::<Result<Vec<usize>>>()?; let output = input0.reshape(input1)?; values.insert(node.output[0].clone(), output); } "LogSoftmax" => { let input = get(&node.input[0])?; let output = match get_attr_opt::<i64>(node, "axis")? { None => candle_nn::ops::softmax_last_dim(input)?, Some(&axis) => { let axis = input.normalize_axis(axis)?; candle_nn::ops::log_softmax(input, axis)? } }; values.insert(node.output[0].clone(), output); } "Softmax" => { let input = get(&node.input[0])?; let output = match get_attr_opt::<i64>(node, "axis")? { None => candle_nn::ops::softmax_last_dim(input)?, Some(&axis) => { let axis = input.normalize_axis(axis)?; candle_nn::ops::softmax(input, axis)? } }; values.insert(node.output[0].clone(), output); } "Transpose" => { let input = get(&node.input[0])?; let output = match get_attr_opt::<[i64]>(node, "perm")? { None => input.t()?, Some(perm) => { let perm = perm.iter().map(|&v| v as usize).collect::<Vec<_>>(); input.permute(perm)? } }; values.insert(node.output[0].clone(), output); } "Dropout" => { let input = get(&node.input[0])?; // Do not apply dropout at the moment, consider that we're only doing inference. values.insert(node.output[0].clone(), input.clone()); } "MaxPool" => { // https://github.com/onnx/onnx/blob/main/docs/Operators.md#MaxPool let dilations = get_attr_opt::<[i64]>(node, "dilations")?; let kernel_shape = get_attr::<[i64]>(node, "kernel_shape")?; let pads = get_attr_opt::<[i64]>(node, "pads")?; let strides = get_attr_opt::<[i64]>(node, "strides")?; let auto_pad = get_attr_opt::<str>(node, "auto_pad")?; match auto_pad { None | Some("NOTSET") => (), Some(s) => bail!("unsupported auto_pad {s}"), }; if let Some(d) = dilations { if d.iter().any(|&v| v != 1) { bail!("MaxPool with dilation != 1, {dilations:?}") } } if let Some(d) = pads { if d.iter().any(|&v| v != 0) { bail!("MaxPool with pads != 0, {pads:?}") } } let xs = get(&node.input[0])?; let (k1, k2) = match kernel_shape { [k1, k2] => (*k1 as usize, *k2 as usize), _ => bail!("only 2d MaxPool is supported, kernel shape {kernel_shape:?}"), }; let ys = match strides { None => xs.max_pool2d((k1, k2))?, Some([s1, s2]) => { xs.max_pool2d_with_stride((k1, k2), (*s1 as usize, *s2 as usize))? } Some(strides) => bail!("only 2d MaxPool is supported, strides {strides:?}"), }; values.insert(node.output[0].clone(), ys); } "AveragePool" => { // https://github.com/onnx/onnx/blob/main/docs/Operators.md#AveragePool let dilations = get_attr_opt::<[i64]>(node, "dilations")?; let kernel_shape = get_attr::<[i64]>(node, "kernel_shape")?; let pads = get_attr_opt::<[i64]>(node, "pads")?; let strides = get_attr_opt::<[i64]>(node, "strides")?; let auto_pad = get_attr_opt::<str>(node, "auto_pad")?; match auto_pad { None | Some("NOTSET") => (), Some(s) => bail!("unsupported auto_pad {s}"), }; if let Some(d) = dilations { if d.iter().any(|&v| v != 1) { bail!("AvgPool with dilation != 1, {dilations:?}") } } if let Some(d) = pads { if d.iter().any(|&v| v != 0) { bail!("AvgPool with pads != 0, {pads:?}") } } let xs = get(&node.input[0])?; let (k1, k2) = match kernel_shape { [k1, k2] => (*k1 as usize, *k2 as usize), _ => bail!("only 2d AvgPool is supported, kernel shape {kernel_shape:?}"), }; let ys = match strides { None => xs.avg_pool2d((k1, k2))?, Some([s1, s2]) => { xs.avg_pool2d_with_stride((k1, k2), (*s1 as usize, *s2 as usize))? } Some(strides) => bail!("only 2d AvgPool is supported, strides {strides:?}"), }; values.insert(node.output[0].clone(), ys); } "BatchNormalization" => { let training_mode = get_attr_opt::<i64>(node, "training_mode")?; if training_mode.copied().unwrap_or(0) != 0 { bail!("training mode is not supported for BatchNorm") } let eps = get_attr_opt::<f32>(node, "epsilon")? .copied() .unwrap_or(1e-5); let xs = get(&node.input[0])?; let weight = get(&node.input[1])?; let bias = get(&node.input[2])?; let running_mean = get(&node.input[3])?; let running_var = get(&node.input[4])?; let target_shape: Vec<usize> = xs .dims() .iter() .enumerate() .map(|(idx, v)| if idx == 1 { *v } else { 1 }) .collect(); let target_shape = target_shape.as_slice(); let xs = xs .broadcast_sub(&running_mean.reshape(target_shape)?)? .broadcast_div(&(running_var.reshape(target_shape)? + eps as f64)?.sqrt()?)?; let weight = weight.reshape(target_shape)?; let bias = bias.reshape(target_shape)?; let xs = xs.broadcast_mul(&weight)?.broadcast_add(&bias)?; values.insert(node.output[0].clone(), xs); } "Squeeze" => { let xs = get(&node.input[0])?; let mut axes = if node.input.len() <= 1 { // contract all the dimensions with size 1 except the batch dim. xs.dims() .iter() .enumerate() .flat_map(|(idx, &s)| if s == 1 && idx > 0 { Some(idx) } else { None }) .collect() } else { get(&node.input[1])? .to_vec1::<i64>()? .iter() .map(|&i| xs.normalize_axis(i)) .collect::<Result<Vec<_>>>()? }; axes.sort(); let mut xs = xs.clone(); for &axis in axes.iter().rev() { xs = xs.squeeze(axis)? } values.insert(node.output[0].clone(), xs); } "ConstantOfShape" => { let dims = get(&node.input[0])?; let shape = dims .to_vec1::<i64>()? .into_iter() .map(|v| v as usize) .collect::<Vec<_>>(); let xs = Tensor::zeros(shape, DType::F32, dims.device())?; values.insert(node.output[0].clone(), xs); } "Unsqueeze" => { let xs = get(&node.input[0])?; let axes = match get_attr_opt::<[i64]>(node, "axes")? { Some(axis) => axis.to_vec(), None => get(&node.input[1])?.to_vec1::<i64>()?, }; let mut axes = axes .iter() .map(|&i| { if i == xs.rank() as i64 { Ok(xs.rank()) } else { xs.normalize_axis(i) } }) .collect::<Result<Vec<_>>>()?; axes.sort(); let mut xs = xs.clone(); for &axis in axes.iter().rev() { xs = xs.unsqueeze(axis)? } values.insert(node.output[0].clone(), xs); } "Clip" => { let xs = get(&node.input[0])?; let xs = if node.input.len() >= 2 { let mins = get(&node.input[1])?; xs.broadcast_maximum(mins)? } else { xs.clone() }; let xs = if node.input.len() >= 3 { let maxs = get(&node.input[2])?; xs.broadcast_minimum(maxs)? } else { xs.clone() }; values.insert(node.output[0].clone(), xs); } "Gather" => { let xs = get(&node.input[0])?; let indices = get(&node.input[1])?; let axis = get_attr_opt::<i64>(node, "axis")?.copied().unwrap_or(0); let axis = xs.normalize_axis(axis)?; // TODO: Provide an op to handle the ONNX generalized gather op ideally in a // differentiable way. let xs = if indices.rank() == 0 { let index = indices.to_vec0::<i64>()? as usize; xs.narrow(axis, index, 1)?.squeeze(axis)? } else { todo!("implement gather for {xs:?} {indices:?} axis {axis}") }; values.insert(node.output[0].clone(), xs); } "Shape" => { // https://github.com/onnx/onnx/blob/main/docs/Operators.md#Shape let xs = get(&node.input[0])?; let start = get_attr_opt::<i64>(node, "start")?.copied().unwrap_or(0); let end = get_attr_opt::<i64>(node, "end")?.copied().unwrap_or(-1); let start = xs.normalize_axis(start)?; let end = xs.normalize_axis(end)?; let mut dims = vec![]; for idx in start..=end { dims.push(xs.dim(idx)? as i64) } let dims = Tensor::from_vec(dims, xs.rank(), xs.device())?; values.insert(node.output[0].clone(), dims); } "Conv" => { // https://github.com/onnx/onnx/blob/main/docs/Operators.md#Conv let dilations = get_attr_opt::<[i64]>(node, "dilations")?; let groups = get_attr_opt::<i64>(node, "group")?.copied().unwrap_or(1); let _kernel_shape = get_attr_opt::<[i64]>(node, "kernel_shape")?; let pads = get_attr_opt::<[i64]>(node, "pads")?; let strides = get_attr_opt::<[i64]>(node, "strides")?; let auto_pad = get_attr_opt::<str>(node, "auto_pad")?; match auto_pad { None | Some("NOTSET") => (), Some(s) => bail!("unsupported auto_pad {s}"), }; let xs = get(&node.input[0])?; let ws = get(&node.input[1])?; let ys = match ws.rank() { 3 => { let (pads, xs) = match pads { None => (0, xs.clone()), Some([p]) => (*p as usize, xs.clone()), Some([p1, p2]) => { if p1 != p2 { (0usize, xs.pad_with_zeros(2, *p1 as usize, *p2 as usize)?) } else { (*p1 as usize, xs.clone()) } } Some(pads) => { bail!("more pads than expected in conv1d {pads:?} {}", node.name) } }; let strides = match strides { None => 1, Some([p]) => *p as usize, Some(s) => { bail!("more strides than expected in conv1d {s:?} {}", node.name) } }; let dilations = match dilations { None => 1, Some([p]) => *p as usize, Some(s) => { bail!("more dilations than expected in conv1d {s:?} {}", node.name) } }; xs.conv1d(ws, pads, strides, dilations, groups as usize)? } 4 => { let (pads, xs) = match pads { None => (0, xs.clone()), Some([p]) => (*p as usize, xs.clone()), Some(&[p1, p2, p3, p4]) => { let p1 = p1 as usize; let p2 = p2 as usize; let p3 = p3 as usize; let p4 = p4 as usize; if p1 != p2 || p1 != p3 || p1 != p4 { (0, xs.pad_with_zeros(2, p1, p3)?.pad_with_zeros(3, p2, p4)?) } else { (p1, xs.clone()) } } Some(pads) => { bail!("more pads than expected in conv2d {pads:?} {}", node.name) } }; let strides = match strides { None => 1, Some([p]) => *p as usize, Some([p1, p2]) => { if p1 != p2 { bail!( "strides have to be the same on both axis {pads:?} {}", node.name ) } *p1 as usize } Some(s) => { bail!("more strides than expected in conv2d {s:?} {}", node.name) } }; let dilations = match dilations { None => 1, Some([p]) => *p as usize, Some([p1, p2]) => { if p1 != p2 { bail!( "dilations have to be the same on both axis {pads:?} {}", node.name ) } *p1 as usize } Some(s) => { bail!("more dilations than expected in conv2d {s:?} {}", node.name) } }; xs.conv2d(ws, pads, strides, dilations, groups as usize)? } rank => bail!( "unsupported rank for weight matrix {rank} in conv {}", node.name ), }; let ys = if node.input.len() > 2 { let bs = get(&node.input[2])?; let mut bs_shape = vec![1; ys.rank()]; bs_shape[1] = bs.elem_count(); ys.broadcast_add(&bs.reshape(bs_shape)?)? } else { ys }; values.insert(node.output[0].clone(), ys); } "Concat" => { // https://github.com/onnx/onnx/blob/main/docs/Operators.md#Concat let inputs = node .input .iter() .map(|n| Ok(get(n.as_str())?.clone())) .collect::<Result<Vec<Value>>>()?; let axis: i64 = *get_attr(node, "axis")?; if inputs.is_empty() { bail!("empty concat") }; let axis = inputs[0].normalize_axis(axis)?; let output = Tensor::cat(&inputs, axis)?; values.insert(node.output[0].clone(), output); } "Abs" => { let input = get(&node.input[0])?; let output = input.abs()?; values.insert(node.output[0].clone(), output); } "Cos" => { let input = get(&node.input[0])?; let output = input.cos()?; values.insert(node.output[0].clone(), output); } "Sin" => { let input = get(&node.input[0])?; let output = input.sin()?; values.insert(node.output[0].clone(), output); } "Neg" => { let input = get(&node.input[0])?; let output = input.neg()?; values.insert(node.output[0].clone(), output); } "Erf" => { let input = get(&node.input[0])?; let output = input.erf()?; values.insert(node.output[0].clone(), output); } "Tanh" => { let input = get(&node.input[0])?; let output = input.tanh()?; values.insert(node.output[0].clone(), output); } "Sigmoid" => { let input = get(&node.input[0])?; let output = candle_nn::ops::sigmoid(input)?; values.insert(node.output[0].clone(), output); } "Gelu" => { let input = get(&node.input[0])?; let output = input.gelu_erf()?; values.insert(node.output[0].clone(), output); } "Relu" => { let input = get(&node.input[0])?; let output = input.relu()?; values.insert(node.output[0].clone(), output); } // https://github.com/onnx/onnx/blob/main/docs/Operators.md#Constant "Constant" => { let value = match node.attribute.iter().find(|attr| attr.name == "value") { None => { // TODO: support sparse_value etc. bail!("cannot find 'value' attr in 'Constant' for {}", node.name) } Some(value) => value, }; let output = match value.r#type() { AttributeType::Tensor => { let t = value.t.as_ref().unwrap(); get_tensor(t, &node.name)? } rtype => bail!("unsupported 'value' type {rtype:?} for {}", node.name), }; values.insert(node.output[0].clone(), output); } // https://github.com/onnx/onnx/blob/main/docs/Operators.md#Cast "Cast" => { let input = get(&node.input[0])?; let dt: i64 = *get_attr(node, "to")?; let dtype = match DataType::try_from(dt as i32) { Ok(DataType::Int32) => DType::I64, Ok(dt) => match dtype(dt) { Some(dt) => dt, None => { bail!("unsupported 'to' value {dt:?} for cast {}", node.name) } }, Err(_) => { bail!("unsupported 'to' value {dt:?} for cast {}", node.name) } }; let output = input.to_dtype(dtype)?; values.insert(node.output[0].clone(), output); } // https://github.com/onnx/onnx/blob/main/docs/Operators.md#CumSum "CumSum" => { let exclusive = get_attr_opt::<i64>(node, "exclusive")? .copied() .unwrap_or(0); let reverse = get_attr_opt::<i64>(node, "reverse")?.copied().unwrap_or(0); if exclusive != 0 { bail!("only exclusive == 0 is supported in CumSum") } if reverse != 0 { bail!("only reverse == 0 is supported in CumSum") } let input = get(&node.input[0])?; let axis = get(&node.input[1])? .to_dtype(DType::U32)? .to_vec0::<u32>()?; let output = input.cumsum(axis as usize)?; values.insert(node.output[0].clone(), output); } // https://github.com/onnx/onnx/blob/main/docs/Operators.md#flatten "Flatten" => { let axis = get_attr_opt::<i64>(node, "axis")?.copied().unwrap_or(1) as usize; let input = get(&node.input[0])?; let first_part: usize = input.shape().dims().iter().take(axis).product(); let end_index = input.shape().dims().iter().product::<usize>(); let new_shape = (first_part, end_index / first_part); let output = input.reshape(new_shape)?; values.insert(node.output[0].clone(), output); } op_type => bail!("unsupported op_type {op_type} for op {node:?}"), } } graph .output .iter() .map(|output| match values.remove(&output.name) { None => bail!("cannot find output {}", output.name), Some(value) => Ok((output.name.clone(), value)), }) .collect() }
candle/candle-onnx/src/eval.rs/0
{ "file_path": "candle/candle-onnx/src/eval.rs", "repo_id": "candle", "token_count": 20779 }
34
import candle from typing import Dict, Tuple, Any from candle import Tensor, QTensor, utils, nn from candle.nn import Module, ModuleList def masked_fill(on_false: Tensor, mask: Tensor, on_true: Tensor): shape = mask.shape on_true = candle.tensor(on_true).broadcast_as(shape) return mask.where_cond(on_true, on_false) def precompute_freqs_cis(hparams: Dict[str, Any], freq_base: float, max_seq_len: int): head_dim = hparams["n_embd"] // hparams["n_head"] theta = [1.0 / freq_base ** (i / head_dim) for i in range(0, head_dim, 2)] theta = candle.tensor(theta) idx_theta = [float(i) for i in range(max_seq_len)] idx_theta = candle.tensor(idx_theta).reshape((max_seq_len, 1)) m = idx_theta.matmul(theta.unsqueeze(0)) return (m.cos(), m.sin()) class RmsNorm(Module): def __init__(self, qtensor: QTensor): super().__init__() self.weight = qtensor.dequantize() def forward(self, x: Tensor) -> Tensor: b_size, seq_len, hidden_size = x.shape norm_x = x.sqr().sum_keepdim(2) / hidden_size x_normed = x.broadcast_div((norm_x + 1e-5).sqrt()) return x_normed.broadcast_mul(self.weight) class QuantizedLayer(Module): def __init__( self, layer_idx: int, hparams: Dict[str, Any], all_tensors: Dict[str, QTensor], cos_sin: Tuple[Tensor, Tensor], ): super().__init__() p = f"layers.{layer_idx}" self.attention_wq = all_tensors[f"{p}.attention.wq.weight"] self.attention_wk = all_tensors[f"{p}.attention.wk.weight"] self.attention_wv = all_tensors[f"{p}.attention.wv.weight"] self.attention_wo = all_tensors[f"{p}.attention.wo.weight"] self.ffw1 = all_tensors[f"{p}.feed_forward.w1.weight"] self.ffw2 = all_tensors[f"{p}.feed_forward.w2.weight"] self.ffw3 = all_tensors[f"{p}.feed_forward.w3.weight"] self.attn_norm = RmsNorm(all_tensors[f"{p}.attention_norm.weight"]) self.ffn_norm = RmsNorm(all_tensors[f"{p}.ffn_norm.weight"]) self.n_head = hparams["n_head"] self.n_kv_head = self.n_head self.head_dim = hparams["n_embd"] // self.n_head self.kv_cache = None self.cos = cos_sin[0] self.sin = cos_sin[1] self._non_persistent_buffers_set.add("cos") self._non_persistent_buffers_set.add("sin") def forward(self, x: Tensor, mask: Tensor, index_pos: int) -> Tensor: residual = x x = self.attn_norm(x) attn = self.forward_attn(x, mask, index_pos) x = attn + residual residual = x x = self.ffn_norm(x) w1 = self.ffw1.matmul_t(x) w3 = self.ffw3.matmul_t(x) mlp = self.ffw2.matmul_t(nn.silu(w1) * w3) return mlp + residual def forward_attn(self, x: Tensor, mask: Tensor, index_pos: int): b_size, seq_len, n_embd = x.shape q = self.attention_wq.matmul_t(x) k = self.attention_wk.matmul_t(x) v = self.attention_wv.matmul_t(x) q = q.reshape((b_size, seq_len, self.n_head, self.head_dim)).transpose(1, 2) k = k.reshape((b_size, seq_len, self.n_kv_head, self.head_dim)).transpose(1, 2) v = v.reshape((b_size, seq_len, self.n_kv_head, self.head_dim)).transpose(1, 2) q = self.apply_rotary_emb(q, index_pos) k = self.apply_rotary_emb(k, index_pos) if self.kv_cache is not None and index_pos > 0: prev_k, prev_v = self.kv_cache k = candle.cat([prev_k, k], 2).contiguous() v = candle.cat([prev_v, v], 2).contiguous() self.kv_cache = (k, v) # TODO: maybe repeat k/v here if we start supporting MQA. att = q.matmul(k.t()) / self.head_dim**0.5 mask = mask.broadcast_as(att.shape) att = masked_fill(att, mask, float("-inf")) att = nn.softmax(att, -1) y = att.matmul(v.contiguous()) y = y.transpose(1, 2).reshape((b_size, seq_len, n_embd)) return self.attention_wo.matmul_t(y) def apply_rotary_emb(self, x: Tensor, index_pos: int): b_size, n_head, seq_len, n_embd = x.shape cos = self.cos.narrow(0, index_pos, seq_len).reshape((seq_len, n_embd // 2, 1)) sin = self.sin.narrow(0, index_pos, seq_len).reshape((seq_len, n_embd // 2, 1)) x = x.reshape((b_size, n_head, seq_len, n_embd // 2, 2)) x0 = x.narrow(-1, 0, 1) x1 = x.narrow(-1, 1, 1) y0 = x0.broadcast_mul(cos) - x1.broadcast_mul(sin) y1 = x0.broadcast_mul(sin) + x1.broadcast_mul(cos) rope = candle.cat([y0, y1], -1) return rope.flatten_from(-2) class QuantizedLlama(Module): def __init__(self, hparams: Dict[str, Any], all_tensors: Dict[str, QTensor]): super().__init__() self.tok_embeddings = all_tensors["tok_embeddings.weight"].dequantize() self.norm = RmsNorm(all_tensors["norm.weight"]) self.output = all_tensors["output.weight"] self.layers = ModuleList() rope_freq = hparams.get("rope_freq", 10000.0) cos_sin = precompute_freqs_cis(hparams, rope_freq, hparams["context_length"]) for layer_idx in range(hparams["n_layer"]): layer = QuantizedLayer(layer_idx, hparams, all_tensors, cos_sin) self.layers.append(layer) def forward(self, token: Tensor, index_pos: int) -> Tensor: b_size, seq_len = token.shape vocab_size, hidden_size = self.tok_embeddings.shape token = token.reshape((b_size * seq_len,)) x = self.tok_embeddings.index_select(token, 0) x = x.reshape((b_size, seq_len, hidden_size)) mask = [int(j > i) for j in range(seq_len) for i in range(seq_len)] mask = candle.tensor(mask).reshape((seq_len, seq_len)) for layer in self.layers: x = layer(x, mask, index_pos) x = self.norm(x) x = x.narrow(1, -1, 1).squeeze(1) x = self.output.matmul_t(x) return x
candle/candle-pyo3/py_src/candle/models/llama.py/0
{ "file_path": "candle/candle-pyo3/py_src/candle/models/llama.py", "repo_id": "candle", "token_count": 2981 }
35
use std::collections::HashMap; use crate::utils::wrap_err; use crate::{PyDType, PyTensor}; use candle_onnx::eval::{dtype, get_tensor, simple_eval}; use candle_onnx::onnx::tensor_proto::DataType; use candle_onnx::onnx::tensor_shape_proto::dimension::Value; use candle_onnx::onnx::type_proto::{Tensor as ONNXTensor, Value as ONNXValue}; use candle_onnx::onnx::{ModelProto, ValueInfoProto}; use pyo3::exceptions::PyValueError; use pyo3::prelude::*; use pyo3::types::{PyList, PyTuple}; #[derive(Clone, Debug)] #[pyclass(name = "ONNXTensorDescription")] /// A wrapper around an ONNX tensor description. pub struct PyONNXTensorDescriptor(ONNXTensor); #[pymethods] impl PyONNXTensorDescriptor { #[getter] /// The data type of the tensor. /// &RETURNS&: DType fn dtype(&self) -> PyResult<PyDType> { match DataType::try_from(self.0.elem_type) { Ok(dt) => match dtype(dt) { Some(dt) => Ok(PyDType(dt)), None => Err(PyValueError::new_err(format!( "unsupported 'value' data-type {dt:?}" ))), }, type_ => Err(PyValueError::new_err(format!( "unsupported input type {type_:?}" ))), } } #[getter] /// The shape of the tensor. /// &RETURNS&: Tuple[Union[int,str,Any]] fn shape(&self, py: Python) -> PyResult<Py<PyTuple>> { let shape = PyList::empty(py); if let Some(d) = &self.0.shape { for dim in d.dim.iter() { if let Some(value) = &dim.value { match value { Value::DimValue(v) => shape.append(*v)?, Value::DimParam(s) => shape.append(s.clone())?, }; } else { return Err(PyValueError::new_err("None value in shape")); } } } Ok(shape.to_tuple().into()) } fn __repr__(&self, py: Python) -> String { match (self.shape(py), self.dtype()) { (Ok(shape), Ok(dtype)) => format!( "TensorDescriptor[shape: {:?}, dtype: {:?}]", shape.to_string(), dtype.__str__() ), (Err(_), Err(_)) => "TensorDescriptor[shape: unknown, dtype: unknown]".to_string(), (Err(_), Ok(dtype)) => format!( "TensorDescriptor[shape: unknown, dtype: {:?}]", dtype.__str__() ), (Ok(shape), Err(_)) => format!( "TensorDescriptor[shape: {:?}, dtype: unknown]", shape.to_string() ), } } fn __str__(&self, py: Python) -> String { self.__repr__(py) } } #[derive(Clone, Debug)] #[pyclass(name = "ONNXModel")] /// A wrapper around an ONNX model. pub struct PyONNXModel(ModelProto); fn extract_tensor_descriptions( value_infos: &[ValueInfoProto], ) -> HashMap<String, PyONNXTensorDescriptor> { let mut map = HashMap::new(); for value_info in value_infos.iter() { let input_type = match &value_info.r#type { Some(input_type) => input_type, None => continue, }; let input_type = match &input_type.value { Some(input_type) => input_type, None => continue, }; let tensor_type: &ONNXTensor = match input_type { ONNXValue::TensorType(tt) => tt, _ => continue, }; map.insert( value_info.name.to_string(), PyONNXTensorDescriptor(tensor_type.clone()), ); } map } #[pymethods] impl PyONNXModel { #[new] #[pyo3(text_signature = "(self, path:str)")] /// Load an ONNX model from the given path. fn new(path: String) -> PyResult<Self> { let model: ModelProto = candle_onnx::read_file(path).map_err(wrap_err)?; Ok(PyONNXModel(model)) } #[getter] /// The version of the IR this model targets. /// &RETURNS&: int fn ir_version(&self) -> i64 { self.0.ir_version } #[getter] /// The producer of the model. /// &RETURNS&: str fn producer_name(&self) -> String { self.0.producer_name.clone() } #[getter] /// The version of the producer of the model. /// &RETURNS&: str fn producer_version(&self) -> String { self.0.producer_version.clone() } #[getter] /// The domain of the operator set of the model. /// &RETURNS&: str fn domain(&self) -> String { self.0.domain.clone() } #[getter] /// The version of the model. /// &RETURNS&: int fn model_version(&self) -> i64 { self.0.model_version } #[getter] /// The doc string of the model. /// &RETURNS&: str fn doc_string(&self) -> String { self.0.doc_string.clone() } /// Get the weights of the model. /// &RETURNS&: Dict[str, Tensor] fn initializers(&self) -> PyResult<HashMap<String, PyTensor>> { let mut map = HashMap::new(); if let Some(graph) = self.0.graph.as_ref() { for tensor_description in graph.initializer.iter() { let tensor = get_tensor(tensor_description, tensor_description.name.as_str()) .map_err(wrap_err)?; map.insert(tensor_description.name.to_string(), PyTensor(tensor)); } } Ok(map) } #[getter] /// The inputs of the model. /// &RETURNS&: Optional[Dict[str, ONNXTensorDescription]] fn inputs(&self) -> Option<HashMap<String, PyONNXTensorDescriptor>> { if let Some(graph) = self.0.graph.as_ref() { return Some(extract_tensor_descriptions(&graph.input)); } None } #[getter] /// The outputs of the model. /// &RETURNS&: Optional[Dict[str, ONNXTensorDescription]] fn outputs(&self) -> Option<HashMap<String, PyONNXTensorDescriptor>> { if let Some(graph) = self.0.graph.as_ref() { return Some(extract_tensor_descriptions(&graph.output)); } None } #[pyo3(text_signature = "(self, inputs:Dict[str,Tensor])")] /// Run the model on the given inputs. /// &RETURNS&: Dict[str,Tensor] fn run(&self, inputs: HashMap<String, PyTensor>) -> PyResult<HashMap<String, PyTensor>> { let unwrapped_tensors = inputs.into_iter().map(|(k, v)| (k.clone(), v.0)).collect(); let result = simple_eval(&self.0, unwrapped_tensors).map_err(wrap_err)?; Ok(result .into_iter() .map(|(k, v)| (k.clone(), PyTensor(v))) .collect()) } }
candle/candle-pyo3/src/onnx.rs/0
{ "file_path": "candle/candle-pyo3/src/onnx.rs", "repo_id": "candle", "token_count": 3266 }
36
pub mod generation; pub mod models; pub mod object_detection; pub mod pipelines; pub mod quantized_nn; pub mod quantized_var_builder; pub mod utils;
candle/candle-transformers/src/lib.rs/0
{ "file_path": "candle/candle-transformers/src/lib.rs", "repo_id": "candle", "token_count": 47 }
37
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; pub const MAX_SEQ_LEN: usize = 4096; #[derive(Debug, Clone, serde::Deserialize)] pub struct LlamaConfig { 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, } fn default_rope() -> f32 { 10_000.0 } impl LlamaConfig { 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.unwrap_or(self.num_attention_heads), rms_norm_eps: self.rms_norm_eps, rope_theta: self.rope_theta, use_flash_attn, } } } #[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, } impl Config { pub fn config_7b_v1(use_flash_attn: bool) -> Self { Self { hidden_size: 4096, intermediate_size: 11008, vocab_size: 32000, num_hidden_layers: 32, num_attention_heads: 32, num_key_value_heads: 32, use_flash_attn, rms_norm_eps: 1e-6, rope_theta: 10_000.0, } } pub fn config_7b_v2(use_flash_attn: bool) -> Self { Self { hidden_size: 4096, intermediate_size: 11008, vocab_size: 32000, num_hidden_layers: 32, num_attention_heads: 32, num_key_value_heads: 32, use_flash_attn, rms_norm_eps: 1e-5, rope_theta: 10_000.0, } } } #[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, } impl Cache { pub fn new(use_kv_cache: bool, dtype: DType, config: &Config, device: &Device) -> Result<Self> { // precompute freqs_cis let n_elem = config.hidden_size / config.num_attention_heads; let theta: Vec<_> = (0..n_elem) .step_by(2) .map(|i| 1f32 / config.rope_theta.powf(i as f32 / n_elem as f32)) .collect(); let theta = Tensor::new(theta.as_slice(), device)?; let idx_theta = Tensor::arange(0, MAX_SEQ_LEN as u32, device)? .to_dtype(DType::F32)? .reshape((MAX_SEQ_LEN, 1))? .matmul(&theta.reshape((1, theta.elem_count()))?)?; // This is different from the paper, see: // https://github.com/huggingface/transformers/blob/6112b1c6442aaf7affd2b0676a1cd4eee30c45cf/src/transformers/models/llama/modeling_llama.py#L112 let idx_theta = Tensor::cat(&[&idx_theta, &idx_theta], D::Minus1)?; 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, } #[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)?; let cos = cos.broadcast_as((b_sz, 1, seq_len, hidden_size))?; let sin = sin.broadcast_as((b_sz, 1, seq_len, hidden_size))?; let x1 = x.narrow(D::Minus1, 0, hidden_size / 2)?; let x2 = x.narrow(D::Minus1, hidden_size / 2, hidden_size / 2)?; let rotate_x = Tensor::cat(&[&x2.neg()?, &x1], D::Minus1)?; let rope = (x.broadcast_mul(&cos)? + rotate_x.broadcast_mul(&sin)?)?; Ok(rope) } 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)?; let k = k .reshape((b_sz, seq_len, self.num_key_value_heads, self.head_dim))? .transpose(1, 2)?; 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 > MAX_SEQ_LEN { k = k .narrow(D::Minus1, k_seq_len - MAX_SEQ_LEN, MAX_SEQ_LEN)? .contiguous()? } let v_seq_len = v.dims()[1]; if v_seq_len > 2 * MAX_SEQ_LEN { v = v .narrow(D::Minus1, v_seq_len - MAX_SEQ_LEN, MAX_SEQ_LEN)? .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 mask = cache.mask(seq_len)?.broadcast_as(att.shape())?; let att = 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> { let n_rep = self.num_attention_heads / self.num_key_value_heads; if n_rep == 1 { Ok(x) } else { let (b_sz, n_kv_head, seq_len, head_dim) = x.dims4()?; let x = x .unsqueeze(2)? .expand((b_sz, n_kv_head, n_rep, seq_len, head_dim))? .reshape((b_sz, n_kv_head * n_rep, seq_len, head_dim))?; Ok(x) } } 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, }) } } 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 Llama { wte: Embedding, blocks: Vec<Block>, ln_f: RmsNorm, lm_head: Linear, } impl Llama { 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, ..))?; 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/llama.rs/0
{ "file_path": "candle/candle-transformers/src/models/llama.rs", "repo_id": "candle", "token_count": 7514 }
38
use std::collections::HashMap; use candle::quantized::QTensor; use candle::quantized::{ggml_file, gguf_file}; use candle::{DType, Device, IndexOp, Result, Tensor, D}; use candle_nn::{Embedding, Module}; pub const MAX_SEQ_LEN: usize = 4096; #[derive(Debug, Clone)] struct RmsNorm { inner: candle_nn::LayerNorm, span: tracing::Span, } impl RmsNorm { fn new(scale: QTensor, eps: f32) -> Result<Self> { let span = tracing::span!(tracing::Level::TRACE, "rms-norm"); let scale = scale.dequantize(&scale.device())?; let inner = candle_nn::LayerNorm::rms_norm(scale, eps as f64); Ok(Self { inner, span }) } fn forward(&self, x: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); self.inner.forward(x) } } // QMatMul wrapper adding some tracing. #[derive(Debug, Clone)] struct QMatMul { inner: candle::quantized::QMatMul, span: tracing::Span, } impl QMatMul { fn from_qtensor(qtensor: QTensor) -> Result<Self> { let inner = candle::quantized::QMatMul::from_qtensor(qtensor)?; let span = tracing::span!(tracing::Level::TRACE, "qmatmul"); Ok(Self { inner, span }) } fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); self.inner.forward(xs) } } #[derive(Debug, Clone)] struct Mlp { feed_forward_w1: QMatMul, feed_forward_w2: QMatMul, feed_forward_w3: QMatMul, } impl Module for Mlp { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let w1 = self.feed_forward_w1.forward(xs)?; let w3 = self.feed_forward_w3.forward(xs)?; self.feed_forward_w2 .forward(&(candle_nn::ops::silu(&w1)? * w3)?) } } #[derive(Debug, Clone)] enum MlpOrMoe { Mlp(Mlp), MoE { n_expert_used: usize, feed_forward_gate_inp: QMatMul, experts: Vec<Mlp>, }, } impl Module for MlpOrMoe { fn forward(&self, xs: &Tensor) -> Result<Tensor> { match self { Self::MoE { feed_forward_gate_inp, experts, n_expert_used, } => { let (b_size, seq_len, hidden_dim) = xs.dims3()?; let xs = xs.reshape(((), hidden_dim))?; let router_logits = feed_forward_gate_inp.forward(&xs)?; let routing_weights = candle_nn::ops::softmax_last_dim(&router_logits)?; // In order to extract topk, we extract the data from the tensor and manipulate it // directly. Maybe we will want to use some custom ops instead at some point. let routing_weights = routing_weights.to_dtype(DType::F32)?.to_vec2::<f32>()?; // routing_weights, selected_experts = torch.topk(routing_weights, self.top_k, dim=-1) // top_x contains the row indexes to evaluate for each expert. let mut top_x = vec![vec![]; experts.len()]; let mut selected_rws = vec![vec![]; experts.len()]; for (row_idx, rw) in routing_weights.iter().enumerate() { let mut dst = (0..rw.len() as u32).collect::<Vec<u32>>(); dst.sort_by(|&i, &j| rw[j as usize].total_cmp(&rw[i as usize])); let mut sum_routing_weights = 0f32; for &expert_idx in dst.iter().take(*n_expert_used) { let expert_idx = expert_idx as usize; let routing_weight = rw[expert_idx]; sum_routing_weights += routing_weight; top_x[expert_idx].push(row_idx as u32); } for &expert_idx in dst.iter().take(*n_expert_used) { let expert_idx = expert_idx as usize; let routing_weight = rw[expert_idx]; selected_rws[expert_idx].push(routing_weight / sum_routing_weights) } } // routing_weights /= routing_weights.sum(dim=-1, keepdim=True) // expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0) let mut ys = xs.zeros_like()?; for (expert_idx, expert_layer) in experts.iter().enumerate() { let top_x = &top_x[expert_idx]; if top_x.is_empty() { continue; } let top_x = Tensor::new(top_x.as_slice(), xs.device())?; let selected_rws = Tensor::new(selected_rws[expert_idx].as_slice(), xs.device())? .reshape(((), 1))?; // Index the correct hidden states and compute the expert hidden state for // the current expert. We need to make sure to multiply the output hidden // states by `routing_weights` on the corresponding tokens (top-1 and top-2) let current_state = xs.index_select(&top_x, 0)?.reshape(((), hidden_dim))?; // current_hidden_states = expert_layer(current_state, routing_weights[top_x_list, idx_list, None]) let current_hidden_states = expert_layer.forward(&current_state)?; let current_hidden_states = current_hidden_states.broadcast_mul(&selected_rws)?; ys = ys.index_add(&top_x, &current_hidden_states, 0)?; } let ys = ys.reshape((b_size, seq_len, hidden_dim))?; Ok(ys) } Self::Mlp(mlp) => mlp.forward(xs), } } } #[derive(Debug, Clone)] struct LayerWeights { attention_wq: QMatMul, attention_wk: QMatMul, attention_wv: QMatMul, attention_wo: QMatMul, attention_norm: RmsNorm, mlp_or_moe: MlpOrMoe, ffn_norm: RmsNorm, n_head: usize, n_kv_head: usize, head_dim: usize, cos: Tensor, sin: Tensor, neg_inf: Tensor, kv_cache: Option<(Tensor, Tensor)>, span_attn: tracing::Span, span_rot: tracing::Span, span_mlp: tracing::Span, } fn masked_fill(on_false: &Tensor, mask: &Tensor, on_true: &Tensor) -> Result<Tensor> { let shape = mask.shape(); let m = mask.where_cond(&on_true.broadcast_as(shape.dims())?, on_false)?; Ok(m) } impl LayerWeights { fn apply_rotary_emb(&self, x: &Tensor, index_pos: usize) -> Result<Tensor> { let _enter = self.span_rot.enter(); let (b_sz, n_head, seq_len, n_embd) = x.dims4()?; let cos = self .cos .narrow(0, index_pos, seq_len)? .reshape((seq_len, n_embd / 2, 1))?; let sin = self .sin .narrow(0, index_pos, seq_len)? .reshape((seq_len, n_embd / 2, 1))?; let cos = cos.broadcast_as((b_sz, 1, seq_len, n_embd / 2, 1))?; let sin = sin.broadcast_as((b_sz, 1, seq_len, n_embd / 2, 1))?; // This mimics the llama.cpp behavior. // https://github.com/ggerganov/llama.cpp/blob/1f0bccb27929e261744c979bc75114955da49e98/ggml.c#L12104-L12105 // The x0 and x1 value are interleaved on the n_embd (= head_dim) dimension. // The resulting y0 and y1 are also interleaved with: // y0 = x0*cos - x1*sin // y1 = x0*sin + x1*cos let x = x.reshape((b_sz, n_head, seq_len, n_embd / 2, 2))?; let x0 = x.narrow(D::Minus1, 0, 1)?; let x1 = x.narrow(D::Minus1, 1, 1)?; let y0 = (x0.broadcast_mul(&cos)? - x1.broadcast_mul(&sin)?)?; let y1 = (x0.broadcast_mul(&sin)? + x1.broadcast_mul(&cos)?)?; let rope = Tensor::cat(&[y0, y1], D::Minus1)?; let rope = rope.flatten_from(D::Minus2)?; Ok(rope) } fn forward_attn(&mut self, x: &Tensor, mask: &Tensor, index_pos: usize) -> Result<Tensor> { let _enter = self.span_attn.enter(); let (b_sz, seq_len, n_embd) = x.dims3()?; let q = self.attention_wq.forward(x)?; let k = self.attention_wk.forward(x)?; let v = self.attention_wv.forward(x)?; let q = q .reshape((b_sz, seq_len, self.n_head, self.head_dim))? .transpose(1, 2)?; let k = k .reshape((b_sz, seq_len, self.n_kv_head, self.head_dim))? .transpose(1, 2)?; let v = v .reshape((b_sz, seq_len, self.n_kv_head, self.head_dim))? .transpose(1, 2)?; let q = self.apply_rotary_emb(&q, index_pos)?; let k = self.apply_rotary_emb(&k, index_pos)?; let (k, v) = match &self.kv_cache { None => (k, v), Some((k_cache, v_cache)) => { if index_pos == 0 { (k, v) } else { let k = Tensor::cat(&[k_cache, &k], 2)?.contiguous()?; let v = Tensor::cat(&[v_cache, &v], 2)?.contiguous()?; (k, v) } } }; self.kv_cache = Some((k.clone(), v.clone())); // Support for MQA, useful for 70B models. let k = self.repeat_kv(k)?; let v = self.repeat_kv(v)?; let att = (q.matmul(&k.t()?)? / (self.head_dim as f64).sqrt())?; let mask = mask.broadcast_as(att.shape())?; let att = masked_fill(&att, &mask, &self.neg_inf)?; let att = candle_nn::ops::softmax_last_dim(&att)?; // Convert to contiguous as matmul doesn't support strided vs for now. let y = att.matmul(&v.contiguous()?)?; let y = y.transpose(1, 2)?.reshape(&[b_sz, seq_len, n_embd])?; let y = self.attention_wo.forward(&y)?; Ok(y) } fn repeat_kv(&self, x: Tensor) -> Result<Tensor> { let n_rep = self.n_head / self.n_kv_head; if n_rep == 1 { Ok(x) } else { let (b_sz, n_kv_head, seq_len, head_dim) = x.dims4()?; let x = x .unsqueeze(2)? .expand((b_sz, n_kv_head, n_rep, seq_len, head_dim))? .reshape((b_sz, n_kv_head * n_rep, seq_len, head_dim))?; Ok(x) } } } #[derive(Debug, Clone)] pub struct ModelWeights { tok_embeddings: Embedding, layers: Vec<LayerWeights>, norm: RmsNorm, output: QMatMul, masks: HashMap<usize, Tensor>, span: tracing::Span, span_output: tracing::Span, } fn precomput_freqs_cis( head_dim: usize, freq_base: f32, device: &Device, ) -> Result<(Tensor, Tensor)> { let theta: Vec<_> = (0..head_dim) .step_by(2) .map(|i| 1f32 / freq_base.powf(i as f32 / head_dim as f32)) .collect(); let theta = Tensor::new(theta.as_slice(), device)?; let idx_theta = Tensor::arange(0, MAX_SEQ_LEN as u32, device)? .to_dtype(DType::F32)? .reshape((MAX_SEQ_LEN, 1))? .matmul(&theta.reshape((1, theta.elem_count()))?)?; let cos = idx_theta.cos()?; let sin = idx_theta.sin()?; Ok((cos, sin)) } impl ModelWeights { pub fn from_ggml(mut ct: ggml_file::Content, gqa: usize) -> Result<Self> { let head_dim = (ct.hparams.n_embd / ct.hparams.n_head) as usize; let (cos, sin) = precomput_freqs_cis(head_dim, 10000., &ct.device)?; let neg_inf = Tensor::new(f32::NEG_INFINITY, &ct.device)?; let tok_embeddings = ct.remove("tok_embeddings.weight")?; let tok_embeddings = tok_embeddings.dequantize(&ct.device)?; let norm = RmsNorm::new(ct.remove("norm.weight")?, 1e-5)?; let output = ct.remove("output.weight")?; let mut layers = Vec::with_capacity(ct.hparams.n_layer as usize); for layer_idx in 0..ct.hparams.n_layer { let prefix = format!("layers.{layer_idx}"); let attention_wq = ct.remove(&format!("{prefix}.attention.wq.weight"))?; let attention_wk = ct.remove(&format!("{prefix}.attention.wk.weight"))?; let attention_wv = ct.remove(&format!("{prefix}.attention.wv.weight"))?; let attention_wo = ct.remove(&format!("{prefix}.attention.wo.weight"))?; let mlp_or_moe = { let feed_forward_w1 = ct.remove(&format!("{prefix}.feed_forward.w1.weight"))?; let feed_forward_w2 = ct.remove(&format!("{prefix}.feed_forward.w2.weight"))?; let feed_forward_w3 = ct.remove(&format!("{prefix}.feed_forward.w3.weight"))?; MlpOrMoe::Mlp(Mlp { feed_forward_w1: QMatMul::from_qtensor(feed_forward_w1)?, feed_forward_w2: QMatMul::from_qtensor(feed_forward_w2)?, feed_forward_w3: QMatMul::from_qtensor(feed_forward_w3)?, }) }; let attention_norm = ct.remove(&format!("{prefix}.attention_norm.weight"))?; let ffn_norm = ct.remove(&format!("{prefix}.ffn_norm.weight"))?; let span_attn = tracing::span!(tracing::Level::TRACE, "attn"); let span_rot = tracing::span!(tracing::Level::TRACE, "attn-rot"); let span_mlp = tracing::span!(tracing::Level::TRACE, "attn-mlp"); layers.push(LayerWeights { attention_wq: QMatMul::from_qtensor(attention_wq)?, attention_wk: QMatMul::from_qtensor(attention_wk)?, attention_wv: QMatMul::from_qtensor(attention_wv)?, attention_wo: QMatMul::from_qtensor(attention_wo)?, attention_norm: RmsNorm::new(attention_norm, 1e-5)?, mlp_or_moe, ffn_norm: RmsNorm::new(ffn_norm, 1e-5)?, n_head: ct.hparams.n_head as usize, n_kv_head: ct.hparams.n_head as usize / gqa, head_dim: (ct.hparams.n_embd / ct.hparams.n_head) as usize, cos: cos.clone(), sin: sin.clone(), neg_inf: neg_inf.clone(), kv_cache: None, span_attn, span_rot, span_mlp, }) } let span = tracing::span!(tracing::Level::TRACE, "model"); let span_output = tracing::span!(tracing::Level::TRACE, "output"); Ok(Self { tok_embeddings: Embedding::new(tok_embeddings, ct.hparams.n_embd as usize), layers, norm, output: QMatMul::from_qtensor(output)?, masks: HashMap::new(), span, span_output, }) } pub fn from_gguf<R: std::io::Seek + std::io::Read>( ct: gguf_file::Content, reader: &mut R, device: &Device, ) -> Result<Self> { let md_get = |s: &str| match ct.metadata.get(s) { None => candle::bail!("cannot find {s} in metadata"), Some(v) => Ok(v), }; // Parameter extraction from metadata. let n_expert = md_get("llama.expert_count") .and_then(|v| v.to_u32()) .unwrap_or(0) as usize; let n_expert_used = md_get("llama.expert_used_count") .and_then(|v| v.to_u32()) .unwrap_or(0) as usize; let head_count = md_get("llama.attention.head_count")?.to_u32()? as usize; let head_count_kv = md_get("llama.attention.head_count_kv")?.to_u32()? as usize; let block_count = md_get("llama.block_count")?.to_u32()? as usize; let embedding_length = md_get("llama.embedding_length")?.to_u32()? as usize; let rope_dim = md_get("llama.rope.dimension_count")?.to_u32()? as usize; // Strangely this value is generally 1e-6 in GGUF file but used to be 1e-5 by default. let rms_norm_eps = md_get("llama.attention.layer_norm_rms_epsilon")?.to_f32()?; let rope_freq_base = md_get("llama.rope.freq_base") .and_then(|m| m.to_f32()) .unwrap_or(10000f32); let (cos, sin) = precomput_freqs_cis(rope_dim, rope_freq_base, device)?; let neg_inf = Tensor::new(f32::NEG_INFINITY, device)?; let tok_embeddings = ct.tensor(reader, "token_embd.weight", device)?; let tok_embeddings = tok_embeddings.dequantize(device)?; let norm = RmsNorm::new( ct.tensor(reader, "output_norm.weight", device)?, rms_norm_eps, )?; let output = ct.tensor(reader, "output.weight", device)?; let mut layers = Vec::with_capacity(block_count); for layer_idx in 0..block_count { let prefix = format!("blk.{layer_idx}"); let attention_wq = ct.tensor(reader, &format!("{prefix}.attn_q.weight"), device)?; let attention_wk = ct.tensor(reader, &format!("{prefix}.attn_k.weight"), device)?; let attention_wv = ct.tensor(reader, &format!("{prefix}.attn_v.weight"), device)?; let attention_wo = ct.tensor(reader, &format!("{prefix}.attn_output.weight"), device)?; let mlp_or_moe = if n_expert <= 1 { let feed_forward_w1 = ct.tensor(reader, &format!("{prefix}.ffn_gate.weight"), device)?; let feed_forward_w2 = ct.tensor(reader, &format!("{prefix}.ffn_down.weight"), device)?; let feed_forward_w3 = ct.tensor(reader, &format!("{prefix}.ffn_up.weight"), device)?; MlpOrMoe::Mlp(Mlp { feed_forward_w1: QMatMul::from_qtensor(feed_forward_w1)?, feed_forward_w2: QMatMul::from_qtensor(feed_forward_w2)?, feed_forward_w3: QMatMul::from_qtensor(feed_forward_w3)?, }) } else { let feed_forward_gate_inp = ct.tensor(reader, &format!("{prefix}.ffn_gate_inp.weight"), device)?; let mut experts = Vec::with_capacity(n_expert); for i in 0..n_expert { let feed_forward_w1 = ct.tensor(reader, &format!("{prefix}.ffn_gate.{i}.weight"), device)?; let feed_forward_w2 = ct.tensor(reader, &format!("{prefix}.ffn_down.{i}.weight"), device)?; let feed_forward_w3 = ct.tensor(reader, &format!("{prefix}.ffn_up.{i}.weight"), device)?; experts.push(Mlp { feed_forward_w1: QMatMul::from_qtensor(feed_forward_w1)?, feed_forward_w2: QMatMul::from_qtensor(feed_forward_w2)?, feed_forward_w3: QMatMul::from_qtensor(feed_forward_w3)?, }) } MlpOrMoe::MoE { n_expert_used, feed_forward_gate_inp: QMatMul::from_qtensor(feed_forward_gate_inp)?, experts, } }; let attention_norm = ct.tensor(reader, &format!("{prefix}.attn_norm.weight"), device)?; let ffn_norm = ct.tensor(reader, &format!("{prefix}.ffn_norm.weight"), device)?; let span_attn = tracing::span!(tracing::Level::TRACE, "attn"); let span_rot = tracing::span!(tracing::Level::TRACE, "attn-rot"); let span_mlp = tracing::span!(tracing::Level::TRACE, "attn-mlp"); layers.push(LayerWeights { attention_wq: QMatMul::from_qtensor(attention_wq)?, attention_wk: QMatMul::from_qtensor(attention_wk)?, attention_wv: QMatMul::from_qtensor(attention_wv)?, attention_wo: QMatMul::from_qtensor(attention_wo)?, attention_norm: RmsNorm::new(attention_norm, rms_norm_eps)?, mlp_or_moe, ffn_norm: RmsNorm::new(ffn_norm, rms_norm_eps)?, n_head: head_count, n_kv_head: head_count_kv, head_dim: embedding_length / head_count, cos: cos.clone(), sin: sin.clone(), neg_inf: neg_inf.clone(), kv_cache: None, span_attn, span_rot, span_mlp, }) } let span = tracing::span!(tracing::Level::TRACE, "model"); let span_output = tracing::span!(tracing::Level::TRACE, "output"); Ok(Self { tok_embeddings: Embedding::new(tok_embeddings, embedding_length), layers, norm, output: QMatMul::from_qtensor(output)?, masks: HashMap::new(), span, span_output, }) } fn mask(&mut self, t: usize, device: &Device) -> Result<Tensor> { if let Some(mask) = self.masks.get(&t) { Ok(mask.clone()) } else { let mask: Vec<_> = (0..t) .flat_map(|i| (0..t).map(move |j| u8::from(j > i))) .collect(); let mask = Tensor::from_slice(&mask, (t, t), device)?; self.masks.insert(t, mask.clone()); Ok(mask) } } pub fn forward(&mut self, x: &Tensor, index_pos: usize) -> Result<Tensor> { let (_b_sz, seq_len) = x.dims2()?; let mask = self.mask(seq_len, x.device())?; let _enter = self.span.enter(); let mut layer_in = self.tok_embeddings.forward(x)?; for layer in self.layers.iter_mut() { let x = layer_in; let residual = &x; let x = layer.attention_norm.forward(&x)?; let attn = layer.forward_attn(&x, &mask, index_pos)?; let x = (attn + residual)?; // MLP let _enter = layer.span_mlp.enter(); let residual = &x; let x = layer.ffn_norm.forward(&x)?; let x = layer.mlp_or_moe.forward(&x)?; let x = (x + residual)?; layer_in = x } let x = self.norm.forward(&layer_in)?; let x = x.i((.., seq_len - 1, ..))?.contiguous()?; let _enter = self.span_output.enter(); self.output.forward(&x) } }
candle/candle-transformers/src/models/quantized_llama.rs/0
{ "file_path": "candle/candle-transformers/src/models/quantized_llama.rs", "repo_id": "candle", "token_count": 11792 }
39
use candle::{DType, IndexOp, Result, Tensor}; use candle_nn::{layer_norm, LayerNorm, Module, VarBuilder}; #[derive(Debug)] struct PatchEmbed { proj: candle_nn::Conv2d, span: tracing::Span, } impl PatchEmbed { fn new( in_chans: usize, embed_dim: usize, k_size: usize, stride: usize, padding: usize, vb: VarBuilder, ) -> Result<Self> { let cfg = candle_nn::Conv2dConfig { stride, padding, ..Default::default() }; let proj = candle_nn::conv2d(in_chans, embed_dim, k_size, cfg, vb.pp("proj"))?; let span = tracing::span!(tracing::Level::TRACE, "patch-embed"); Ok(Self { proj, span }) } } impl Module for PatchEmbed { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); xs.apply(&self.proj)?.permute((0, 2, 3, 1)) } } // A custom op to make add_decomposed_rel_pos faster. Most of the time is spent on the final // addition in the case where b = 12, q_h = q_w = 4096, k_h = k_w = 4096 // (attn.reshape((b, q_h, q_w, k_h, k_w))? // + rel_h.unsqueeze(4)?.broadcast_add(&rel_w.unsqueeze(3)?)?)? // .reshape((b, q_h * q_w, k_h * k_w)) // Ideally we would perform this operation in place but this is not supported in candle at the // moment. We should also investigate using f16 rather than f32. struct Add3(usize, usize, usize, usize, usize); impl candle::CustomOp3 for Add3 { fn name(&self) -> &'static str { "add3" } fn cpu_fwd( &self, s1: &candle::CpuStorage, l1: &candle::Layout, s2: &candle::CpuStorage, l2: &candle::Layout, s3: &candle::CpuStorage, l3: &candle::Layout, ) -> Result<(candle::CpuStorage, candle::Shape)> { use rayon::prelude::*; let Add3(b, q_h, q_w, k_h, k_w) = *self; let s1 = s1.as_slice::<f32>()?; let s1 = match l1.contiguous_offsets() { None => candle::bail!("input1 has to be contiguous"), Some((o1, o2)) => &s1[o1..o2], }; let s2 = s2.as_slice::<f32>()?; let s2 = match l2.contiguous_offsets() { None => candle::bail!("input2 has to be contiguous"), Some((o1, o2)) => &s2[o1..o2], }; let s3 = s3.as_slice::<f32>()?; let s3 = match l3.contiguous_offsets() { None => candle::bail!("input3 has to be contiguous"), Some((o1, o2)) => &s3[o1..o2], }; let mut dst = vec![0f32; b * q_h * q_w * k_h * k_w]; dst.par_chunks_exact_mut(k_h * k_w) .enumerate() .for_each(|(b_idx, dst)| { let s1_idx = b_idx * k_h * k_w; let s2_idx = b_idx * k_h; let s3_idx = b_idx * k_w; for h_idx in 0..k_h { let s1_idx = s1_idx + h_idx * k_w; let s2_idx = s2_idx + h_idx; let dst_idx = h_idx * k_w; for w_idx in 0..k_w { let s1_idx = s1_idx + w_idx; let s3_idx = s3_idx + w_idx; let dst_idx = dst_idx + w_idx; dst[dst_idx] = s1[s1_idx] + s2[s2_idx] + s3[s3_idx] } } }); let dst = candle::WithDType::to_cpu_storage_owned(dst); Ok((dst, (b, q_h * q_w, k_h * k_w).into())) } } #[derive(Debug)] struct Attention { qkv: super::Linear, proj: super::Linear, num_heads: usize, scale: f64, rel_pos_hw: Option<(Tensor, Tensor)>, span: tracing::Span, span_matmul: tracing::Span, span_rel_pos: tracing::Span, span_softmax: tracing::Span, } impl Attention { fn new( dim: usize, num_heads: usize, qkv_bias: bool, use_rel_pos: bool, input_size: (usize, usize), vb: VarBuilder, ) -> Result<Self> { let span = tracing::span!(tracing::Level::TRACE, "attention"); let span_matmul = tracing::span!(tracing::Level::TRACE, "attn-matmul"); let span_rel_pos = tracing::span!(tracing::Level::TRACE, "attn-rel-pos"); let span_softmax = tracing::span!(tracing::Level::TRACE, "attn-sm"); let qkv = super::linear(vb.pp("qkv"), dim, dim * 3, qkv_bias)?; let proj = super::linear(vb.pp("proj"), dim, dim, true)?; let head_dim = dim / num_heads; let scale = 1. / (head_dim as f64).sqrt(); let rel_pos_hw = if use_rel_pos { let h = vb.get((2 * input_size.0 - 1, head_dim), "rel_pos_h")?; let w = vb.get((2 * input_size.1 - 1, head_dim), "rel_pos_w")?; Some((h, w)) } else { None }; Ok(Self { qkv, proj, num_heads, scale, rel_pos_hw, span, span_matmul, span_rel_pos, span_softmax, }) } fn add_decomposed_rel_pos( &self, attn: Tensor, q: &Tensor, (q_h, q_w): (usize, usize), (k_h, k_w): (usize, usize), ) -> Result<Tensor> { match &self.rel_pos_hw { Some((rel_pos_h, rel_pos_w)) => { let r_h = get_rel_pos(q_h, k_h, rel_pos_h)?; let r_w = get_rel_pos(q_w, k_w, rel_pos_w)?; let (b, _, dim) = q.dims3()?; let r_q = q.reshape((b, q_h, q_w, dim))?; // rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh) let rel_h = r_q.matmul(&r_h.broadcast_left(b)?.t()?.contiguous()?)?; // rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw) let rel_w = r_q .transpose(1, 2)? // -> bwhc .contiguous()? .matmul(&r_w.broadcast_left(b)?.t()?.contiguous()?)? // bwhc,bwck -> bwhk .transpose(1, 2)? .contiguous()?; if attn.device().is_cpu() { let op = Add3(b, q_h, q_w, k_h, k_w); attn.apply_op3_no_bwd(&rel_h, &rel_w, &op) } else { (attn.reshape((b, q_h, q_w, k_h, k_w))? + rel_h.unsqueeze(4)?.broadcast_add(&rel_w.unsqueeze(3)?)?)? .reshape((b, q_h * q_w, k_h * k_w)) } } None => Ok(attn), } } } fn get_rel_pos(q_size: usize, k_size: usize, rel_pos: &Tensor) -> Result<Tensor> { let max_rel_dist = 2 * usize::max(q_size, k_size) - 1; let dev = rel_pos.device(); let rel_pos_resized = if rel_pos.dim(0)? != max_rel_dist { todo!("interpolation") } else { rel_pos }; let q_coords = Tensor::arange(0u32, q_size as u32, dev)? .reshape((q_size, 1))? .to_dtype(DType::F32)?; let k_coords = Tensor::arange(0u32, k_size as u32, dev)? .reshape((1, k_size))? .to_dtype(DType::F32)?; let q_coords = (q_coords * f64::max(1f64, k_size as f64 / q_size as f64))?; let k_coords = (k_coords * f64::max(1f64, q_size as f64 / k_size as f64))?; let relative_coords = (q_coords.broadcast_sub(&k_coords)? + (k_size as f64 - 1.) * f64::max(1f64, q_size as f64 / k_size as f64))?; let (d1, d2) = relative_coords.dims2()?; let relative_coords = relative_coords.to_dtype(DType::U32)?; rel_pos_resized .index_select(&relative_coords.reshape(d1 * d2)?, 0)? .reshape((d1, d2, ())) } impl Module for Attention { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let (b, h, w, c) = xs.dims4()?; let qkv = self .qkv .forward(&xs.flatten_to(1)?)? .reshape((b, h * w, 3, self.num_heads, c / self.num_heads))? .permute((2, 0, 3, 1, 4))? .reshape((3, b * self.num_heads, h * w, c / self.num_heads))?; let q = qkv.i(0)?; let k = qkv.i(1)?; let v = qkv.i(2)?; let attn = { let _enter = self.span_matmul.enter(); (&q * self.scale)?.matmul(&k.t()?)? }; let attn = { let _enter = self.span_rel_pos.enter(); self.add_decomposed_rel_pos(attn, &q, (h, w), (h, w))? }; let attn = { let _enter = self.span_softmax.enter(); candle_nn::ops::softmax_last_dim(&attn)? }; let attn = { let _enter = self.span_matmul.enter(); attn.matmul(&v)? }; let attn = attn .reshape((b, self.num_heads, h, w, c / self.num_heads))? .permute((0, 2, 3, 1, 4))? .reshape((b, h * w, c))?; self.proj.forward(&attn)?.reshape((b, h, w, c)) } } #[derive(Debug)] struct Block { norm1: LayerNorm, attn: Attention, norm2: LayerNorm, mlp: super::MlpBlock, window_size: usize, span: tracing::Span, } impl Block { fn new( dim: usize, num_heads: usize, qkv_bias: bool, use_rel_pos: bool, window_size: usize, input_size: (usize, usize), vb: VarBuilder, ) -> Result<Self> { let norm1 = layer_norm(dim, 1e-6, vb.pp("norm1"))?; let norm2 = layer_norm(dim, 1e-6, vb.pp("norm2"))?; let input_size_attn = if window_size == 0 { input_size } else { (window_size, window_size) }; let attn = Attention::new( dim, num_heads, qkv_bias, use_rel_pos, input_size_attn, vb.pp("attn"), )?; let mlp = super::MlpBlock::new(dim, dim * 4, candle_nn::Activation::Gelu, vb.pp("mlp"))?; let span = tracing::span!(tracing::Level::TRACE, "ie-block"); Ok(Self { norm1, attn, norm2, mlp, window_size, span, }) } } fn window_partition(xs: Tensor, window_size: usize) -> Result<(Tensor, (usize, usize))> { let (b, h, w, c) = xs.dims4()?; let pad_h = (window_size - h % window_size) % window_size; let pad_w = (window_size - w % window_size) % window_size; let xs = if pad_h > 0 { xs.pad_with_zeros(1, 0, pad_h)? } else { xs }; let xs = if pad_w > 0 { xs.pad_with_zeros(2, 0, pad_w)? } else { xs }; let (h_p, w_p) = (h + pad_h, w + pad_w); let windows = xs .reshape(( b, h_p / window_size, window_size, w_p / window_size, window_size, c, ))? .transpose(2, 3)? .contiguous()? .flatten_to(2)?; Ok((windows, (h_p, w_p))) } fn window_unpartition( windows: Tensor, window_size: usize, (h_p, w_p): (usize, usize), (h, w): (usize, usize), ) -> Result<Tensor> { let b = windows.dim(0)? / (h_p * w_p / window_size / window_size); let xs = windows .reshape(( b, h_p / window_size, w_p / window_size, window_size, window_size, windows.elem_count() / b / h_p / w_p, ))? .transpose(2, 3)? .contiguous()? .reshape((b, h_p, w_p, ()))?; let xs = if h_p > h { xs.narrow(1, 0, h)? } else { xs }; let xs = if w_p > w { xs.narrow(2, 0, w)? } else { xs }; Ok(xs) } impl Module for Block { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let shortcut = xs; let xs = self.norm1.forward(xs)?; let hw = (xs.dim(1)?, xs.dim(2)?); let (xs, pad_hw) = if self.window_size > 0 { window_partition(xs, self.window_size)? } else { (xs, (0, 0)) }; let xs = self.attn.forward(&xs)?; let xs = if self.window_size > 0 { window_unpartition(xs, self.window_size, pad_hw, hw)? } else { xs }; let xs = (xs + shortcut)?; &xs + xs.apply(&self.norm2)?.apply(&self.mlp)? } } #[derive(Debug)] pub struct ImageEncoderViT { patch_embed: PatchEmbed, blocks: Vec<Block>, neck_conv1: candle_nn::Conv2d, neck_ln1: super::LayerNorm2d, neck_conv2: candle_nn::Conv2d, neck_ln2: super::LayerNorm2d, pos_embed: Option<Tensor>, span: tracing::Span, } impl ImageEncoderViT { #[allow(clippy::too_many_arguments)] pub fn new( img_size: usize, patch_size: usize, in_chans: usize, embed_dim: usize, depth: usize, num_heads: usize, out_chans: usize, qkv_bias: bool, use_rel_pos: bool, use_abs_pos: bool, window_size: usize, global_attn_indexes: &[usize], vb: VarBuilder, ) -> Result<Self> { let patch_embed = PatchEmbed::new( in_chans, embed_dim, patch_size, patch_size, 0, vb.pp("patch_embed"), )?; let mut blocks = Vec::with_capacity(depth); let vb_b = vb.pp("blocks"); for i in 0..depth { let window_size = if global_attn_indexes.contains(&i) { 0 } else { window_size }; let block = Block::new( embed_dim, num_heads, qkv_bias, use_rel_pos, window_size, (img_size / patch_size, img_size / patch_size), vb_b.pp(i), )?; blocks.push(block) } let neck_conv1 = candle_nn::conv2d_no_bias( embed_dim, out_chans, 1, Default::default(), vb.pp("neck.0"), )?; let neck_ln1 = super::LayerNorm2d::new(out_chans, 1e-6, vb.pp("neck.1"))?; let cfg = candle_nn::Conv2dConfig { padding: 1, ..Default::default() }; let neck_conv2 = candle_nn::conv2d_no_bias(out_chans, out_chans, 3, cfg, vb.pp("neck.2"))?; let neck_ln2 = super::LayerNorm2d::new(out_chans, 1e-6, vb.pp("neck.3"))?; let pos_embed = if use_abs_pos { let p = vb.get( (1, img_size / patch_size, img_size / patch_size, embed_dim), "pos_embed", )?; Some(p) } else { None }; let span = tracing::span!(tracing::Level::TRACE, "image-encoder-vit"); Ok(Self { patch_embed, blocks, neck_conv1, neck_ln1, neck_conv2, neck_ln2, pos_embed, span, }) } } impl Module for ImageEncoderViT { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let _enter = self.span.enter(); let xs = self.patch_embed.forward(xs)?; let mut xs = match &self.pos_embed { Some(pos_embed) => (xs + pos_embed)?, None => xs, }; for block in self.blocks.iter() { xs = block.forward(&xs)? } xs.permute((0, 3, 1, 2))? .apply(&self.neck_conv1)? .apply(&self.neck_ln1)? .apply(&self.neck_conv2)? .apply(&self.neck_ln2) } }
candle/candle-transformers/src/models/segment_anything/image_encoder.rs/0
{ "file_path": "candle/candle-transformers/src/models/segment_anything/image_encoder.rs", "repo_id": "candle", "token_count": 8848 }
40
//! 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 }
41
use candle::{DType, Module, Result, Tensor, D}; use candle_nn::VarBuilder; // https://github.com/huggingface/diffusers/blob/19edca82f1ff194c07317369a92b470dbae97f34/src/diffusers/pipelines/wuerstchen/modeling_wuerstchen_common.py#L22 #[derive(Debug)] pub struct WLayerNorm { eps: f64, } impl WLayerNorm { pub fn new(_size: usize) -> Result<Self> { Ok(Self { eps: 1e-6 }) } } impl Module for WLayerNorm { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let xs = xs.permute((0, 2, 3, 1))?; let x_dtype = xs.dtype(); let internal_dtype = match x_dtype { DType::F16 | DType::BF16 => DType::F32, d => d, }; let hidden_size = xs.dim(D::Minus1)?; let xs = xs.to_dtype(internal_dtype)?; let mean_x = (xs.sum_keepdim(D::Minus1)? / hidden_size as f64)?; let xs = xs.broadcast_sub(&mean_x)?; let norm_x = (xs.sqr()?.sum_keepdim(D::Minus1)? / hidden_size as f64)?; xs.broadcast_div(&(norm_x + self.eps)?.sqrt()?)? .to_dtype(x_dtype)? .permute((0, 3, 1, 2)) } } #[derive(Debug)] pub struct LayerNormNoWeights { eps: f64, } impl LayerNormNoWeights { pub fn new(_size: usize) -> Result<Self> { Ok(Self { eps: 1e-6 }) } } impl Module for LayerNormNoWeights { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let x_dtype = xs.dtype(); let internal_dtype = match x_dtype { DType::F16 | DType::BF16 => DType::F32, d => d, }; let hidden_size = xs.dim(D::Minus1)?; let xs = xs.to_dtype(internal_dtype)?; let mean_x = (xs.sum_keepdim(D::Minus1)? / hidden_size as f64)?; let xs = xs.broadcast_sub(&mean_x)?; let norm_x = (xs.sqr()?.sum_keepdim(D::Minus1)? / hidden_size as f64)?; xs.broadcast_div(&(norm_x + self.eps)?.sqrt()?)? .to_dtype(x_dtype) } } #[derive(Debug)] pub struct TimestepBlock { mapper: candle_nn::Linear, } impl TimestepBlock { pub fn new(c: usize, c_timestep: usize, vb: VarBuilder) -> Result<Self> { let mapper = candle_nn::linear(c_timestep, c * 2, vb.pp("mapper"))?; Ok(Self { mapper }) } pub fn forward(&self, xs: &Tensor, t: &Tensor) -> Result<Tensor> { let ab = self .mapper .forward(t)? .unsqueeze(2)? .unsqueeze(3)? .chunk(2, 1)?; xs.broadcast_mul(&(&ab[0] + 1.)?)?.broadcast_add(&ab[1]) } } #[derive(Debug)] pub struct GlobalResponseNorm { gamma: Tensor, beta: Tensor, } impl GlobalResponseNorm { pub fn new(dim: usize, vb: VarBuilder) -> Result<Self> { let gamma = vb.get((1, 1, 1, dim), "gamma")?; let beta = vb.get((1, 1, 1, dim), "beta")?; Ok(Self { gamma, beta }) } } impl Module for GlobalResponseNorm { fn forward(&self, xs: &Tensor) -> Result<Tensor> { let agg_norm = xs.sqr()?.sum_keepdim((1, 2))?.sqrt()?; let stand_div_norm = agg_norm.broadcast_div(&(agg_norm.mean_keepdim(D::Minus1)? + 1e-6)?)?; xs.broadcast_mul(&stand_div_norm)? .broadcast_mul(&self.gamma)? .broadcast_add(&self.beta)? + xs } } #[derive(Debug)] pub struct ResBlock { depthwise: candle_nn::Conv2d, norm: WLayerNorm, channelwise_lin1: candle_nn::Linear, channelwise_grn: GlobalResponseNorm, channelwise_lin2: candle_nn::Linear, } impl ResBlock { pub fn new(c: usize, c_skip: usize, ksize: usize, vb: VarBuilder) -> Result<Self> { let cfg = candle_nn::Conv2dConfig { padding: ksize / 2, groups: c, ..Default::default() }; let depthwise = candle_nn::conv2d(c + c_skip, c, ksize, cfg, vb.pp("depthwise"))?; let norm = WLayerNorm::new(c)?; let channelwise_lin1 = candle_nn::linear(c, c * 4, vb.pp("channelwise.0"))?; let channelwise_grn = GlobalResponseNorm::new(c * 4, vb.pp("channelwise.2"))?; let channelwise_lin2 = candle_nn::linear(c * 4, c, vb.pp("channelwise.4"))?; Ok(Self { depthwise, norm, channelwise_lin1, channelwise_grn, channelwise_lin2, }) } pub fn forward(&self, xs: &Tensor, x_skip: Option<&Tensor>) -> Result<Tensor> { let x_res = xs; let xs = match x_skip { None => xs.clone(), Some(x_skip) => Tensor::cat(&[xs, x_skip], 1)?, }; let xs = xs .apply(&self.depthwise)? .apply(&self.norm)? .permute((0, 2, 3, 1))?; let xs = xs .apply(&self.channelwise_lin1)? .gelu_erf()? .apply(&self.channelwise_grn)? .apply(&self.channelwise_lin2)? .permute((0, 3, 1, 2))?; xs + x_res } } use super::attention_processor::Attention; #[derive(Debug)] pub struct AttnBlock { self_attn: bool, norm: WLayerNorm, attention: Attention, kv_mapper_lin: candle_nn::Linear, } impl AttnBlock { pub fn new( c: usize, c_cond: usize, nhead: usize, self_attn: bool, use_flash_attn: bool, vb: VarBuilder, ) -> Result<Self> { let norm = WLayerNorm::new(c)?; let attention = Attention::new(c, nhead, c / nhead, use_flash_attn, vb.pp("attention"))?; let kv_mapper_lin = candle_nn::linear(c_cond, c, vb.pp("kv_mapper.1"))?; Ok(Self { self_attn, norm, attention, kv_mapper_lin, }) } pub fn forward(&self, xs: &Tensor, kv: &Tensor) -> Result<Tensor> { let kv = candle_nn::ops::silu(kv)?.apply(&self.kv_mapper_lin)?; let norm_xs = self.norm.forward(xs)?; let kv = if self.self_attn { let (b_size, channel, _, _) = xs.dims4()?; let norm_xs = norm_xs.reshape((b_size, channel, ()))?.transpose(1, 2)?; Tensor::cat(&[&norm_xs, &kv], 1)?.contiguous()? } else { kv }; xs + self.attention.forward(&norm_xs, &kv) } }
candle/candle-transformers/src/models/wuerstchen/common.rs/0
{ "file_path": "candle/candle-transformers/src/models/wuerstchen/common.rs", "repo_id": "candle", "token_count": 3219 }
42
//load Candle Bert Module wasm module import init, { Model } from "./build/m.js"; async function fetchArrayBuffer(url) { const cacheName = "bert-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 Bert { static instance = {}; static async getInstance(weightsURL, tokenizerURL, configURL, modelID) { if (!this.instance[modelID]) { await init(); self.postMessage({ status: "loading", message: "Loading Model" }); const [weightsArrayU8, tokenizerArrayU8, mel_filtersArrayU8] = await Promise.all([ fetchArrayBuffer(weightsURL), fetchArrayBuffer(tokenizerURL), fetchArrayBuffer(configURL), ]); this.instance[modelID] = new Model( weightsArrayU8, tokenizerArrayU8, mel_filtersArrayU8 ); } else { self.postMessage({ status: "ready", message: "Model Already Loaded" }); } return this.instance[modelID]; } } self.addEventListener("message", async (event) => { const { weightsURL, tokenizerURL, configURL, modelID, sentences, normalize = true, } = event.data; try { self.postMessage({ status: "ready", message: "Starting Bert Model" }); const model = await Bert.getInstance( weightsURL, tokenizerURL, configURL, modelID ); self.postMessage({ status: "embedding", message: "Calculating Embeddings", }); const output = model.get_embeddings({ sentences: sentences, normalize_embeddings: normalize, }); self.postMessage({ status: "complete", message: "complete", output: output.data, }); } catch (e) { self.postMessage({ error: e }); } });
candle/candle-wasm-examples/bert/bertWorker.js/0
{ "file_path": "candle/candle-wasm-examples/bert/bertWorker.js", "repo_id": "candle", "token_count": 779 }
43
cargo build --target wasm32-unknown-unknown --release wasm-bindgen ../../target/wasm32-unknown-unknown/release/m.wasm --out-dir build --target web
candle/candle-wasm-examples/llama2-c/build-lib.sh/0
{ "file_path": "candle/candle-wasm-examples/llama2-c/build-lib.sh", "repo_id": "candle", "token_count": 48 }
44
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 }
45
use crate::languages::LANGUAGES; use anyhow::Error as E; use candle::{safetensors::Load, DType, Device, IndexOp, Tensor, D}; use candle_nn::{ops::softmax, VarBuilder}; pub use candle_transformers::models::whisper::{self as m, Config}; use rand::{distributions::Distribution, rngs::StdRng, SeedableRng}; use serde::{Deserialize, Serialize}; use tokenizers::Tokenizer; use wasm_bindgen::prelude::*; use yew_agent::{HandlerId, Public, WorkerLink}; #[wasm_bindgen] extern "C" { // Use `js_namespace` here to bind `console.log(..)` instead of just // `log(..)` #[wasm_bindgen(js_namespace = console)] pub fn log(s: &str); } #[macro_export] macro_rules! console_log { // Note that this is using the `log` function imported above during // `bare_bones` ($($t:tt)*) => ($crate::worker::log(&format_args!($($t)*).to_string())) } pub const DTYPE: DType = DType::F32; pub enum Model { Normal(m::model::Whisper), Quantized(m::quantized_model::Whisper), } // Maybe we should use some traits rather than doing the dispatch for all these. impl Model { pub fn config(&self) -> &Config { match self { Self::Normal(m) => &m.config, Self::Quantized(m) => &m.config, } } pub fn encoder_forward(&mut self, x: &Tensor, flush: bool) -> candle::Result<Tensor> { match self { Self::Normal(m) => m.encoder.forward(x, flush), Self::Quantized(m) => m.encoder.forward(x, flush), } } pub fn decoder_forward( &mut self, x: &Tensor, xa: &Tensor, flush: bool, ) -> candle::Result<Tensor> { match self { Self::Normal(m) => m.decoder.forward(x, xa, flush), Self::Quantized(m) => m.decoder.forward(x, xa, flush), } } pub fn decoder_final_linear(&self, x: &Tensor) -> candle::Result<Tensor> { match self { Self::Normal(m) => m.decoder.final_linear(x), Self::Quantized(m) => m.decoder.final_linear(x), } } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DecodingResult { pub tokens: Vec<u32>, pub text: String, pub avg_logprob: f64, pub no_speech_prob: f64, temperature: f64, compression_ratio: f64, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Segment { pub start: f64, pub duration: f64, pub dr: DecodingResult, } pub struct Decoder { model: Model, rng: rand::rngs::StdRng, task: Option<Task>, language: Option<String>, is_multilingual: bool, mel_filters: Vec<f32>, timestamps: bool, tokenizer: Tokenizer, suppress_tokens: Tensor, sot_token: u32, transcribe_token: u32, translate_token: u32, eot_token: u32, no_speech_token: u32, no_timestamps_token: u32, } impl Decoder { #[allow(clippy::too_many_arguments)] fn new( model: Model, tokenizer: Tokenizer, mel_filters: Vec<f32>, device: &Device, task: Option<Task>, language: Option<String>, is_multilingual: bool, timestamps: bool, ) -> anyhow::Result<Self> { let suppress_tokens: Vec<f32> = (0..model.config().vocab_size as u32) .map(|i| { if model.config().suppress_tokens.contains(&i) { f32::NEG_INFINITY } else { 0f32 } }) .collect(); let no_timestamps_token = token_id(&tokenizer, m::NO_TIMESTAMPS_TOKEN)?; let suppress_tokens = Tensor::new(suppress_tokens.as_slice(), device)?; let sot_token = token_id(&tokenizer, m::SOT_TOKEN)?; let transcribe_token = token_id(&tokenizer, m::TRANSCRIBE_TOKEN)?; let translate_token = token_id(&tokenizer, m::TRANSLATE_TOKEN)?; let eot_token = token_id(&tokenizer, m::EOT_TOKEN)?; let no_speech_token = m::NO_SPEECH_TOKENS .iter() .find_map(|token| token_id(&tokenizer, token).ok()); let no_speech_token = match no_speech_token { None => anyhow::bail!("unable to find any non-speech token"), Some(n) => n, }; let seed = 299792458; Ok(Self { model, rng: StdRng::seed_from_u64(seed), tokenizer, mel_filters, task, timestamps, language, is_multilingual, suppress_tokens, sot_token, transcribe_token, translate_token, eot_token, no_speech_token, no_timestamps_token, }) } fn decode(&mut self, mel: &Tensor, t: f64) -> anyhow::Result<DecodingResult> { let model = &mut self.model; let language_token = match (self.is_multilingual, &self.language) { (true, None) => Some(detect_language(model, &self.tokenizer, mel)?), (false, None) => None, (true, Some(language)) => { match token_id(&self.tokenizer, &format!("<|{:?}|>", self.language)) { Ok(token_id) => Some(token_id), Err(_) => anyhow::bail!("language {language} is not supported"), } } (false, Some(_)) => { anyhow::bail!("a language cannot be set for non-multilingual models") } }; let audio_features = model.encoder_forward(mel, true)?; println!("audio features: {:?}", audio_features.dims()); let sample_len = model.config().max_target_positions / 2; let mut sum_logprob = 0f64; let mut no_speech_prob = f64::NAN; let mut tokens = vec![self.sot_token]; if let Some(language_token) = language_token { tokens.push(language_token); } match self.task { None | Some(Task::Transcribe) => tokens.push(self.transcribe_token), Some(Task::Translate) => tokens.push(self.translate_token), } if !self.timestamps { tokens.push(self.no_timestamps_token); } for i in 0..sample_len { let tokens_t = Tensor::new(tokens.as_slice(), mel.device())?; // The model expects a batch dim but this inference loop does not handle // it so we add it at this point. let tokens_t = tokens_t.unsqueeze(0)?; let ys = model.decoder_forward(&tokens_t, &audio_features, i == 0)?; // Extract the no speech probability on the first iteration by looking at the first // token logits and the probability for the according token. if i == 0 { let logits = model.decoder_final_linear(&ys.i(..1)?)?.i(0)?.i(0)?; no_speech_prob = softmax(&logits, 0)? .i(self.no_speech_token as usize)? .to_scalar::<f32>()? as f64; } let (_, seq_len, _) = ys.dims3()?; let logits = model .decoder_final_linear(&ys.i((..1, seq_len - 1..))?)? .i(0)? .i(0)?; // TODO: Besides suppress tokens, we should apply the heuristics from // ApplyTimestampRules, i.e.: // - Timestamps come in pairs, except before EOT. // - Timestamps should be non-decreasing. // - If the sum of the probabilities of timestamps is higher than any other tokens, // only consider timestamps when sampling. // https://github.com/openai/whisper/blob/e8622f9afc4eba139bf796c210f5c01081000472/whisper/decoding.py#L439 let logits = logits.broadcast_add(&self.suppress_tokens)?; let next_token = if t > 0f64 { let prs = softmax(&(&logits / t)?, 0)?; let logits_v: Vec<f32> = prs.to_vec1()?; let distr = rand::distributions::WeightedIndex::new(&logits_v)?; distr.sample(&mut self.rng) as u32 } else { let logits_v: Vec<f32> = logits.to_vec1()?; logits_v .iter() .enumerate() .max_by(|(_, u), (_, v)| u.total_cmp(v)) .map(|(i, _)| i as u32) .unwrap() }; tokens.push(next_token); let prob = softmax(&logits, candle::D::Minus1)? .i(next_token as usize)? .to_scalar::<f32>()? as f64; if next_token == self.eot_token || tokens.len() > model.config().max_target_positions { break; } sum_logprob += prob.ln(); } let text = self.tokenizer.decode(&tokens, true).map_err(E::msg)?; let avg_logprob = sum_logprob / tokens.len() as f64; Ok(DecodingResult { tokens, text, avg_logprob, no_speech_prob, temperature: t, compression_ratio: f64::NAN, }) } fn decode_with_fallback(&mut self, segment: &Tensor) -> anyhow::Result<DecodingResult> { for (i, &t) in m::TEMPERATURES.iter().enumerate() { let dr: Result<DecodingResult, _> = self.decode(segment, t); if i == m::TEMPERATURES.len() - 1 { return dr; } // On errors, we try again with a different temperature. match dr { Ok(dr) => { let needs_fallback = dr.compression_ratio > m::COMPRESSION_RATIO_THRESHOLD || dr.avg_logprob < m::LOGPROB_THRESHOLD; if !needs_fallback || dr.no_speech_prob > m::NO_SPEECH_THRESHOLD { return Ok(dr); } } Err(err) => { console_log!("Error running at {t}: {err}") } } } unreachable!() } fn run(&mut self, mel: &Tensor) -> anyhow::Result<Vec<Segment>> { let (_, _, content_frames) = mel.dims3()?; let mut seek = 0; let mut segments = vec![]; while seek < content_frames { let time_offset = (seek * m::HOP_LENGTH) as f64 / m::SAMPLE_RATE as f64; let segment_size = usize::min(content_frames - seek, m::N_FRAMES); let mel_segment = mel.narrow(2, seek, segment_size)?; let segment_duration = (segment_size * m::HOP_LENGTH) as f64 / m::SAMPLE_RATE as f64; let dr = self.decode_with_fallback(&mel_segment)?; seek += segment_size; if dr.no_speech_prob > m::NO_SPEECH_THRESHOLD && dr.avg_logprob < m::LOGPROB_THRESHOLD { console_log!("no speech detected, skipping {seek} {dr:?}"); continue; } let segment = Segment { start: time_offset, duration: segment_duration, dr, }; console_log!("{seek}: {segment:?}"); segments.push(segment) } Ok(segments) } pub fn load(md: ModelData) -> anyhow::Result<Self> { let device = Device::Cpu; let tokenizer = Tokenizer::from_bytes(&md.tokenizer).map_err(E::msg)?; let mel_filters = safetensors::tensor::SafeTensors::deserialize(&md.mel_filters)?; let mel_filters = mel_filters.tensor("mel_80")?.load(&device)?; console_log!("loaded mel filters {:?}", mel_filters.shape()); let mel_filters = mel_filters.flatten_all()?.to_vec1::<f32>()?; let config: Config = serde_json::from_slice(&md.config)?; let model = if md.quantized { let vb = candle_transformers::quantized_var_builder::VarBuilder::from_gguf_buffer( &md.weights, &device, )?; Model::Quantized(m::quantized_model::Whisper::load(&vb, config)?) } else { let vb = VarBuilder::from_buffered_safetensors(md.weights, m::DTYPE, &device)?; Model::Normal(m::model::Whisper::load(&vb, config)?) }; console_log!("done loading model"); let task = match md.task.as_deref() { Some("translate") => Some(Task::Translate), _ => Some(Task::Transcribe), }; let decoder = Self::new( model, tokenizer, mel_filters, &device, task, md.language, md.is_multilingual, md.timestamps, )?; Ok(decoder) } pub fn convert_and_run(&mut self, wav_input: &[u8]) -> anyhow::Result<Vec<Segment>> { let device = Device::Cpu; let mut wav_input = std::io::Cursor::new(wav_input); let (header, data) = wav::read(&mut wav_input)?; console_log!("loaded wav data: {header:?}"); if header.sampling_rate != m::SAMPLE_RATE as u32 { anyhow::bail!("wav file must have a {} sampling rate", m::SAMPLE_RATE); } let data = data.as_sixteen().expect("expected 16 bit wav file"); let pcm_data: Vec<_> = data[..data.len() / header.channel_count as usize] .iter() .map(|v| *v as f32 / 32768.) .collect(); console_log!("pcm data loaded {}", pcm_data.len()); let mel = crate::audio::pcm_to_mel(self.model.config(), &pcm_data, &self.mel_filters)?; let mel_len = mel.len(); let n_mels = self.model.config().num_mel_bins; let mel = Tensor::from_vec(mel, (1, n_mels, mel_len / n_mels), &device)?; console_log!("loaded mel: {:?}", mel.dims()); let segments = self.run(&mel)?; Ok(segments) } } /// Returns the token id for the selected language. pub fn detect_language(model: &mut Model, tokenizer: &Tokenizer, mel: &Tensor) -> Result<u32, E> { console_log!("detecting language"); let (_bsize, _, seq_len) = mel.dims3()?; let mel = mel.narrow( 2, 0, usize::min(seq_len, model.config().max_source_positions), )?; let device = mel.device(); let language_token_ids = LANGUAGES .iter() .map(|(t, _)| token_id(tokenizer, &format!("<|{t}|>"))) .map(|e| e.map_err(E::msg)) .collect::<Result<Vec<_>, E>>()?; let sot_token = token_id(tokenizer, m::SOT_TOKEN)?; let audio_features = model.encoder_forward(&mel, true)?; let tokens = Tensor::new(&[[sot_token]], device)?; let language_token_ids = Tensor::new(language_token_ids.as_slice(), device)?; let ys = model.decoder_forward(&tokens, &audio_features, true)?; let logits = model.decoder_final_linear(&ys.i(..1)?)?.i(0)?.i(0)?; let logits = logits.index_select(&language_token_ids, 0)?; let probs = candle_nn::ops::softmax(&logits, D::Minus1)?; let probs = probs.to_vec1::<f32>()?; let mut probs = LANGUAGES.iter().zip(probs.iter()).collect::<Vec<_>>(); probs.sort_by(|(_, p1), (_, p2)| p2.total_cmp(p1)); for ((_, language), p) in probs.iter().take(5) { println!("{language}: {p}") } let token = &format!("<|{}|>", probs[0].0 .0); let language = token_id(tokenizer, token)?; console_log!("detected language: {language} {token}"); Ok(language) } pub fn token_id(tokenizer: &Tokenizer, token: &str) -> candle::Result<u32> { match tokenizer.token_to_id(token) { None => candle::bail!("no token-id for {token}"), Some(id) => Ok(id), } } #[derive(Serialize, Deserialize, Clone, Copy, Debug)] pub enum Task { Transcribe, Translate, } // Communication to the worker happens through bincode, the model weights and configs are fetched // on the main thread and transferred via the following structure. #[derive(Serialize, Deserialize)] pub struct ModelData { pub weights: Vec<u8>, pub tokenizer: Vec<u8>, pub mel_filters: Vec<u8>, pub config: Vec<u8>, pub quantized: bool, pub timestamps: bool, pub is_multilingual: bool, pub language: Option<String>, pub task: Option<String>, } pub struct Worker { link: WorkerLink<Self>, decoder: Option<Decoder>, } #[derive(Serialize, Deserialize)] pub enum WorkerInput { ModelData(ModelData), DecodeTask { wav_bytes: Vec<u8> }, } #[derive(Serialize, Deserialize)] pub enum WorkerOutput { Decoded(Vec<Segment>), WeightsLoaded, } impl yew_agent::Worker for Worker { type Input = WorkerInput; type Message = (); type Output = Result<WorkerOutput, String>; type Reach = Public<Self>; fn create(link: WorkerLink<Self>) -> Self { Self { link, decoder: None, } } fn update(&mut self, _msg: Self::Message) { // no messaging } fn handle_input(&mut self, msg: Self::Input, id: HandlerId) { let output = match msg { WorkerInput::ModelData(md) => match Decoder::load(md) { Ok(decoder) => { self.decoder = Some(decoder); Ok(WorkerOutput::WeightsLoaded) } Err(err) => Err(format!("model creation error {err:?}")), }, WorkerInput::DecodeTask { wav_bytes } => match &mut self.decoder { None => Err("model has not been set".to_string()), Some(decoder) => decoder .convert_and_run(&wav_bytes) .map(WorkerOutput::Decoded) .map_err(|e| e.to_string()), }, }; self.link.respond(id, output); } fn name_of_resource() -> &'static str { "worker.js" } fn resource_path_is_relative() -> bool { true } }
candle/candle-wasm-examples/whisper/src/worker.rs/0
{ "file_path": "candle/candle-wasm-examples/whisper/src/worker.rs", "repo_id": "candle", "token_count": 8765 }
46
[package] name = "candle-wasm-tests" version.workspace = true edition.workspace = true description = "WASM tests for candle" keywords.workspace = true categories.workspace = true [dependencies] candle = { workspace = true } rand = { workspace = true } getrandom = { version = "0.2", features = ["js"] } [dev-dependencies] wasm-bindgen-test = "0.3.0"
candle/candle-wasm-tests/Cargo.toml/0
{ "file_path": "candle/candle-wasm-tests/Cargo.toml", "repo_id": "candle", "token_count": 122 }
47
ARG INCLUDE_DB=false FROM mongo:latest as mongo FROM node:20-slim as local_db_false FROM node:20-slim as local_db_true RUN apt-get update RUN apt-get install gnupg curl -y COPY --from=mongo /usr/bin/mongo* /usr/bin/ FROM local_db_${INCLUDE_DB} as final ARG INCLUDE_DB=false ENV INCLUDE_DB=${INCLUDE_DB} WORKDIR /app COPY --link --chown=1000 package-lock.json package.json ./ RUN --mount=type=cache,target=/app/.npm \ npm set cache /app/.npm && \ npm ci # copy the rest of the files, run regardless of COPY --chown=1000 --link . . RUN chmod +x /app/entrypoint.sh CMD ["/bin/bash", "-c", "/app/entrypoint.sh"]
chat-ui/Dockerfile.local/0
{ "file_path": "chat-ui/Dockerfile.local", "repo_id": "chat-ui", "token_count": 278 }
48
export function clickOutside(element: HTMLDialogElement, callbackFunction: () => void) { function onClick(event: MouseEvent) { if (!element.contains(event.target as Node)) { callbackFunction(); } } document.body.addEventListener("click", onClick); return { update(newCallbackFunction: () => void) { callbackFunction = newCallbackFunction; }, destroy() { document.body.removeEventListener("click", onClick); }, }; }
chat-ui/src/lib/actions/clickOutside.ts/0
{ "file_path": "chat-ui/src/lib/actions/clickOutside.ts", "repo_id": "chat-ui", "token_count": 143 }
49
<script lang="ts"> import type { WebSearchUpdate } from "$lib/types/MessageUpdate"; import CarbonError from "~icons/carbon/error-filled"; import EosIconsLoading from "~icons/eos-icons/loading"; import IconInternet from "./icons/IconInternet.svelte"; export let classNames = ""; export let webSearchMessages: WebSearchUpdate[] = []; $: sources = webSearchMessages.find((m) => m.sources)?.sources; $: lastMessage = webSearchMessages.filter((m) => m.messageType !== "sources").slice(-1)[0]; $: loading = !sources && lastMessage.messageType !== "error"; </script> <details class="flex w-fit rounded-xl border border-gray-200 bg-white shadow-sm dark:border-gray-800 dark:bg-gray-900 {classNames} max-w-full" > <summary class="grid min-w-72 select-none grid-cols-[40px,1fr] items-center gap-2.5 p-2"> <div class="relative grid aspect-square place-content-center overflow-hidden rounded-lg bg-gray-100 dark:bg-gray-800" > <svg class="absolute inset-0 text-gray-300 transition-opacity dark:text-gray-700 {loading ? 'opacity-100' : 'opacity-0'}" width="40" height="40" viewBox="0 0 38 38" fill="none" xmlns="http://www.w3.org/2000/svg" > <path class="loading-path" d="M8 2.5H30C30 2.5 35.5 2.5 35.5 8V30C35.5 30 35.5 35.5 30 35.5H8C8 35.5 2.5 35.5 2.5 30V8C2.5 8 2.5 2.5 8 2.5Z" stroke="currentColor" stroke-width="1" stroke-linecap="round" id="shape" /> </svg> <IconInternet classNames="relative fill-current text-xl" /> </div> <dl class="leading-4"> <dd class="text-sm">Web Search</dd> <dt class="flex items-center gap-1 truncate whitespace-nowrap text-[.82rem] text-gray-400"> {#if sources} Completed {:else} {lastMessage.message} {/if} </dt> </dl> </summary> <div class="content px-5 pb-5 pt-4"> {#if webSearchMessages.length === 0} <div class="mx-auto w-fit"> <EosIconsLoading class="mb-3 h-4 w-4" /> </div> {:else} <ol> {#each webSearchMessages as message} {#if message.messageType === "update"} <li class="group border-l pb-6 last:!border-transparent last:pb-0 dark:border-gray-800"> <div class="flex items-start"> <div class="-ml-1.5 h-3 w-3 flex-none rounded-full bg-gray-200 dark:bg-gray-600 {loading ? 'group-last:animate-pulse group-last:bg-gray-300 group-last:dark:bg-gray-500' : ''}" /> <h3 class="text-md -mt-1.5 pl-2.5 text-gray-800 dark:text-gray-100"> {message.message} </h3> </div> {#if message.args} <p class="mt-1.5 pl-4 text-gray-500 dark:text-gray-400"> {message.args} </p> {/if} </li> {:else if message.messageType === "error"} <li class="group border-l pb-6 last:!border-transparent last:pb-0 dark:border-gray-800"> <div class="flex items-start"> <CarbonError class="-ml-1.5 h-3 w-3 flex-none scale-110 text-red-700 dark:text-red-500" /> <h3 class="text-md -mt-1.5 pl-2.5 text-red-700 dark:text-red-500"> {message.message} </h3> </div> {#if message.args} <p class="mt-1.5 pl-4 text-gray-500 dark:text-gray-400"> {message.args} </p> {/if} </li> {/if} {/each} </ol> {/if} </div> </details> <style> details summary::-webkit-details-marker { display: none; } .loading-path { stroke-dasharray: 61.45; animation: loading 2s linear infinite; } @keyframes loading { to { stroke-dashoffset: 122.9; } } </style>
chat-ui/src/lib/components/OpenWebSearchResults.svelte/0
{ "file_path": "chat-ui/src/lib/components/OpenWebSearchResults.svelte", "repo_id": "chat-ui", "token_count": 1709 }
50
<script lang="ts"> import { marked } from "marked"; import markedKatex from "marked-katex-extension"; import type { Message } from "$lib/types/Message"; import { afterUpdate, createEventDispatcher, tick } from "svelte"; import { deepestChild } from "$lib/utils/deepestChild"; import { page } from "$app/stores"; import CodeBlock from "../CodeBlock.svelte"; import CopyToClipBoardBtn from "../CopyToClipBoardBtn.svelte"; import IconLoading from "../icons/IconLoading.svelte"; import CarbonRotate360 from "~icons/carbon/rotate-360"; import CarbonDownload from "~icons/carbon/download"; import CarbonThumbsUp from "~icons/carbon/thumbs-up"; import CarbonThumbsDown from "~icons/carbon/thumbs-down"; import CarbonPen from "~icons/carbon/pen"; import CarbonChevronLeft from "~icons/carbon/chevron-left"; import CarbonChevronRight from "~icons/carbon/chevron-right"; import { PUBLIC_SEP_TOKEN } from "$lib/constants/publicSepToken"; import type { Model } from "$lib/types/Model"; import OpenWebSearchResults from "../OpenWebSearchResults.svelte"; import type { WebSearchUpdate } from "$lib/types/MessageUpdate"; import { base } from "$app/paths"; import { useConvTreeStore } from "$lib/stores/convTree"; function sanitizeMd(md: string) { let ret = md .replace(/<\|[a-z]*$/, "") .replace(/<\|[a-z]+\|$/, "") .replace(/<$/, "") .replaceAll(PUBLIC_SEP_TOKEN, " ") .replaceAll(/<\|[a-z]+\|>/g, " ") .replaceAll(/<br\s?\/?>/gi, "\n") .replaceAll("<", "&lt;") .trim(); for (const stop of [...(model.parameters?.stop ?? []), "<|endoftext|>"]) { if (ret.endsWith(stop)) { ret = ret.slice(0, -stop.length).trim(); } } return ret; } function unsanitizeMd(md: string) { return md.replaceAll("&lt;", "<"); } export let model: Model; export let id: Message["id"]; export let messages: Message[]; export let loading = false; export let isAuthor = true; export let readOnly = false; export let isTapped = false; $: message = messages.find((m) => m.id === id) ?? ({} as Message); const dispatch = createEventDispatcher<{ retry: { content?: string; id: Message["id"] }; vote: { score: Message["score"]; id: Message["id"] }; }>(); let contentEl: HTMLElement; let loadingEl: IconLoading; let pendingTimeout: ReturnType<typeof setTimeout>; let isCopied = false; let initialized = false; const renderer = new marked.Renderer(); // For code blocks with simple backticks renderer.codespan = (code) => { // Unsanitize double-sanitized code return `<code>${code.replaceAll("&amp;", "&")}</code>`; }; renderer.link = (href, title, text) => { return `<a href="${href?.replace(/>$/, "")}" target="_blank" rel="noreferrer">${text}</a>`; }; // eslint-disable-next-line @typescript-eslint/no-unused-vars const { extensions, ...defaults } = marked.getDefaults() as marked.MarkedOptions & { // eslint-disable-next-line @typescript-eslint/no-explicit-any extensions: any; }; const options: marked.MarkedOptions = { ...defaults, gfm: true, breaks: true, renderer, }; marked.use( markedKatex({ throwOnError: false, // output: "html", }) ); $: tokens = marked.lexer(sanitizeMd(message.content)); $: emptyLoad = !message.content && (webSearchIsDone || (searchUpdates && searchUpdates.length === 0)); afterUpdate(() => { loadingEl?.$destroy(); clearTimeout(pendingTimeout); // Add loading animation to the last message if update takes more than 600ms if (isLast && loading && emptyLoad) { pendingTimeout = setTimeout(() => { if (contentEl) { loadingEl = new IconLoading({ target: deepestChild(contentEl), props: { classNames: "loading inline ml-2 first:ml-0" }, }); } }, 600); } }); function handleKeyDown(e: KeyboardEvent) { if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) { editFormEl.requestSubmit(); } } $: searchUpdates = (message.updates?.filter(({ type }) => type === "webSearch") ?? []) as WebSearchUpdate[]; $: downloadLink = message.from === "user" ? `${$page.url.pathname}/message/${message.id}/prompt` : undefined; let webSearchIsDone = true; $: webSearchIsDone = searchUpdates.length > 0 && searchUpdates[searchUpdates.length - 1].messageType === "sources"; $: webSearchSources = searchUpdates && searchUpdates?.filter(({ messageType }) => messageType === "sources")?.[0]?.sources; $: if (isCopied) { setTimeout(() => { isCopied = false; }, 1000); } $: editMode = $convTreeStore.editing === message.id; let editContentEl: HTMLTextAreaElement; let editFormEl: HTMLFormElement; $: if (editMode) { tick(); if (editContentEl) { editContentEl.value = message.content; editContentEl?.focus(); } } $: isLast = (message && message.children?.length === 0) ?? false; $: childrenToRender = 0; $: nChildren = message?.children?.length ?? 0; $: { if (initialized) { childrenToRender = Math.max(0, nChildren - 1); } else { childrenToRender = 0; initialized = true; } } const convTreeStore = useConvTreeStore(); $: if (message.children?.length === 0) $convTreeStore.leaf = message.id; </script> {#if message.from === "assistant"} <div class="group relative -mb-6 flex items-start justify-start gap-4 pb-4 leading-relaxed" role="presentation" on:click={() => (isTapped = !isTapped)} on:keydown={() => (isTapped = !isTapped)} > {#if $page.data?.assistant?.avatar} <img src="{base}/settings/assistants/{$page.data.assistant._id}/avatar.jpg" alt="Avatar" class="mt-5 h-3 w-3 flex-none select-none rounded-full shadow-lg" /> {:else} <img alt="" src="https://huggingface.co/avatars/2edb18bd0206c16b433841a47f53fa8e.svg" class="mt-5 h-3 w-3 flex-none select-none rounded-full shadow-lg" /> {/if} <div class="relative min-h-[calc(2rem+theme(spacing[3.5])*2)] min-w-[60px] break-words rounded-2xl border border-gray-100 bg-gradient-to-br from-gray-50 px-5 py-3.5 text-gray-600 prose-pre:my-2 dark:border-gray-800 dark:from-gray-800/40 dark:text-gray-300" > {#if searchUpdates && searchUpdates.length > 0} <OpenWebSearchResults classNames={tokens.length ? "mb-3.5" : ""} webSearchMessages={searchUpdates} /> {/if} <div class="prose max-w-none max-sm:prose-sm dark:prose-invert prose-headings:font-semibold prose-h1:text-lg prose-h2:text-base prose-h3:text-base prose-pre:bg-gray-800 dark:prose-pre:bg-gray-900" bind:this={contentEl} > {#each tokens as token} {#if token.type === "code"} <CodeBlock lang={token.lang} code={unsanitizeMd(token.text)} /> {:else} <!-- eslint-disable-next-line svelte/no-at-html-tags --> {@html marked.parse(token.raw, options)} {/if} {/each} </div> <!-- Web Search sources --> {#if webSearchSources?.length} <div class="mt-4 flex flex-wrap items-center gap-x-2 gap-y-1.5 text-sm"> <div class="text-gray-400">Sources:</div> {#each webSearchSources as { link, title, hostname }} <a class="flex items-center gap-2 whitespace-nowrap rounded-lg border bg-white px-2 py-1.5 leading-none hover:border-gray-300 dark:border-gray-800 dark:bg-gray-900 dark:hover:border-gray-700" href={link} target="_blank" > <img class="h-3.5 w-3.5 rounded" src="https://www.google.com/s2/favicons?sz=64&domain_url={hostname}" alt="{title} favicon" /> <div>{hostname.replace(/^www\./, "")}</div> </a> {/each} </div> {/if} </div> {#if !loading && message.content} <div class="absolute bottom-1 right-0 -mb-4 flex max-md:transition-all md:bottom-0 md:group-hover:visible md:group-hover:opacity-100 {message.score ? 'visible opacity-100' : 'invisible max-md:-translate-y-4 max-md:opacity-0'} {isTapped || isCopied ? 'max-md:visible max-md:translate-y-0 max-md:opacity-100' : ''} " > {#if isAuthor} <button class="btn rounded-sm p-1 text-sm text-gray-400 focus:ring-0 hover:text-gray-500 dark:text-gray-400 dark:hover:text-gray-300 {message.score && message.score > 0 ? 'text-green-500 hover:text-green-500 dark:text-green-400 hover:dark:text-green-400' : ''}" title={message.score === 1 ? "Remove +1" : "+1"} type="button" on:click={() => dispatch("vote", { score: message.score === 1 ? 0 : 1, id: message.id })} > <CarbonThumbsUp class="h-[1.14em] w-[1.14em]" /> </button> <button class="btn rounded-sm p-1 text-sm text-gray-400 focus:ring-0 hover:text-gray-500 dark:text-gray-400 dark:hover:text-gray-300 {message.score && message.score < 0 ? 'text-red-500 hover:text-red-500 dark:text-red-400 hover:dark:text-red-400' : ''}" title={message.score === -1 ? "Remove -1" : "-1"} type="button" on:click={() => dispatch("vote", { score: message.score === -1 ? 0 : -1, id: message.id })} > <CarbonThumbsDown class="h-[1.14em] w-[1.14em]" /> </button> {/if} <button class="btn rounded-sm p-1 text-sm text-gray-400 focus:ring-0 hover:text-gray-500 dark:text-gray-400 dark:hover:text-gray-300" title="Retry" type="button" on:click={() => dispatch("retry", { id: message.id })} > <CarbonRotate360 /> </button> <CopyToClipBoardBtn on:click={() => { isCopied = true; }} classNames="ml-1.5 !rounded-sm !p-1 !text-sm !text-gray-400 focus:!ring-0 hover:!text-gray-500 dark:!text-gray-400 dark:hover:!text-gray-300 !border-none !shadow-none" value={message.content} /> </div> {/if} </div> <slot name="childrenNav" /> {/if} {#if message.from === "user"} <div class="group relative w-full items-start justify-start gap-4 max-sm:text-sm" role="presentation" on:click={() => (isTapped = !isTapped)} on:keydown={() => (isTapped = !isTapped)} > <div class="flex w-full flex-col"> {#if message.files && message.files.length > 0} <div class="mx-auto grid w-fit grid-cols-2 gap-5 px-5"> {#each message.files as file} <!-- handle the case where this is a hash that points to an image in the db, hash is always 64 char long --> {#if file.length === 64} <img src={$page.url.pathname + "/output/" + file} alt="input from user" class="my-2 aspect-auto max-h-48 rounded-lg shadow-lg" /> {:else} <!-- handle the case where this is a base64 encoded image --> <img src={"data:image/*;base64," + file} alt="input from user" class="my-2 aspect-auto max-h-48 rounded-lg shadow-lg" /> {/if} {/each} </div> {/if} <div class="flex w-full flex-row flex-nowrap"> {#if !editMode} <p class="disabled w-full appearance-none whitespace-break-spaces text-wrap break-words bg-inherit px-5 py-3.5 text-gray-500 dark:text-gray-400" > {message.content.trim()} </p> {:else} <form class="flex w-full flex-col" bind:this={editFormEl} on:submit|preventDefault={() => { dispatch("retry", { content: editContentEl.value, id: message.id }); $convTreeStore.editing = null; }} > <textarea class="w-full whitespace-break-spaces break-words rounded-lg bg-gray-100 px-5 py-3.5 text-gray-500 *:h-max dark:bg-gray-800 dark:text-gray-400" bind:this={editContentEl} value={message.content.trim()} on:keydown={handleKeyDown} required /> <div class="flex w-full flex-row flex-nowrap items-center justify-center gap-2 pt-2"> <button type="submit" class="btn rounded-lg px-3 py-1.5 text-sm {loading ? 'bg-gray-300 text-gray-400 dark:bg-gray-700 dark:text-gray-600' : 'bg-gray-200 text-gray-600 focus:ring-0 hover:text-gray-800 dark:bg-gray-800 dark:text-gray-300 dark:hover:text-gray-200'} " disabled={loading} > Submit </button> <button type="button" class="btn rounded-sm p-2 text-sm text-gray-400 focus:ring-0 hover:text-gray-500 dark:text-gray-400 dark:hover:text-gray-300" on:click={() => { $convTreeStore.editing = null; }} > Cancel </button> </div> </form> {/if} {#if !loading && !editMode} <div class=" max-md:opacity-0' invisible absolute right-0 top-3.5 z-10 h-max max-md:-translate-y-4 max-md:transition-all md:bottom-0 md:group-hover:visible md:group-hover:opacity-100 {isTapped || isCopied ? 'max-md:visible max-md:translate-y-0 max-md:opacity-100' : ''}" > <div class="mx-auto flex flex-row flex-nowrap gap-2"> {#if downloadLink} <a class="rounded-lg border border-gray-100 bg-gray-100 p-1 text-xs text-gray-400 group-hover:block hover:text-gray-500 max-sm:!hidden md:hidden dark:border-gray-800 dark:bg-gray-800 dark:text-gray-400 dark:hover:text-gray-300" title="Download prompt and parameters" type="button" target="_blank" href={downloadLink} > <CarbonDownload /> </a> {/if} {#if !readOnly} <button class="cursor-pointer rounded-lg border border-gray-100 bg-gray-100 p-1 text-xs text-gray-400 group-hover:block hover:text-gray-500 md:hidden lg:-right-2 dark:border-gray-800 dark:bg-gray-800 dark:text-gray-400 dark:hover:text-gray-300" title="Branch" type="button" on:click={() => ($convTreeStore.editing = message.id)} > <CarbonPen /> </button> {/if} </div> </div> {/if} </div> <slot name="childrenNav" /> </div> </div> {/if} {#if nChildren > 0} <svelte:self {loading} {messages} {isAuthor} {readOnly} {model} id={messages.find((m) => m.id === id)?.children?.[childrenToRender]} on:retry on:vote on:continue > <svelte:fragment slot="childrenNav"> {#if nChildren > 1 && $convTreeStore.editing === null} <div class="font-white z-10 -mt-1 ml-3.5 mr-auto flex h-6 w-fit select-none flex-row items-center justify-center gap-1 text-sm" > <button class="inline text-lg font-thin text-gray-400 disabled:pointer-events-none disabled:opacity-25 hover:text-gray-800 dark:text-gray-500 dark:hover:text-gray-200" on:click={() => (childrenToRender = Math.max(0, childrenToRender - 1))} disabled={childrenToRender === 0 || loading} > <CarbonChevronLeft class="text-sm" /> </button> <span class=" text-gray-400 dark:text-gray-500"> {childrenToRender + 1} / {nChildren} </span> <button class="inline text-lg font-thin text-gray-400 disabled:pointer-events-none disabled:opacity-25 hover:text-gray-800 dark:text-gray-500 dark:hover:text-gray-200" on:click={() => (childrenToRender = Math.min( message?.children?.length ?? 1 - 1, childrenToRender + 1 ))} disabled={childrenToRender === nChildren - 1 || loading} > <CarbonChevronRight class="text-sm" /> </button> </div> {/if} </svelte:fragment> </svelte:self> {/if}
chat-ui/src/lib/components/chat/ChatMessage.svelte/0
{ "file_path": "chat-ui/src/lib/components/chat/ChatMessage.svelte", "repo_id": "chat-ui", "token_count": 6727 }
51
import type { MongoClient, ObjectId } from "mongodb"; import updateSearchAssistant from "./01-update-search-assistants"; export interface Migration { _id: ObjectId; name: string; up: (client: MongoClient) => Promise<boolean>; down?: (client: MongoClient) => Promise<boolean>; runForFreshInstall?: "only" | "never"; // leave unspecified to run for both runForHuggingChat?: "only" | "never"; // leave unspecified to run for both } export const migrations: Migration[] = [updateSearchAssistant];
chat-ui/src/lib/migrations/routines/index.ts/0
{ "file_path": "chat-ui/src/lib/migrations/routines/index.ts", "repo_id": "chat-ui", "token_count": 149 }
52
import type { TextGenerationStreamOutput } from "@huggingface/inference"; import type OpenAI from "openai"; import type { Stream } from "openai/streaming"; /** * Transform a stream of OpenAI.Completions.Completion into a stream of TextGenerationStreamOutput */ export async function* openAICompletionToTextGenerationStream( completionStream: Stream<OpenAI.Completions.Completion> ) { let generatedText = ""; let tokenId = 0; for await (const completion of completionStream) { const { choices } = completion; const text = choices[0]?.text ?? ""; const last = choices[0]?.finish_reason === "stop"; if (text) { generatedText = generatedText + text; } const output: TextGenerationStreamOutput = { token: { id: tokenId++, text, logprob: 0, special: last, }, generated_text: last ? generatedText : null, details: null, }; yield output; } }
chat-ui/src/lib/server/endpoints/openai/openAICompletionToTextGenerationStream.ts/0
{ "file_path": "chat-ui/src/lib/server/endpoints/openai/openAICompletionToTextGenerationStream.ts", "repo_id": "chat-ui", "token_count": 310 }
53
import type { YouWebSearch } from "../../types/WebSearch"; import { WebSearchProvider } from "../../types/WebSearch"; import { SERPAPI_KEY, SERPER_API_KEY, SERPSTACK_API_KEY, USE_LOCAL_WEBSEARCH, SEARXNG_QUERY_URL, YDC_API_KEY, } from "$env/static/private"; import { getJson } from "serpapi"; import type { GoogleParameters } from "serpapi"; import { searchWebLocal } from "./searchWebLocal"; import { searchSearxng } from "./searchSearxng"; // get which SERP api is providing web results export function getWebSearchProvider() { if (YDC_API_KEY) { return WebSearchProvider.YOU; } else if (SEARXNG_QUERY_URL) { return WebSearchProvider.SEARXNG; } else { return WebSearchProvider.GOOGLE; } } // Show result as JSON export async function searchWeb(query: string) { if (USE_LOCAL_WEBSEARCH) { return await searchWebLocal(query); } if (SEARXNG_QUERY_URL) { return await searchSearxng(query); } if (SERPER_API_KEY) { return await searchWebSerper(query); } if (YDC_API_KEY) { return await searchWebYouApi(query); } if (SERPAPI_KEY) { return await searchWebSerpApi(query); } if (SERPSTACK_API_KEY) { return await searchSerpStack(query); } throw new Error("No You.com or Serper.dev or SerpAPI key found"); } export async function searchWebSerper(query: string) { const params = { q: query, hl: "en", gl: "us", }; const response = await fetch("https://google.serper.dev/search", { method: "POST", body: JSON.stringify(params), headers: { "x-api-key": SERPER_API_KEY, "Content-type": "application/json; charset=UTF-8", }, }); /* eslint-disable @typescript-eslint/no-explicit-any */ const data = (await response.json()) as Record<string, any>; if (!response.ok) { throw new Error( data["message"] ?? `Serper API returned error code ${response.status} - ${response.statusText}` ); } return { organic_results: data["organic"] ?? [], }; } export async function searchWebSerpApi(query: string) { const params = { q: query, hl: "en", gl: "us", google_domain: "google.com", api_key: SERPAPI_KEY, } satisfies GoogleParameters; // Show result as JSON const response = await getJson("google", params); return response; } export async function searchWebYouApi(query: string) { const response = await fetch(`https://api.ydc-index.io/search?query=${query}`, { method: "GET", headers: { "X-API-Key": YDC_API_KEY, "Content-type": "application/json; charset=UTF-8", }, }); if (!response.ok) { throw new Error(`You.com API returned error code ${response.status} - ${response.statusText}`); } const data = (await response.json()) as YouWebSearch; const formattedResultsWithSnippets = data.hits .map(({ title, url, snippets }) => ({ title, link: url, text: snippets?.join("\n") || "", hostname: new URL(url).hostname, })) .sort((a, b) => b.text.length - a.text.length); // desc order by text length return { organic_results: formattedResultsWithSnippets, }; } export async function searchSerpStack(query: string) { const response = await fetch( `http://api.serpstack.com/search?access_key=${SERPSTACK_API_KEY}&query=${query}&hl=en&gl=us`, { method: "GET", headers: { "Content-type": "application/json; charset=UTF-8", }, } ); const data = (await response.json()) as Record<string, any>; if (!response.ok) { throw new Error( data["error"] ?? `SerpStack API returned error code ${response.status} - ${response.statusText}` ); } const resultsWithSnippets = data["organic_results"].map( ({ title, url, snippet }: { title: string; url: string; snippet: string | undefined }) => ({ title, link: url, text: snippet || "", }) ); return { organic_results: resultsWithSnippets ?? [], }; }
chat-ui/src/lib/server/websearch/searchWeb.ts/0
{ "file_path": "chat-ui/src/lib/server/websearch/searchWeb.ts", "repo_id": "chat-ui", "token_count": 1441 }
54
import type { MessageUpdate } from "./MessageUpdate"; import type { Timestamps } from "./Timestamps"; import type { WebSearch } from "./WebSearch"; import type { v4 } from "uuid"; export type Message = Partial<Timestamps> & { from: "user" | "assistant" | "system"; id: ReturnType<typeof v4>; content: string; updates?: MessageUpdate[]; webSearchId?: WebSearch["_id"]; // legacy version webSearch?: WebSearch; score?: -1 | 0 | 1; files?: string[]; // can contain either the hash of the file or the b64 encoded image data on the client side when uploading interrupted?: boolean; // needed for conversation trees ancestors?: Message["id"][]; // goes one level deep children?: Message["id"][]; };
chat-ui/src/lib/types/Message.ts/0
{ "file_path": "chat-ui/src/lib/types/Message.ts", "repo_id": "chat-ui", "token_count": 219 }
55
/** * Chunk array into arrays of length at most `chunkSize` * * @param chunkSize must be greater than or equal to 1 */ export function chunk<T extends unknown[] | string>(arr: T, chunkSize: number): T[] { if (isNaN(chunkSize) || chunkSize < 1) { throw new RangeError("Invalid chunk size: " + chunkSize); } if (!arr.length) { return []; } /// Small optimization to not chunk buffers unless needed if (arr.length <= chunkSize) { return [arr]; } return range(Math.ceil(arr.length / chunkSize)).map((i) => { return arr.slice(i * chunkSize, (i + 1) * chunkSize); }) as T[]; } function range(n: number, b?: number): number[] { return b ? Array(b - n) .fill(0) .map((_, i) => n + i) : Array(n) .fill(0) .map((_, i) => i); }
chat-ui/src/lib/utils/chunk.ts/0
{ "file_path": "chat-ui/src/lib/utils/chunk.ts", "repo_id": "chat-ui", "token_count": 295 }
56
const PUNCTUATION_REGEX = /\p{P}/gu; function removeDiacritics(s: string, form: "NFD" | "NFKD" = "NFD"): string { return s.normalize(form).replace(/[\u0300-\u036f]/g, ""); } export function generateSearchTokens(value: string): string[] { const fullTitleToken = removeDiacritics(value) .replace(PUNCTUATION_REGEX, "") .replaceAll(/\s+/g, "") .toLowerCase(); return [ ...new Set([ ...removeDiacritics(value) .split(/\s+/) .map((word) => word.replace(PUNCTUATION_REGEX, "").toLowerCase()) .filter((word) => word.length), ...(fullTitleToken.length ? [fullTitleToken] : []), ]), ]; } function escapeForRegExp(s: string): string { return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string } export function generateQueryTokens(query: string): RegExp[] { return removeDiacritics(query) .split(/\s+/) .map((word) => word.replace(PUNCTUATION_REGEX, "").toLowerCase()) .filter((word) => word.length) .map((token) => new RegExp(`^${escapeForRegExp(token)}`)); }
chat-ui/src/lib/utils/searchTokens.ts/0
{ "file_path": "chat-ui/src/lib/utils/searchTokens.ts", "repo_id": "chat-ui", "token_count": 426 }
57
import type { Message } from "$lib/types/Message"; export function isMessageId(id: string): id is Message["id"] { return id.split("-").length === 5; }
chat-ui/src/lib/utils/tree/isMessageId.ts/0
{ "file_path": "chat-ui/src/lib/utils/tree/isMessageId.ts", "repo_id": "chat-ui", "token_count": 48 }
58
import { base } from "$app/paths"; import { ENABLE_ASSISTANTS } from "$env/static/private"; import { collections } from "$lib/server/database.js"; import type { Assistant } from "$lib/types/Assistant"; import type { User } from "$lib/types/User"; import { generateQueryTokens } from "$lib/utils/searchTokens.js"; import { error, redirect } from "@sveltejs/kit"; import type { Filter } from "mongodb"; const NUM_PER_PAGE = 24; export const load = async ({ url, locals }) => { if (!ENABLE_ASSISTANTS) { throw redirect(302, `${base}/`); } const modelId = url.searchParams.get("modelId"); const pageIndex = parseInt(url.searchParams.get("p") ?? "0"); const username = url.searchParams.get("user"); const query = url.searchParams.get("q")?.trim() ?? null; const createdByCurrentUser = locals.user?.username && locals.user.username === username; let user: Pick<User, "_id"> | null = null; if (username) { user = await collections.users.findOne<Pick<User, "_id">>( { username }, { projection: { _id: 1 } } ); if (!user) { throw error(404, `User "${username}" doesn't exist`); } } // fetch the top assistants sorted by user count from biggest to smallest, filter out all assistants with only 1 users. filter by model too if modelId is provided const filter: Filter<Assistant> = { ...(modelId && { modelId }), ...(!createdByCurrentUser && { userCount: { $gt: 1 } }), ...(user ? { createdById: user._id } : { featured: true }), ...(query && { searchTokens: { $all: generateQueryTokens(query) } }), }; const assistants = await collections.assistants .find(filter) .skip(NUM_PER_PAGE * pageIndex) .sort({ userCount: -1 }) .limit(NUM_PER_PAGE) .toArray(); const numTotalItems = await collections.assistants.countDocuments(filter); return { assistants: JSON.parse(JSON.stringify(assistants)) as Array<Assistant>, selectedModel: modelId ?? "", numTotalItems, numItemsPerPage: NUM_PER_PAGE, query, }; };
chat-ui/src/routes/assistants/+page.server.ts/0
{ "file_path": "chat-ui/src/routes/assistants/+page.server.ts", "repo_id": "chat-ui", "token_count": 673 }
59
import { dev } from "$app/environment"; import { base } from "$app/paths"; import { COOKIE_NAME } from "$env/static/private"; import { collections } from "$lib/server/database"; import { redirect } from "@sveltejs/kit"; export const actions = { async default({ cookies, locals }) { await collections.sessions.deleteOne({ sessionId: locals.sessionId }); cookies.delete(COOKIE_NAME, { path: "/", // So that it works inside the space's iframe sameSite: dev ? "lax" : "none", secure: !dev, httpOnly: true, }); throw redirect(303, `${base}/`); }, };
chat-ui/src/routes/logout/+page.server.ts/0
{ "file_path": "chat-ui/src/routes/logout/+page.server.ts", "repo_id": "chat-ui", "token_count": 203 }
60
<script lang="ts"> import { applyAction, enhance } from "$app/forms"; import { invalidateAll } from "$app/navigation"; import Modal from "$lib/components/Modal.svelte"; import { createEventDispatcher } from "svelte"; const dispatch = createEventDispatcher<{ close: void }>(); let reason = ""; </script> <Modal on:close> <form method="POST" action="?/report" use:enhance={() => { return async ({ result }) => { await applyAction(result); dispatch("close"); invalidateAll(); }; }} class="w-full min-w-64 p-4" > <span class="mb-1 text-sm font-semibold">Report an assistant</span> <p class="text-sm text-gray-500"> Please provide a brief description of why you are reporting this assistant. </p> <textarea name="reportReason" class="mt-6 max-h-48 w-full resize-y rounded-lg border-2 border-gray-200 bg-gray-100 p-2 text-smd" placeholder="Reason(s) for the report" maxlength="128" bind:value={reason} /> <div class="flex w-full flex-row justify-between px-2 pt-4"> <button type="button" class="text-sm text-gray-700 hover:underline" on:click={() => dispatch("close")}>Cancel</button > <button type="submit" class="rounded-full bg-black px-4 py-2 text-sm font-semibold text-white md:px-8" disabled={!reason} class:bg-gray-200={!reason} class:!text-gray-400={!reason} > Submit report </button> </div> </form> </Modal>
chat-ui/src/routes/settings/(nav)/assistants/[assistantId]/ReportModal.svelte/0
{ "file_path": "chat-ui/src/routes/settings/(nav)/assistants/[assistantId]/ReportModal.svelte", "repo_id": "chat-ui", "token_count": 593 }
61
{ "$schema": "https://vega.github.io/schema/vega-lite/v4.json", "data": { "values": "<DVC_METRIC_DATA>" }, "title": "<DVC_METRIC_TITLE>", "mark": { "type": "line" }, "encoding": { "x": { "field": "<DVC_METRIC_X>", "type": "quantitative", "title": "<DVC_METRIC_X_LABEL>" }, "y": { "field": "<DVC_METRIC_Y>", "type": "quantitative", "title": "<DVC_METRIC_Y_LABEL>", "scale": { "zero": false } }, "color": { "field": "rev", "type": "nominal" } }, "transform": [ { "loess": "<DVC_METRIC_Y>", "on": "<DVC_METRIC_X>", "groupby": [ "rev" ], "bandwidth": 0.3 } ] }
datasets/.dvc/plots/smooth.json/0
{ "file_path": "datasets/.dvc/plots/smooth.json", "repo_id": "datasets", "token_count": 569 }
62
# Process audio data This guide shows specific methods for processing audio datasets. Learn how to: - Resample the sampling rate. - Use [`~Dataset.map`] with audio datasets. For a guide on how to process any type of dataset, take a look at the <a class="underline decoration-sky-400 decoration-2 font-semibold" href="./process">general process guide</a>. ## Cast The [`~Dataset.cast_column`] function is used to cast a column to another feature to be decoded. When you use this function with the [`Audio`] feature, you can resample the sampling rate: ```py >>> from datasets import load_dataset, Audio >>> dataset = load_dataset("PolyAI/minds14", "en-US", split="train") >>> dataset = dataset.cast_column("audio", Audio(sampling_rate=16000)) ``` Audio files are decoded and resampled on-the-fly, so the next time you access an example, the audio file is resampled to 16kHz: ```py >>> dataset[0]["audio"] {'array': array([ 2.3443763e-05, 2.1729663e-04, 2.2145823e-04, ..., 3.8356509e-05, -7.3497440e-06, -2.1754686e-05], dtype=float32), 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav', 'sampling_rate': 16000} ``` <div class="flex justify-center"> <img class="block dark:hidden" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/resample.gif"/> <img class="hidden dark:block" src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/datasets/resample-dark.gif"/> </div> ## Map The [`~Dataset.map`] function helps preprocess your entire dataset at once. Depending on the type of model you're working with, you'll need to either load a [feature extractor](https://huggingface.co/docs/transformers/model_doc/auto#transformers.AutoFeatureExtractor) or a [processor](https://huggingface.co/docs/transformers/model_doc/auto#transformers.AutoProcessor). - For pretrained speech recognition models, load a feature extractor and tokenizer and combine them in a `processor`: ```py >>> from transformers import AutoTokenizer, AutoFeatureExtractor, AutoProcessor >>> model_checkpoint = "facebook/wav2vec2-large-xlsr-53" # after defining a vocab.json file you can instantiate a tokenizer object: >>> tokenizer = AutoTokenizer("./vocab.json", unk_token="[UNK]", pad_token="[PAD]", word_delimiter_token="|") >>> feature_extractor = AutoFeatureExtractor.from_pretrained(model_checkpoint) >>> processor = AutoProcessor.from_pretrained(feature_extractor=feature_extractor, tokenizer=tokenizer) ``` - For fine-tuned speech recognition models, you only need to load a `processor`: ```py >>> from transformers import AutoProcessor >>> processor = AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h") ``` When you use [`~Dataset.map`] with your preprocessing function, include the `audio` column to ensure you're actually resampling the audio data: ```py >>> def prepare_dataset(batch): ... audio = batch["audio"] ... batch["input_values"] = processor(audio["array"], sampling_rate=audio["sampling_rate"]).input_values[0] ... batch["input_length"] = len(batch["input_values"]) ... with processor.as_target_processor(): ... batch["labels"] = processor(batch["sentence"]).input_ids ... return batch >>> dataset = dataset.map(prepare_dataset, remove_columns=dataset.column_names) ```
datasets/docs/source/audio_process.mdx/0
{ "file_path": "datasets/docs/source/audio_process.mdx", "repo_id": "datasets", "token_count": 1186 }
63
<!--Copyright 2023 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> # Quickstart [[open-in-colab]] This quickstart is intended for developers who are ready to dive into the code and see an example of how to integrate 🤗 Datasets into their model training workflow. If you're a beginner, we recommend starting with our [tutorials](./tutorial), where you'll get a more thorough introduction. Each dataset is unique, and depending on the task, some datasets may require additional steps to prepare it for training. But you can always use 🤗 Datasets tools to load and process a dataset. The fastest and easiest way to get started is by loading an existing dataset from the [Hugging Face Hub](https://huggingface.co/datasets). There are thousands of datasets to choose from, spanning many tasks. Choose the type of dataset you want to work with, and let's get started! <div class="mt-4"> <div class="w-full flex flex-col space-y-4 md:space-y-0 md:grid md:grid-cols-3 md:gap-y-4 md:gap-x-5"> <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="#audio" ><div class="w-full text-center bg-gradient-to-r from-violet-300 via-sky-400 to-green-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Audio</div> <p class="text-gray-700">Resample an audio dataset and get it ready for a model to classify what type of banking issue a speaker is calling about.</p> </a> <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="#vision" ><div class="w-full text-center bg-gradient-to-r from-pink-400 via-purple-400 to-blue-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Vision</div> <p class="text-gray-700">Apply data augmentation to an image dataset and get it ready for a model to diagnose disease in bean plants.</p> </a> <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="#nlp" ><div class="w-full text-center bg-gradient-to-r from-orange-300 via-red-400 to-violet-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">NLP</div> <p class="text-gray-700">Tokenize a dataset and get it ready for a model to determine whether a pair of sentences have the same meaning.</p> </a> </div> </div> <Tip> Check out [Chapter 5](https://huggingface.co/course/chapter5/1?fw=pt) of the Hugging Face course to learn more about other important topics such as loading remote or local datasets, tools for cleaning up a dataset, and creating your own dataset. </Tip> Start by installing 🤗 Datasets: ```bash pip install datasets ``` 🤗 Datasets also support audio and image data formats: * To work with audio datasets, install the [`Audio`] feature: ```bash pip install datasets[audio] ``` * To work with image datasets, install the [`Image`] feature: ```bash pip install datasets[vision] ``` Besides 🤗 Datasets, make sure your preferred machine learning framework is installed: <frameworkcontent> <pt> ```bash pip install torch ``` </pt> <tf> ```bash pip install tensorflow ``` </tf> </frameworkcontent> ## Audio Audio datasets are loaded just like text datasets. However, an audio dataset is preprocessed a bit differently. Instead of a tokenizer, you'll need a [feature extractor](https://huggingface.co/docs/transformers/main_classes/feature_extractor#feature-extractor). An audio input may also require resampling its sampling rate to match the sampling rate of the pretrained model you're using. In this quickstart, you'll prepare the [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) dataset for a model train on and classify the banking issue a customer is having. **1**. Load the MInDS-14 dataset by providing the [`load_dataset`] function with the dataset name, dataset configuration (not all datasets will have a configuration), and a dataset split: ```py >>> from datasets import load_dataset, Audio >>> dataset = load_dataset("PolyAI/minds14", "en-US", split="train") ``` **2**. Next, load a pretrained [Wav2Vec2](https://huggingface.co/facebook/wav2vec2-base) model and its corresponding feature extractor from the [🤗 Transformers](https://huggingface.co/transformers/) library. It is totally normal to see a warning after you load the model about some weights not being initialized. This is expected because you are loading this model checkpoint for training with another task. ```py >>> from transformers import AutoModelForAudioClassification, AutoFeatureExtractor >>> model = AutoModelForAudioClassification.from_pretrained("facebook/wav2vec2-base") >>> feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base") ``` **3**. The [MInDS-14](https://huggingface.co/datasets/PolyAI/minds14) dataset card indicates the sampling rate is 8kHz, but the Wav2Vec2 model was pretrained on a sampling rate of 16kHZ. You'll need to upsample the `audio` column with the [`~Dataset.cast_column`] function and [`Audio`] feature to match the model's sampling rate. ```py >>> dataset = dataset.cast_column("audio", Audio(sampling_rate=16000)) >>> dataset[0]["audio"] {'array': array([ 2.3443763e-05, 2.1729663e-04, 2.2145823e-04, ..., 3.8356509e-05, -7.3497440e-06, -2.1754686e-05], dtype=float32), 'path': '/root/.cache/huggingface/datasets/downloads/extracted/f14948e0e84be638dd7943ac36518a4cf3324e8b7aa331c5ab11541518e9368c/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav', 'sampling_rate': 16000} ``` **4**. Create a function to preprocess the audio `array` with the feature extractor, and truncate and pad the sequences into tidy rectangular tensors. The most important thing to remember is to call the audio `array` in the feature extractor since the `array` - the actual speech signal - is the model input. Once you have a preprocessing function, use the [`~Dataset.map`] function to speed up processing by applying the function to batches of examples in the dataset. ```py >>> def preprocess_function(examples): ... audio_arrays = [x["array"] for x in examples["audio"]] ... inputs = feature_extractor( ... audio_arrays, ... sampling_rate=16000, ... padding=True, ... max_length=100000, ... truncation=True, ... ) ... return inputs >>> dataset = dataset.map(preprocess_function, batched=True) ``` **5**. Use the [`~Dataset.rename_column`] function to rename the `intent_class` column to `labels`, which is the expected input name in [Wav2Vec2ForSequenceClassification](https://huggingface.co/docs/transformers/main/en/model_doc/wav2vec2#transformers.Wav2Vec2ForSequenceClassification): ```py >>> dataset = dataset.rename_column("intent_class", "labels") ``` **6**. Set the dataset format according to the machine learning framework you're using. <frameworkcontent> <pt> Use the [`~Dataset.set_format`] function to set the dataset format to `torch` and specify the columns you want to format. This function applies formatting on-the-fly. After converting to PyTorch tensors, wrap the dataset in [`torch.utils.data.DataLoader`](https://alband.github.io/doc_view/data.html?highlight=torch%20utils%20data%20dataloader#torch.utils.data.DataLoader): ```py >>> from torch.utils.data import DataLoader >>> dataset.set_format(type="torch", columns=["input_values", "labels"]) >>> dataloader = DataLoader(dataset, batch_size=4) ``` </pt> <tf> Use the [`~transformers.TFPreTrainedModel.prepare_tf_dataset`] method from 🤗 Transformers to prepare the dataset to be compatible with TensorFlow, and ready to train/fine-tune a model, as it wraps a HuggingFace [`~datasets.Dataset`] as a `tf.data.Dataset` with collation and batching, so one can pass it directly to Keras methods like `fit()` without further modification. ```py >>> import tensorflow as tf >>> tf_dataset = model.prepare_tf_dataset( ... dataset, ... batch_size=4, ... shuffle=True, ... ) ``` </tf> </frameworkcontent> **7**. Start training with your machine learning framework! Check out the 🤗 Transformers [audio classification guide](https://huggingface.co/docs/transformers/tasks/audio_classification) for an end-to-end example of how to train a model on an audio dataset. ## Vision Image datasets are loaded just like text datasets. However, instead of a tokenizer, you'll need a [feature extractor](https://huggingface.co/docs/transformers/main_classes/feature_extractor#feature-extractor) to preprocess the dataset. Applying data augmentation to an image is common in computer vision to make the model more robust against overfitting. You're free to use any data augmentation library you want, and then you can apply the augmentations with 🤗 Datasets. In this quickstart, you'll load the [Beans](https://huggingface.co/datasets/beans) dataset and get it ready for the model to train on and identify disease from the leaf images. **1**. Load the Beans dataset by providing the [`load_dataset`] function with the dataset name and a dataset split: ```py >>> from datasets import load_dataset, Image >>> dataset = load_dataset("beans", split="train") ``` Most image models work with RBG images. If your dataset contains images in a different mode, you can use the [`~Dataset.cast_column`] function to set the mode to RGB: ```py >>> dataset = dataset.cast_column("image", Image(mode="RGB")) ``` The Beans dataset contains only RGB images, so this step is unnecessary here. **2**. Now you can add some data augmentations with any library ([Albumentations](https://albumentations.ai/), [imgaug](https://imgaug.readthedocs.io/en/latest/), [Kornia](https://kornia.readthedocs.io/en/latest/)) you like. Here, you'll use [torchvision](https://pytorch.org/vision/stable/transforms.html) to randomly change the color properties of an image: ```py >>> from torchvision.transforms import Compose, ColorJitter, ToTensor >>> jitter = Compose( ... [ColorJitter(brightness=0.5, hue=0.5), ToTensor()] ... ) ``` **3**. Create a function to apply your transform to the dataset and generate the model input: `pixel_values`. ```python >>> def transforms(examples): ... examples["pixel_values"] = [jitter(image.convert("RGB")) for image in examples["image"]] ... return examples ``` **4**. Use the [`~Dataset.with_transform`] function to apply the data augmentations on-the-fly: ```py >>> dataset = dataset.with_transform(transforms) ``` **5**. Set the dataset format according to the machine learning framework you're using. <frameworkcontent> <pt> Wrap the dataset in [`torch.utils.data.DataLoader`](https://alband.github.io/doc_view/data.html?highlight=torch%20utils%20data%20dataloader#torch.utils.data.DataLoader). You'll also need to create a collate function to collate the samples into batches: ```py >>> from torch.utils.data import DataLoader >>> def collate_fn(examples): ... images = [] ... labels = [] ... for example in examples: ... images.append((example["pixel_values"])) ... labels.append(example["labels"]) ... ... pixel_values = torch.stack(images) ... labels = torch.tensor(labels) ... return {"pixel_values": pixel_values, "labels": labels} >>> dataloader = DataLoader(dataset, collate_fn=collate_fn, batch_size=4) ``` </pt> <tf> Use the [`~transformers.TFPreTrainedModel.prepare_tf_dataset`] method from 🤗 Transformers to prepare the dataset to be compatible with TensorFlow, and ready to train/fine-tune a model, as it wraps a HuggingFace [`~datasets.Dataset`] as a `tf.data.Dataset` with collation and batching, so one can pass it directly to Keras methods like `fit()` without further modification. Before you start, make sure you have up-to-date versions of `albumentations` and `cv2` installed: ```bash pip install -U albumentations opencv-python ``` ```py >>> import albumentations >>> import numpy as np >>> transform = albumentations.Compose([ ... albumentations.RandomCrop(width=256, height=256), ... albumentations.HorizontalFlip(p=0.5), ... albumentations.RandomBrightnessContrast(p=0.2), ... ]) >>> def transforms(examples): ... examples["pixel_values"] = [ ... transform(image=np.array(image))["image"] for image in examples["image"] ... ] ... return examples >>> dataset.set_transform(transforms) >>> tf_dataset = model.prepare_tf_dataset( ... dataset, ... batch_size=4, ... shuffle=True, ... ) ``` </tf> </frameworkcontent> **6**. Start training with your machine learning framework! Check out the 🤗 Transformers [image classification guide](https://huggingface.co/docs/transformers/tasks/image_classification) for an end-to-end example of how to train a model on an image dataset. ## NLP Text needs to be tokenized into individual tokens by a [tokenizer](https://huggingface.co/docs/transformers/main_classes/tokenizer). For the quickstart, you'll load the [Microsoft Research Paraphrase Corpus (MRPC)](https://huggingface.co/datasets/glue/viewer/mrpc) training dataset to train a model to determine whether a pair of sentences mean the same thing. **1**. Load the MRPC dataset by providing the [`load_dataset`] function with the dataset name, dataset configuration (not all datasets will have a configuration), and dataset split: ```py >>> from datasets import load_dataset >>> dataset = load_dataset("glue", "mrpc", split="train") ``` **2**. Next, load a pretrained [BERT](https://huggingface.co/bert-base-uncased) model and its corresponding tokenizer from the [🤗 Transformers](https://huggingface.co/transformers/) library. It is totally normal to see a warning after you load the model about some weights not being initialized. This is expected because you are loading this model checkpoint for training with another task. ```py >>> from transformers import AutoModelForSequenceClassification, AutoTokenizer >>> model = AutoModelForSequenceClassification.from_pretrained("bert-base-uncased") >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased") ===PT-TF-SPLIT=== >>> from transformers import TFAutoModelForSequenceClassification, AutoTokenizer >>> model = TFAutoModelForSequenceClassification.from_pretrained("bert-base-uncased") >>> tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased") ``` **3**. Create a function to tokenize the dataset, and you should also truncate and pad the text into tidy rectangular tensors. The tokenizer generates three new columns in the dataset: `input_ids`, `token_type_ids`, and an `attention_mask`. These are the model inputs. Use the [`~Dataset.map`] function to speed up processing by applying your tokenization function to batches of examples in the dataset: ```py >>> def encode(examples): ... return tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, padding="max_length") >>> dataset = dataset.map(encode, batched=True) >>> dataset[0] {'sentence1': 'Amrozi accused his brother , whom he called " the witness " , of deliberately distorting his evidence .', 'sentence2': 'Referring to him as only " the witness " , Amrozi accused his brother of deliberately distorting his evidence .', 'label': 1, 'idx': 0, 'input_ids': array([ 101, 7277, 2180, 5303, 4806, 1117, 1711, 117, 2292, 1119, 1270, 107, 1103, 7737, 107, 117, 1104, 9938, 4267, 12223, 21811, 1117, 2554, 119, 102, 11336, 6732, 3384, 1106, 1140, 1112, 1178, 107, 1103, 7737, 107, 117, 7277, 2180, 5303, 4806, 1117, 1711, 1104, 9938, 4267, 12223, 21811, 1117, 2554, 119, 102]), 'token_type_ids': array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]), 'attention_mask': array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1])} ``` **4**. Rename the `label` column to `labels`, which is the expected input name in [BertForSequenceClassification](https://huggingface.co/docs/transformers/main/en/model_doc/bert#transformers.BertForSequenceClassification): ```py >>> dataset = dataset.map(lambda examples: {"labels": examples["label"]}, batched=True) ``` **5**. Set the dataset format according to the machine learning framework you're using. <frameworkcontent> <pt> Use the [`~Dataset.set_format`] function to set the dataset format to `torch` and specify the columns you want to format. This function applies formatting on-the-fly. After converting to PyTorch tensors, wrap the dataset in [`torch.utils.data.DataLoader`](https://alband.github.io/doc_view/data.html?highlight=torch%20utils%20data%20dataloader#torch.utils.data.DataLoader): ```py >>> import torch >>> dataset.set_format(type="torch", columns=["input_ids", "token_type_ids", "attention_mask", "labels"]) >>> dataloader = torch.utils.data.DataLoader(dataset, batch_size=32) ``` </pt> <tf> Use the [`~transformers.TFPreTrainedModel.prepare_tf_dataset`] method from 🤗 Transformers to prepare the dataset to be compatible with TensorFlow, and ready to train/fine-tune a model, as it wraps a HuggingFace [`~datasets.Dataset`] as a `tf.data.Dataset` with collation and batching, so one can pass it directly to Keras methods like `fit()` without further modification. ```py >>> import tensorflow as tf >>> tf_dataset = model.prepare_tf_dataset( ... dataset, ... batch_size=4, ... shuffle=True, ... ) ``` </tf> </frameworkcontent> **6**. Start training with your machine learning framework! Check out the 🤗 Transformers [text classification guide](https://huggingface.co/docs/transformers/tasks/sequence_classification) for an end-to-end example of how to train a model on a text dataset. ## What's next? This completes the 🤗 Datasets quickstart! You can load any text, audio, or image dataset with a single function and get it ready for your model to train on. For your next steps, take a look at our [How-to guides](./how_to) and learn how to do more specific things like loading different dataset formats, aligning labels, and streaming large datasets. If you're interested in learning more about 🤗 Datasets core concepts, grab a cup of coffee and read our [Conceptual Guides](./about_arrow)!
datasets/docs/source/quickstart.mdx/0
{ "file_path": "datasets/docs/source/quickstart.mdx", "repo_id": "datasets", "token_count": 6102 }
64
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor. # # 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. """Accuracy metric.""" from sklearn.metrics import accuracy_score import datasets _DESCRIPTION = """ Accuracy is the proportion of correct predictions among the total number of cases processed. It can be computed with: Accuracy = (TP + TN) / (TP + TN + FP + FN) Where: TP: True positive TN: True negative FP: False positive FN: False negative """ _KWARGS_DESCRIPTION = """ Args: predictions (`list` of `int`): Predicted labels. references (`list` of `int`): Ground truth labels. normalize (`boolean`): If set to False, returns the number of correctly classified samples. Otherwise, returns the fraction of correctly classified samples. Defaults to True. sample_weight (`list` of `float`): Sample weights Defaults to None. Returns: accuracy (`float` or `int`): Accuracy score. Minimum possible value is 0. Maximum possible value is 1.0, or the number of examples input, if `normalize` is set to `True`.. A higher score means higher accuracy. Examples: Example 1-A simple example >>> accuracy_metric = datasets.load_metric("accuracy") >>> results = accuracy_metric.compute(references=[0, 1, 2, 0, 1, 2], predictions=[0, 1, 1, 2, 1, 0]) >>> print(results) {'accuracy': 0.5} Example 2-The same as Example 1, except with `normalize` set to `False`. >>> accuracy_metric = datasets.load_metric("accuracy") >>> results = accuracy_metric.compute(references=[0, 1, 2, 0, 1, 2], predictions=[0, 1, 1, 2, 1, 0], normalize=False) >>> print(results) {'accuracy': 3.0} Example 3-The same as Example 1, except with `sample_weight` set. >>> accuracy_metric = datasets.load_metric("accuracy") >>> results = accuracy_metric.compute(references=[0, 1, 2, 0, 1, 2], predictions=[0, 1, 1, 2, 1, 0], sample_weight=[0.5, 2, 0.7, 0.5, 9, 0.4]) >>> print(results) {'accuracy': 0.8778625954198473} """ _CITATION = """ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION) class Accuracy(datasets.Metric): def _info(self): return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("int32")), "references": datasets.Sequence(datasets.Value("int32")), } if self.config_name == "multilabel" else { "predictions": datasets.Value("int32"), "references": datasets.Value("int32"), } ), reference_urls=["https://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html"], ) def _compute(self, predictions, references, normalize=True, sample_weight=None): return { "accuracy": float( accuracy_score(references, predictions, normalize=normalize, sample_weight=sample_weight) ) }
datasets/metrics/accuracy/accuracy.py/0
{ "file_path": "datasets/metrics/accuracy/accuracy.py", "repo_id": "datasets", "token_count": 1611 }
65
# Metric Card for Competition MATH ## Metric description This metric is used to assess performance on the [Mathematics Aptitude Test of Heuristics (MATH) dataset](https://huggingface.co/datasets/competition_math). It first canonicalizes the inputs (e.g., converting `1/2` to `\\frac{1}{2}`) and then computes accuracy. ## How to use This metric takes two arguments: `predictions`: a list of predictions to score. Each prediction is a string that contains natural language and LaTeX. `references`: list of reference for each prediction. Each reference is a string that contains natural language and LaTeX. ```python >>> from datasets import load_metric >>> math = load_metric("competition_math") >>> references = ["\\frac{1}{2}"] >>> predictions = ["1/2"] >>> results = math.compute(references=references, predictions=predictions) ``` N.B. To be able to use Competition MATH, you need to install the `math_equivalence` dependency using `pip install git+https://github.com/hendrycks/math.git`. ## Output values This metric returns a dictionary that contains the [accuracy](https://huggingface.co/metrics/accuracy) after canonicalizing inputs, on a scale between 0.0 and 1.0. ### Values from popular papers The [original MATH dataset paper](https://arxiv.org/abs/2103.03874) reported accuracies ranging from 3.0% to 6.9% by different large language models. More recent progress on the dataset can be found on the [dataset leaderboard](https://paperswithcode.com/sota/math-word-problem-solving-on-math). ## Examples Maximal values (full match): ```python >>> from datasets import load_metric >>> math = load_metric("competition_math") >>> references = ["\\frac{1}{2}"] >>> predictions = ["1/2"] >>> results = math.compute(references=references, predictions=predictions) >>> print(results) {'accuracy': 1.0} ``` Minimal values (no match): ```python >>> from datasets import load_metric >>> math = load_metric("competition_math") >>> references = ["\\frac{1}{2}"] >>> predictions = ["3/4"] >>> results = math.compute(references=references, predictions=predictions) >>> print(results) {'accuracy': 0.0} ``` Partial match: ```python >>> from datasets import load_metric >>> math = load_metric("competition_math") >>> references = ["\\frac{1}{2}","\\frac{3}{4}"] >>> predictions = ["1/5", "3/4"] >>> results = math.compute(references=references, predictions=predictions) >>> print(results) {'accuracy': 0.5} ``` ## Limitations and bias This metric is limited to datasets with the same format as the [Mathematics Aptitude Test of Heuristics (MATH) dataset](https://huggingface.co/datasets/competition_math), and is meant to evaluate the performance of large language models at solving mathematical problems. N.B. The MATH dataset also assigns levels of difficulty to different problems, so disagregating model performance by difficulty level (similarly to what was done in the [original paper](https://arxiv.org/abs/2103.03874) can give a better indication of how a given model does on a given difficulty of math problem, compared to overall accuracy. ## Citation ```bibtex @article{hendrycksmath2021, title={Measuring Mathematical Problem Solving With the MATH Dataset}, author={Dan Hendrycks and Collin Burns and Saurav Kadavath and Akul Arora and Steven Basart and Eric Tang and Dawn Song and Jacob Steinhardt}, journal={arXiv preprint arXiv:2103.03874}, year={2021} } ``` ## Further References - [MATH dataset](https://huggingface.co/datasets/competition_math) - [MATH leaderboard](https://paperswithcode.com/sota/math-word-problem-solving-on-math) - [MATH paper](https://arxiv.org/abs/2103.03874)
datasets/metrics/competition_math/README.md/0
{ "file_path": "datasets/metrics/competition_math/README.md", "repo_id": "datasets", "token_count": 1135 }
66
# Copyright 2020 The HuggingFace Datasets Authors. # # 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. """Google BLEU (aka GLEU) metric.""" from typing import Dict, List from nltk.translate import gleu_score import datasets from datasets import MetricInfo _CITATION = """\ @misc{wu2016googles, title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation}, author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes and Jeffrey Dean}, year={2016}, eprint={1609.08144}, archivePrefix={arXiv}, primaryClass={cs.CL} } """ _DESCRIPTION = """\ The BLEU score has some undesirable properties when used for single sentences, as it was designed to be a corpus measure. We therefore use a slightly different score for our RL experiments which we call the 'GLEU score'. For the GLEU score, we record all sub-sequences of 1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then compute a recall, which is the ratio of the number of matching n-grams to the number of total n-grams in the target (ground truth) sequence, and a precision, which is the ratio of the number of matching n-grams to the number of total n-grams in the generated output sequence. Then GLEU score is simply the minimum of recall and precision. This GLEU score's range is always between 0 (no matches) and 1 (all match) and it is symmetrical when switching output and target. According to our experiments, GLEU score correlates quite well with the BLEU metric on a corpus level but does not have its drawbacks for our per sentence reward objective. """ _KWARGS_DESCRIPTION = """\ Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references. Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values. Args: predictions (list of str): list of translations to score. Each translation should be tokenized into a list of tokens. references (list of list of str): list of lists of references for each translation. Each reference should be tokenized into a list of tokens. min_len (int): The minimum order of n-gram this function should extract. Defaults to 1. max_len (int): The maximum order of n-gram this function should extract. Defaults to 4. Returns: 'google_bleu': google_bleu score Examples: Example 1: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric("google_bleu") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results["google_bleu"], 2)) 0.44 Example 2: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric("google_bleu") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references) >>> print(round(results["google_bleu"], 2)) 0.61 Example 3: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric("google_bleu") >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2) >>> print(round(results["google_bleu"], 2)) 0.53 Example 4: >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'always', ... 'disobeys', 'the', 'commands', 'of', 'the', 'cat'] >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which', ... 'guarantees', 'the', 'rubber', 'duck', 'forces', 'never', ... 'being', 'under', 'the', 'command', 'of', 'the', 'cat'] >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that', ... 'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never', ... 'heed', 'the', 'cat', 'commands'] >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the', ... 'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions', ... 'of', 'the', 'cat'] >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was', ... 'interested', 'in', 'world', 'history'] >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history', ... 'because', 'he', 'read', 'the', 'book'] >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]] >>> hypotheses = [hyp1, hyp2] >>> google_bleu = datasets.load_metric("google_bleu") >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6) >>> print(round(results["google_bleu"], 2)) 0.4 """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION) class GoogleBleu(datasets.Metric): def _info(self) -> MetricInfo: return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("string", id="token"), id="sequence"), "references": datasets.Sequence( datasets.Sequence(datasets.Value("string", id="token"), id="sequence"), id="references" ), } ), ) def _compute( self, predictions: List[List[List[str]]], references: List[List[str]], min_len: int = 1, max_len: int = 4, ) -> Dict[str, float]: return { "google_bleu": gleu_score.corpus_gleu( list_of_references=references, hypotheses=predictions, min_len=min_len, max_len=max_len ) }
datasets/metrics/google_bleu/google_bleu.py/0
{ "file_path": "datasets/metrics/google_bleu/google_bleu.py", "repo_id": "datasets", "token_count": 4259 }
67
# Copyright 2022 The HuggingFace Datasets Authors and the current dataset script contributor. # # 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. """MSE - Mean Squared Error Metric""" from sklearn.metrics import mean_squared_error import datasets _CITATION = """\ @article{scikit-learn, title={Scikit-learn: Machine Learning in {P}ython}, author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V. and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P. and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.}, journal={Journal of Machine Learning Research}, volume={12}, pages={2825--2830}, year={2011} } """ _DESCRIPTION = """\ Mean Squared Error(MSE) is the average of the square of difference between the predicted and actual values. """ _KWARGS_DESCRIPTION = """ Args: predictions: array-like of shape (n_samples,) or (n_samples, n_outputs) Estimated target values. references: array-like of shape (n_samples,) or (n_samples, n_outputs) Ground truth (correct) target values. sample_weight: array-like of shape (n_samples,), default=None Sample weights. multioutput: {"raw_values", "uniform_average"} or array-like of shape (n_outputs,), default="uniform_average" Defines aggregating of multiple output values. Array-like value defines weights used to average errors. "raw_values" : Returns a full set of errors in case of multioutput input. "uniform_average" : Errors of all outputs are averaged with uniform weight. squared : bool, default=True If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value. Returns: mse : mean squared error. Examples: >>> mse_metric = datasets.load_metric("mse") >>> predictions = [2.5, 0.0, 2, 8] >>> references = [3, -0.5, 2, 7] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {'mse': 0.375} >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False) >>> print(rmse_result) {'mse': 0.6123724356957945} If you're using multi-dimensional lists, then set the config as follows : >>> mse_metric = datasets.load_metric("mse", "multilist") >>> predictions = [[0.5, 1], [-1, 1], [7, -6]] >>> references = [[0, 2], [-1, 2], [8, -5]] >>> results = mse_metric.compute(predictions=predictions, references=references) >>> print(results) {'mse': 0.7083333333333334} >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput='raw_values') >>> print(results) # doctest: +NORMALIZE_WHITESPACE {'mse': array([0.41666667, 1. ])} """ @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION) class Mse(datasets.Metric): def _info(self): return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features(self._get_feature_types()), reference_urls=[ "https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html" ], ) def _get_feature_types(self): if self.config_name == "multilist": return { "predictions": datasets.Sequence(datasets.Value("float")), "references": datasets.Sequence(datasets.Value("float")), } else: return { "predictions": datasets.Value("float"), "references": datasets.Value("float"), } def _compute(self, predictions, references, sample_weight=None, multioutput="uniform_average", squared=True): mse = mean_squared_error( references, predictions, sample_weight=sample_weight, multioutput=multioutput, squared=squared ) return {"mse": mse}
datasets/metrics/mse/mse.py/0
{ "file_path": "datasets/metrics/mse/mse.py", "repo_id": "datasets", "token_count": 1715 }
68
# Copyright 2020 The HuggingFace Datasets Authors and the current dataset script contributor. # # 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. """SARI metric.""" from collections import Counter import sacrebleu import sacremoses from packaging import version import datasets _CITATION = """\ @inproceedings{xu-etal-2016-optimizing, title = {Optimizing Statistical Machine Translation for Text Simplification}, authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris}, journal = {Transactions of the Association for Computational Linguistics}, volume = {4}, year={2016}, url = {https://www.aclweb.org/anthology/Q16-1029}, pages = {401--415}, } """ _DESCRIPTION = """\ SARI is a metric used for evaluating automatic text simplification systems. The metric compares the predicted simplified sentences against the reference and the source sentences. It explicitly measures the goodness of words that are added, deleted and kept by the system. Sari = (F1_add + F1_keep + P_del) / 3 where F1_add: n-gram F1 score for add operation F1_keep: n-gram F1 score for keep operation P_del: n-gram precision score for delete operation n = 4, as in the original paper. This implementation is adapted from Tensorflow's tensor2tensor implementation [3]. It has two differences with the original GitHub [1] implementation: (1) Defines 0/0=1 instead of 0 to give higher scores for predictions that match a target exactly. (2) Fixes an alleged bug [2] in the keep score computation. [1] https://github.com/cocoxu/simplification/blob/master/SARI.py (commit 0210f15) [2] https://github.com/cocoxu/simplification/issues/6 [3] https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py """ _KWARGS_DESCRIPTION = """ Calculates sari score (between 0 and 100) given a list of source and predicted sentences, and a list of lists of reference sentences. Args: sources: list of source sentences where each sentence should be a string. predictions: list of predicted sentences where each sentence should be a string. references: list of lists of reference sentences where each sentence should be a string. Returns: sari: sari score Examples: >>> sources=["About 95 species are currently accepted ."] >>> predictions=["About 95 you now get in ."] >>> references=[["About 95 species are currently known .","About 95 species are now accepted .","95 species are now accepted ."]] >>> sari = datasets.load_metric("sari") >>> results = sari.compute(sources=sources, predictions=predictions, references=references) >>> print(results) {'sari': 26.953601953601954} """ def SARIngram(sgrams, cgrams, rgramslist, numref): rgramsall = [rgram for rgrams in rgramslist for rgram in rgrams] rgramcounter = Counter(rgramsall) sgramcounter = Counter(sgrams) sgramcounter_rep = Counter() for sgram, scount in sgramcounter.items(): sgramcounter_rep[sgram] = scount * numref cgramcounter = Counter(cgrams) cgramcounter_rep = Counter() for cgram, ccount in cgramcounter.items(): cgramcounter_rep[cgram] = ccount * numref # KEEP keepgramcounter_rep = sgramcounter_rep & cgramcounter_rep keepgramcountergood_rep = keepgramcounter_rep & rgramcounter keepgramcounterall_rep = sgramcounter_rep & rgramcounter keeptmpscore1 = 0 keeptmpscore2 = 0 for keepgram in keepgramcountergood_rep: keeptmpscore1 += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram] # Fix an alleged bug [2] in the keep score computation. # keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram] keeptmpscore2 += keepgramcountergood_rep[keepgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. keepscore_precision = 1 keepscore_recall = 1 if len(keepgramcounter_rep) > 0: keepscore_precision = keeptmpscore1 / len(keepgramcounter_rep) if len(keepgramcounterall_rep) > 0: # Fix an alleged bug [2] in the keep score computation. # keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep) keepscore_recall = keeptmpscore2 / sum(keepgramcounterall_rep.values()) keepscore = 0 if keepscore_precision > 0 or keepscore_recall > 0: keepscore = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall) # DELETION delgramcounter_rep = sgramcounter_rep - cgramcounter_rep delgramcountergood_rep = delgramcounter_rep - rgramcounter delgramcounterall_rep = sgramcounter_rep - rgramcounter deltmpscore1 = 0 deltmpscore2 = 0 for delgram in delgramcountergood_rep: deltmpscore1 += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram] deltmpscore2 += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram] # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. delscore_precision = 1 if len(delgramcounter_rep) > 0: delscore_precision = deltmpscore1 / len(delgramcounter_rep) # ADDITION addgramcounter = set(cgramcounter) - set(sgramcounter) addgramcountergood = set(addgramcounter) & set(rgramcounter) addgramcounterall = set(rgramcounter) - set(sgramcounter) addtmpscore = 0 for addgram in addgramcountergood: addtmpscore += 1 # Define 0/0=1 instead of 0 to give higher scores for predictions that match # a target exactly. addscore_precision = 1 addscore_recall = 1 if len(addgramcounter) > 0: addscore_precision = addtmpscore / len(addgramcounter) if len(addgramcounterall) > 0: addscore_recall = addtmpscore / len(addgramcounterall) addscore = 0 if addscore_precision > 0 or addscore_recall > 0: addscore = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall) return (keepscore, delscore_precision, addscore) def SARIsent(ssent, csent, rsents): numref = len(rsents) s1grams = ssent.split(" ") c1grams = csent.split(" ") s2grams = [] c2grams = [] s3grams = [] c3grams = [] s4grams = [] c4grams = [] r1gramslist = [] r2gramslist = [] r3gramslist = [] r4gramslist = [] for rsent in rsents: r1grams = rsent.split(" ") r2grams = [] r3grams = [] r4grams = [] r1gramslist.append(r1grams) for i in range(0, len(r1grams) - 1): if i < len(r1grams) - 1: r2gram = r1grams[i] + " " + r1grams[i + 1] r2grams.append(r2gram) if i < len(r1grams) - 2: r3gram = r1grams[i] + " " + r1grams[i + 1] + " " + r1grams[i + 2] r3grams.append(r3gram) if i < len(r1grams) - 3: r4gram = r1grams[i] + " " + r1grams[i + 1] + " " + r1grams[i + 2] + " " + r1grams[i + 3] r4grams.append(r4gram) r2gramslist.append(r2grams) r3gramslist.append(r3grams) r4gramslist.append(r4grams) for i in range(0, len(s1grams) - 1): if i < len(s1grams) - 1: s2gram = s1grams[i] + " " + s1grams[i + 1] s2grams.append(s2gram) if i < len(s1grams) - 2: s3gram = s1grams[i] + " " + s1grams[i + 1] + " " + s1grams[i + 2] s3grams.append(s3gram) if i < len(s1grams) - 3: s4gram = s1grams[i] + " " + s1grams[i + 1] + " " + s1grams[i + 2] + " " + s1grams[i + 3] s4grams.append(s4gram) for i in range(0, len(c1grams) - 1): if i < len(c1grams) - 1: c2gram = c1grams[i] + " " + c1grams[i + 1] c2grams.append(c2gram) if i < len(c1grams) - 2: c3gram = c1grams[i] + " " + c1grams[i + 1] + " " + c1grams[i + 2] c3grams.append(c3gram) if i < len(c1grams) - 3: c4gram = c1grams[i] + " " + c1grams[i + 1] + " " + c1grams[i + 2] + " " + c1grams[i + 3] c4grams.append(c4gram) (keep1score, del1score, add1score) = SARIngram(s1grams, c1grams, r1gramslist, numref) (keep2score, del2score, add2score) = SARIngram(s2grams, c2grams, r2gramslist, numref) (keep3score, del3score, add3score) = SARIngram(s3grams, c3grams, r3gramslist, numref) (keep4score, del4score, add4score) = SARIngram(s4grams, c4grams, r4gramslist, numref) avgkeepscore = sum([keep1score, keep2score, keep3score, keep4score]) / 4 avgdelscore = sum([del1score, del2score, del3score, del4score]) / 4 avgaddscore = sum([add1score, add2score, add3score, add4score]) / 4 finalscore = (avgkeepscore + avgdelscore + avgaddscore) / 3 return finalscore def normalize(sentence, lowercase: bool = True, tokenizer: str = "13a", return_str: bool = True): # Normalization is requried for the ASSET dataset (one of the primary # datasets in sentence simplification) to allow using space # to split the sentence. Even though Wiki-Auto and TURK datasets, # do not require normalization, we do it for consistency. # Code adapted from the EASSE library [1] written by the authors of the ASSET dataset. # [1] https://github.com/feralvam/easse/blob/580bba7e1378fc8289c663f864e0487188fe8067/easse/utils/preprocessing.py#L7 if lowercase: sentence = sentence.lower() if tokenizer in ["13a", "intl"]: if version.parse(sacrebleu.__version__).major >= 2: normalized_sent = sacrebleu.metrics.bleu._get_tokenizer(tokenizer)()(sentence) else: normalized_sent = sacrebleu.TOKENIZERS[tokenizer]()(sentence) elif tokenizer == "moses": normalized_sent = sacremoses.MosesTokenizer().tokenize(sentence, return_str=True, escape=False) elif tokenizer == "penn": normalized_sent = sacremoses.MosesTokenizer().penn_tokenize(sentence, return_str=True) else: normalized_sent = sentence if not return_str: normalized_sent = normalized_sent.split() return normalized_sent @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION) class Sari(datasets.Metric): def _info(self): return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { "sources": datasets.Value("string", id="sequence"), "predictions": datasets.Value("string", id="sequence"), "references": datasets.Sequence(datasets.Value("string", id="sequence"), id="references"), } ), codebase_urls=[ "https://github.com/cocoxu/simplification/blob/master/SARI.py", "https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py", ], reference_urls=["https://www.aclweb.org/anthology/Q16-1029.pdf"], ) def _compute(self, sources, predictions, references): if not (len(sources) == len(predictions) == len(references)): raise ValueError("Sources length must match predictions and references lengths.") sari_score = 0 for src, pred, refs in zip(sources, predictions, references): sari_score += SARIsent(normalize(src), normalize(pred), [normalize(sent) for sent in refs]) sari_score = sari_score / len(predictions) return {"sari": 100 * sari_score}
datasets/metrics/sari/sari.py/0
{ "file_path": "datasets/metrics/sari/sari.py", "repo_id": "datasets", "token_count": 4913 }
69
# Metric Card for WER ## Metric description Word error rate (WER) is a common metric of the performance of an automatic speech recognition (ASR) system. The general difficulty of measuring the performance of ASR systems lies in the fact that the recognized word sequence can have a different length from the reference word sequence (supposedly the correct one). The WER is derived from the [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance), working at the word level. This problem is solved by first aligning the recognized word sequence with the reference (spoken) word sequence using dynamic string alignment. Examination of this issue is seen through a theory called the power law that states the correlation between [perplexity](https://huggingface.co/metrics/perplexity) and word error rate (see [this article](https://www.cs.cmu.edu/~roni/papers/eval-metrics-bntuw-9802.pdf) for further information). Word error rate can then be computed as: `WER = (S + D + I) / N = (S + D + I) / (S + D + C)` where `S` is the number of substitutions, `D` is the number of deletions, `I` is the number of insertions, `C` is the number of correct words, `N` is the number of words in the reference (`N=S+D+C`). ## How to use The metric takes two inputs: references (a list of references for each speech input) and predictions (a list of transcriptions to score). ```python from datasets import load_metric wer = load_metric("wer") wer_score = wer.compute(predictions=predictions, references=references) ``` ## Output values This metric outputs a float representing the word error rate. ``` print(wer_score) 0.5 ``` This value indicates the average number of errors per reference word. The **lower** the value, the **better** the performance of the ASR system, with a WER of 0 being a perfect score. ### Values from popular papers This metric is highly dependent on the content and quality of the dataset, and therefore users can expect very different values for the same model but on different datasets. For example, datasets such as [LibriSpeech](https://huggingface.co/datasets/librispeech_asr) report a WER in the 1.8-3.3 range, whereas ASR models evaluated on [Timit](https://huggingface.co/datasets/timit_asr) report a WER in the 8.3-20.4 range. See the leaderboards for [LibriSpeech](https://paperswithcode.com/sota/speech-recognition-on-librispeech-test-clean) and [Timit](https://paperswithcode.com/sota/speech-recognition-on-timit) for the most recent values. ## Examples Perfect match between prediction and reference: ```python from datasets import load_metric wer = load_metric("wer") predictions = ["hello world", "good night moon"] references = ["hello world", "good night moon"] wer_score = wer.compute(predictions=predictions, references=references) print(wer_score) 0.0 ``` Partial match between prediction and reference: ```python from datasets import load_metric wer = load_metric("wer") predictions = ["this is the prediction", "there is an other sample"] references = ["this is the reference", "there is another one"] wer_score = wer.compute(predictions=predictions, references=references) print(wer_score) 0.5 ``` No match between prediction and reference: ```python from datasets import load_metric wer = load_metric("wer") predictions = ["hello world", "good night moon"] references = ["hi everyone", "have a great day"] wer_score = wer.compute(predictions=predictions, references=references) print(wer_score) 1.0 ``` ## Limitations and bias WER is a valuable tool for comparing different systems as well as for evaluating improvements within one system. This kind of measurement, however, provides no details on the nature of translation errors and further work is therefore required to identify the main source(s) of error and to focus any research effort. ## Citation ```bibtex @inproceedings{woodard1982, author = {Woodard, J.P. and Nelson, J.T., year = {1982}, journal = Ẅorkshop on standardisation for speech I/O technology, Naval Air Development Center, Warminster, PA}, title = {An information theoretic measure of speech recognition performance} } ``` ```bibtex @inproceedings{morris2004, author = {Morris, Andrew and Maier, Viktoria and Green, Phil}, year = {2004}, month = {01}, pages = {}, title = {From WER and RIL to MER and WIL: improved evaluation measures for connected speech recognition.} } ``` ## Further References - [Word Error Rate -- Wikipedia](https://en.wikipedia.org/wiki/Word_error_rate) - [Hugging Face Tasks -- Automatic Speech Recognition](https://huggingface.co/tasks/automatic-speech-recognition)
datasets/metrics/wer/README.md/0
{ "file_path": "datasets/metrics/wer/README.md", "repo_id": "datasets", "token_count": 1325 }
70
# Copyright 2020 The TensorFlow Datasets Authors. # # 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. # Lint as: python3 """Mock download manager interface.""" import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version logger = get_logger(__name__) class MockDownloadManager: dummy_file_name = "dummy_data" datasets_scripts_dir = "datasets" is_streaming = False def __init__( self, dataset_name: str, config: str, version: Union[Version, str], cache_dir: Optional[str] = None, use_local_dummy_data: bool = False, load_existing_dummy_data: bool = True, download_callbacks: Optional[List[Callable]] = None, ): self.downloaded_size = 0 self.dataset_name = dataset_name self.cache_dir = cache_dir self.use_local_dummy_data = use_local_dummy_data self.config = config # download_callbacks take a single url as input self.download_callbacks: List[Callable] = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root self.load_existing_dummy_data = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general self.version_name = str(version) # to be downloaded self._dummy_file = None self._bucket_url = None @property def dummy_file(self): if self._dummy_file is None: self._dummy_file = self.download_dummy_data() return self._dummy_file @property def dummy_data_folder(self): if self.config is not None: # structure is dummy / config_name / version_name return os.path.join("dummy", self.config.name, self.version_name) # structure is dummy / version_name return os.path.join("dummy", self.version_name) @property def dummy_zip_file(self): return os.path.join(self.dummy_data_folder, "dummy_data.zip") def download_dummy_data(self): path_to_dummy_data_dir = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) local_path = cached_path( path_to_dummy_data_dir, cache_dir=self.cache_dir, extract_compressed_file=True, force_extract=True ) return os.path.join(local_path, self.dummy_file_name) @property def local_path_to_dummy_data(self): return os.path.join(self.datasets_scripts_dir, self.dataset_name, self.dummy_zip_file) @property def github_path_to_dummy_data(self): if self._bucket_url is None: self._bucket_url = hf_github_url(self.dataset_name, self.dummy_zip_file.replace(os.sep, "/")) return self._bucket_url @property def manual_dir(self): # return full path if its a dir if os.path.isdir(self.dummy_file): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep, "/").split("/")[:-1]) # this function has to be in the manager under this name so that testing works def download_and_extract(self, data_url, *args): if self.load_existing_dummy_data: # dummy data is downloaded and tested dummy_file = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned dummy_file = self.dummy_file_name # special case when data_url is a dict if isinstance(data_url, dict): return self.create_dummy_data_dict(dummy_file, data_url) elif isinstance(data_url, (list, tuple)): return self.create_dummy_data_list(dummy_file, data_url) else: return self.create_dummy_data_single(dummy_file, data_url) # this function has to be in the manager under this name so that testing works def download(self, data_url, *args): return self.download_and_extract(data_url) # this function has to be in the manager under this name so that testing works def download_custom(self, data_url, custom_download): return self.download_and_extract(data_url) # this function has to be in the manager under this name so that testing works def extract(self, path, *args, **kwargs): return path # this function has to be in the manager under this name so that testing works def get_recorded_sizes_checksums(self): return {} def create_dummy_data_dict(self, path_to_dummy_data, data_url): dummy_data_dict = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(single_urls, list): for single_url in single_urls: download_callback(single_url) else: single_url = single_urls download_callback(single_url) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(single_urls, list): value = [os.path.join(path_to_dummy_data, urllib.parse.quote_plus(Path(x).name)) for x in single_urls] else: single_url = single_urls value = os.path.join(path_to_dummy_data, urllib.parse.quote_plus(Path(single_url).name)) dummy_data_dict[key] = value # make sure that values are unique if all(isinstance(i, str) for i in dummy_data_dict.values()) and len(set(dummy_data_dict.values())) < len( dummy_data_dict.values() ): # append key to value to make its name unique dummy_data_dict = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def create_dummy_data_list(self, path_to_dummy_data, data_url): dummy_data_list = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one is_tf_records = all(bool(re.findall("[0-9]{3,}-of-[0-9]{3,}", url)) for url in data_url) is_pubmed_records = all( url.startswith("https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed") for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): data_url = [data_url[0]] * len(data_url) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(single_url) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus value = os.path.join(path_to_dummy_data, urllib.parse.quote_plus(single_url.split("/")[-1])) dummy_data_list.append(value) return dummy_data_list def create_dummy_data_single(self, path_to_dummy_data, data_url): for download_callback in self.download_callbacks: download_callback(data_url) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus value = os.path.join(path_to_dummy_data, urllib.parse.quote_plus(data_url.split("/")[-1])) if os.path.exists(value) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def delete_extracted_files(self): pass def manage_extracted_files(self): pass def iter_archive(self, path): def _iter_archive_members(path): # this preserves the order of the members inside the ZIP archive dummy_parent_path = Path(self.dummy_file).parent relative_path = path.relative_to(dummy_parent_path) with ZipFile(self.local_path_to_dummy_data) as zip_file: members = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix()): yield dummy_parent_path.joinpath(member) path = Path(path) file_paths = _iter_archive_members(path) if self.use_local_dummy_data else path.rglob("*") for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith((".", "__")): yield file_path.relative_to(path).as_posix(), file_path.open("rb") def iter_files(self, paths): if not isinstance(paths, list): paths = [paths] for path in paths: if os.path.isfile(path): yield path else: for dirpath, dirnames, filenames in os.walk(path): if os.path.basename(dirpath).startswith((".", "__")): continue dirnames.sort() for filename in sorted(filenames): if filename.startswith((".", "__")): continue yield os.path.join(dirpath, filename)
datasets/src/datasets/download/mock_download_manager.py/0
{ "file_path": "datasets/src/datasets/download/mock_download_manager.py", "repo_id": "datasets", "token_count": 4438 }
71
# Copyright 2020 The HuggingFace Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys from collections.abc import Mapping from functools import partial from typing import TYPE_CHECKING, Optional import pyarrow as pa from .. import config from ..features import Features from ..features.features import decode_nested_example from ..utils.py_utils import no_op_if_value_is_null from .formatting import BaseArrowExtractor, TensorFormatter if TYPE_CHECKING: import polars as pl class PolarsArrowExtractor(BaseArrowExtractor["pl.DataFrame", "pl.Series", "pl.DataFrame"]): def extract_row(self, pa_table: pa.Table) -> "pl.DataFrame": if config.POLARS_AVAILABLE: if "polars" not in sys.modules: import polars else: polars = sys.modules["polars"] return polars.from_arrow(pa_table.slice(length=1)) else: raise ValueError("Polars needs to be installed to be able to return Polars dataframes.") def extract_column(self, pa_table: pa.Table) -> "pl.Series": if config.POLARS_AVAILABLE: if "polars" not in sys.modules: import polars else: polars = sys.modules["polars"] return polars.from_arrow(pa_table.select([0]))[pa_table.column_names[0]] else: raise ValueError("Polars needs to be installed to be able to return Polars dataframes.") def extract_batch(self, pa_table: pa.Table) -> "pl.DataFrame": if config.POLARS_AVAILABLE: if "polars" not in sys.modules: import polars else: polars = sys.modules["polars"] return polars.from_arrow(pa_table) else: raise ValueError("Polars needs to be installed to be able to return Polars dataframes.") class PolarsFeaturesDecoder: def __init__(self, features: Optional[Features]): self.features = features import polars as pl # noqa: F401 - import pl at initialization def decode_row(self, row: "pl.DataFrame") -> "pl.DataFrame": decode = ( { column_name: no_op_if_value_is_null(partial(decode_nested_example, feature)) for column_name, feature in self.features.items() if self.features._column_requires_decoding[column_name] } if self.features else {} ) if decode: row[list(decode.keys())] = row.map_rows(decode) return row def decode_column(self, column: "pl.Series", column_name: str) -> "pl.Series": decode = ( no_op_if_value_is_null(partial(decode_nested_example, self.features[column_name])) if self.features and column_name in self.features and self.features._column_requires_decoding[column_name] else None ) if decode: column = column.map_elements(decode) return column def decode_batch(self, batch: "pl.DataFrame") -> "pl.DataFrame": return self.decode_row(batch) class PolarsFormatter(TensorFormatter[Mapping, "pl.DataFrame", Mapping]): def __init__(self, features=None, **np_array_kwargs): super().__init__(features=features) self.np_array_kwargs = np_array_kwargs self.polars_arrow_extractor = PolarsArrowExtractor self.polars_features_decoder = PolarsFeaturesDecoder(features) import polars as pl # noqa: F401 - import pl at initialization def format_row(self, pa_table: pa.Table) -> "pl.DataFrame": row = self.polars_arrow_extractor().extract_row(pa_table) row = self.polars_features_decoder.decode_row(row) return row def format_column(self, pa_table: pa.Table) -> "pl.Series": column = self.polars_arrow_extractor().extract_column(pa_table) column = self.polars_features_decoder.decode_column(column, pa_table.column_names[0]) return column def format_batch(self, pa_table: pa.Table) -> "pl.DataFrame": row = self.polars_arrow_extractor().extract_batch(pa_table) row = self.polars_features_decoder.decode_batch(row) return row
datasets/src/datasets/formatting/polars_formatter.py/0
{ "file_path": "datasets/src/datasets/formatting/polars_formatter.py", "repo_id": "datasets", "token_count": 1910 }
72
# Copyright 2020 The HuggingFace Datasets Authors and the TensorFlow Datasets Authors. # # 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. # Lint as: python3 """Access datasets.""" import filecmp import glob import importlib import inspect import json import os import posixpath import shutil import signal import time import warnings from collections import Counter from contextlib import nullcontext from dataclasses import dataclass, field from pathlib import Path from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Type, Union import fsspec import requests import yaml from fsspec.core import url_to_fs from huggingface_hub import DatasetCard, DatasetCardData, HfApi, HfFileSystem from . import config from .arrow_dataset import Dataset from .builder import BuilderConfig, DatasetBuilder from .data_files import ( DEFAULT_PATTERNS_ALL, DataFilesDict, DataFilesList, DataFilesPatternsDict, DataFilesPatternsList, EmptyDatasetError, get_data_patterns, get_metadata_patterns, sanitize_patterns, ) from .dataset_dict import DatasetDict, IterableDatasetDict from .download.download_config import DownloadConfig from .download.download_manager import DownloadMode from .download.streaming_download_manager import StreamingDownloadManager, xbasename, xglob, xjoin from .exceptions import DataFilesNotFoundError, DatasetNotFoundError from .features import Features from .fingerprint import Hasher from .info import DatasetInfo, DatasetInfosDict from .iterable_dataset import IterableDataset from .metric import Metric from .naming import camelcase_to_snakecase, snakecase_to_camelcase from .packaged_modules import ( _EXTENSION_TO_MODULE, _MODULE_SUPPORTS_METADATA, _MODULE_TO_EXTENSIONS, _PACKAGED_DATASETS_MODULES, _hash_python_lines, ) from .splits import Split from .utils import _datasets_server from .utils.deprecation_utils import deprecated from .utils.file_utils import ( OfflineModeIsEnabled, _raise_if_offline_mode_is_enabled, cached_path, head_hf_s3, hf_github_url, init_hf_modules, is_relative_path, relative_to_absolute_path, url_or_path_join, ) from .utils.hub import hf_hub_url from .utils.info_utils import VerificationMode, is_small_dataset from .utils.logging import get_logger from .utils.metadata import MetadataConfigs from .utils.py_utils import get_imports, lock_importable_file from .utils.version import Version logger = get_logger(__name__) ALL_ALLOWED_EXTENSIONS = list(_EXTENSION_TO_MODULE.keys()) + [".zip"] def _raise_timeout_error(signum, frame): raise ValueError( "Loading this dataset requires you to execute custom code contained in the dataset repository on your local " "machine. Please set the option `trust_remote_code=True` to permit loading of this dataset." ) def resolve_trust_remote_code(trust_remote_code: Optional[bool], repo_id: str) -> bool: """ Copied and adapted from Transformers https://github.com/huggingface/transformers/blob/2098d343cc4b4b9d2aea84b3cf1eb5a1e610deff/src/transformers/dynamic_module_utils.py#L589 """ trust_remote_code = trust_remote_code if trust_remote_code is not None else config.HF_DATASETS_TRUST_REMOTE_CODE if trust_remote_code is None: if config.TIME_OUT_REMOTE_CODE > 0: try: signal.signal(signal.SIGALRM, _raise_timeout_error) signal.alarm(config.TIME_OUT_REMOTE_CODE) while trust_remote_code is None: answer = input( f"The repository for {repo_id} contains custom code which must be executed to correctly " f"load the dataset. You can inspect the repository content at https://hf.co/datasets/{repo_id}.\n" f"You can avoid this prompt in future by passing the argument `trust_remote_code=True`.\n\n" f"Do you wish to run the custom code? [y/N] " ) if answer.lower() in ["yes", "y", "1"]: trust_remote_code = True elif answer.lower() in ["no", "n", "0", ""]: trust_remote_code = False signal.alarm(0) except Exception: # OS which does not support signal.SIGALRM raise ValueError( f"The repository for {repo_id} contains custom code which must be executed to correctly " f"load the dataset. You can inspect the repository content at https://hf.co/datasets/{repo_id}.\n" f"Please pass the argument `trust_remote_code=True` to allow custom code to be run." ) else: # For the CI which might put the timeout at 0 _raise_timeout_error(None, None) return trust_remote_code def init_dynamic_modules( name: str = config.MODULE_NAME_FOR_DYNAMIC_MODULES, hf_modules_cache: Optional[Union[Path, str]] = None ): """ Create a module with name `name` in which you can add dynamic modules such as metrics or datasets. The module can be imported using its name. The module is created in the HF_MODULE_CACHE directory by default (~/.cache/huggingface/modules) but it can be overridden by specifying a path to another directory in `hf_modules_cache`. """ hf_modules_cache = init_hf_modules(hf_modules_cache) dynamic_modules_path = os.path.join(hf_modules_cache, name) os.makedirs(dynamic_modules_path, exist_ok=True) if not os.path.exists(os.path.join(dynamic_modules_path, "__init__.py")): with open(os.path.join(dynamic_modules_path, "__init__.py"), "w"): pass return dynamic_modules_path def import_main_class(module_path, dataset=True) -> Optional[Union[Type[DatasetBuilder], Type[Metric]]]: """Import a module at module_path and return its main class: - a DatasetBuilder if dataset is True - a Metric if dataset is False """ module = importlib.import_module(module_path) if dataset: main_cls_type = DatasetBuilder else: main_cls_type = Metric # Find the main class in our imported module module_main_cls = None for name, obj in module.__dict__.items(): if inspect.isclass(obj) and issubclass(obj, main_cls_type): if inspect.isabstract(obj): continue module_main_cls = obj obj_module = inspect.getmodule(obj) if obj_module is not None and module == obj_module: break return module_main_cls class _InitializeConfiguredDatasetBuilder: """ From https://stackoverflow.com/questions/4647566/pickle-a-dynamically-parameterized-sub-class See also ConfiguredDatasetBuilder.__reduce__ When called with the param value as the only argument, returns an un-initialized instance of the parameterized class. Subsequent __setstate__ will be called by pickle. """ def __call__(self, builder_cls, metadata_configs, default_config_name, name): # make a simple object which has no complex __init__ (this one will do) obj = _InitializeConfiguredDatasetBuilder() obj.__class__ = configure_builder_class( builder_cls, metadata_configs, default_config_name=default_config_name, dataset_name=name ) return obj def configure_builder_class( builder_cls: Type[DatasetBuilder], builder_configs: List[BuilderConfig], default_config_name: Optional[str], dataset_name: str, ) -> Type[DatasetBuilder]: """ Dynamically create a builder class with custom builder configs parsed from README.md file, i.e. set BUILDER_CONFIGS class variable of a builder class to custom configs list. """ class ConfiguredDatasetBuilder(builder_cls): BUILDER_CONFIGS = builder_configs DEFAULT_CONFIG_NAME = default_config_name __module__ = builder_cls.__module__ # so that the actual packaged builder can be imported def __reduce__(self): # to make dynamically created class pickable, see _InitializeParameterizedDatasetBuilder parent_builder_cls = self.__class__.__mro__[1] return ( _InitializeConfiguredDatasetBuilder(), ( parent_builder_cls, self.BUILDER_CONFIGS, self.DEFAULT_CONFIG_NAME, self.dataset_name, ), self.__dict__.copy(), ) ConfiguredDatasetBuilder.__name__ = ( f"{builder_cls.__name__.lower().capitalize()}{snakecase_to_camelcase(dataset_name)}" ) ConfiguredDatasetBuilder.__qualname__ = ( f"{builder_cls.__name__.lower().capitalize()}{snakecase_to_camelcase(dataset_name)}" ) return ConfiguredDatasetBuilder def get_dataset_builder_class( dataset_module: "DatasetModule", dataset_name: Optional[str] = None ) -> Type[DatasetBuilder]: with lock_importable_file( dataset_module.importable_file_path ) if dataset_module.importable_file_path else nullcontext(): builder_cls = import_main_class(dataset_module.module_path) if dataset_module.builder_configs_parameters.builder_configs: dataset_name = dataset_name or dataset_module.builder_kwargs.get("dataset_name") if dataset_name is None: raise ValueError("dataset_name should be specified but got None") builder_cls = configure_builder_class( builder_cls, builder_configs=dataset_module.builder_configs_parameters.builder_configs, default_config_name=dataset_module.builder_configs_parameters.default_config_name, dataset_name=dataset_name, ) return builder_cls def files_to_hash(file_paths: List[str]) -> str: """ Convert a list of scripts or text files provided in file_paths into a hashed filename in a repeatable way. """ # List all python files in directories if directories are supplied as part of external imports to_use_files: List[Union[Path, str]] = [] for file_path in file_paths: if os.path.isdir(file_path): to_use_files.extend(list(Path(file_path).rglob("*.[pP][yY]"))) else: to_use_files.append(file_path) # Get the code from all these files lines = [] for file_path in to_use_files: with open(file_path, encoding="utf-8") as f: lines.extend(f.readlines()) return _hash_python_lines(lines) def increase_load_count(name: str, resource_type: str): """Update the download count of a dataset or metric.""" if not config.HF_DATASETS_OFFLINE and config.HF_UPDATE_DOWNLOAD_COUNTS: try: head_hf_s3(name, filename=name + ".py", dataset=(resource_type == "dataset")) except Exception: pass def _download_additional_modules( name: str, base_path: str, imports: Tuple[str, str, str, str], download_config: Optional[DownloadConfig] ) -> List[Tuple[str, str]]: """ Download additional module for a module <name>.py at URL (or local path) <base_path>/<name>.py The imports must have been parsed first using ``get_imports``. If some modules need to be installed with pip, an error is raised showing how to install them. This function return the list of downloaded modules as tuples (import_name, module_file_path). The downloaded modules can then be moved into an importable directory with ``_copy_script_and_other_resources_in_importable_dir``. """ local_imports = [] library_imports = [] download_config = download_config.copy() if download_config.download_desc is None: download_config.download_desc = "Downloading extra modules" for import_type, import_name, import_path, sub_directory in imports: if import_type == "library": library_imports.append((import_name, import_path)) # Import from a library continue if import_name == name: raise ValueError( f"Error in the {name} script, importing relative {import_name} module " f"but {import_name} is the name of the script. " f"Please change relative import {import_name} to another name and add a '# From: URL_OR_PATH' " f"comment pointing to the original relative import file path." ) if import_type == "internal": url_or_filename = url_or_path_join(base_path, import_path + ".py") elif import_type == "external": url_or_filename = import_path else: raise ValueError("Wrong import_type") local_import_path = cached_path( url_or_filename, download_config=download_config, ) if sub_directory is not None: local_import_path = os.path.join(local_import_path, sub_directory) local_imports.append((import_name, local_import_path)) # Check library imports needs_to_be_installed = {} for library_import_name, library_import_path in library_imports: try: lib = importlib.import_module(library_import_name) # noqa F841 except ImportError: if library_import_name not in needs_to_be_installed or library_import_path != library_import_name: needs_to_be_installed[library_import_name] = library_import_path if needs_to_be_installed: _dependencies_str = "dependencies" if len(needs_to_be_installed) > 1 else "dependency" _them_str = "them" if len(needs_to_be_installed) > 1 else "it" if "sklearn" in needs_to_be_installed.keys(): needs_to_be_installed["sklearn"] = "scikit-learn" if "Bio" in needs_to_be_installed.keys(): needs_to_be_installed["Bio"] = "biopython" raise ImportError( f"To be able to use {name}, you need to install the following {_dependencies_str}: " f"{', '.join(needs_to_be_installed)}.\nPlease install {_them_str} using 'pip install " f"{' '.join(needs_to_be_installed.values())}' for instance." ) return local_imports def _copy_script_and_other_resources_in_importable_dir( name: str, importable_directory_path: str, subdirectory_name: str, original_local_path: str, local_imports: List[Tuple[str, str]], additional_files: List[Tuple[str, str]], download_mode: Optional[Union[DownloadMode, str]], ) -> str: """Copy a script and its required imports to an importable directory Args: name (str): name of the resource to load importable_directory_path (str): path to the loadable folder in the dynamic modules directory subdirectory_name (str): name of the subdirectory in importable_directory_path in which to place the script original_local_path (str): local path to the resource script local_imports (List[Tuple[str, str]]): list of (destination_filename, import_file_to_copy) additional_files (List[Tuple[str, str]]): list of (destination_filename, additional_file_to_copy) download_mode (Optional[Union[DownloadMode, str]]): download mode Return: importable_file: path to an importable module with importlib.import_module """ # Define a directory with a unique name in our dataset or metric folder # path is: ./datasets|metrics/dataset|metric_name/hash_from_code/script.py # we use a hash as subdirectory_name to be able to have multiple versions of a dataset/metric processing file together importable_subdirectory = os.path.join(importable_directory_path, subdirectory_name) importable_file = os.path.join(importable_subdirectory, name + ".py") # Prevent parallel disk operations with lock_importable_file(importable_file): # Create main dataset/metrics folder if needed if download_mode == DownloadMode.FORCE_REDOWNLOAD and os.path.exists(importable_directory_path): shutil.rmtree(importable_directory_path) os.makedirs(importable_directory_path, exist_ok=True) # add an __init__ file to the main dataset folder if needed init_file_path = os.path.join(importable_directory_path, "__init__.py") if not os.path.exists(init_file_path): with open(init_file_path, "w"): pass # Create hash dataset folder if needed os.makedirs(importable_subdirectory, exist_ok=True) # add an __init__ file to the hash dataset folder if needed init_file_path = os.path.join(importable_subdirectory, "__init__.py") if not os.path.exists(init_file_path): with open(init_file_path, "w"): pass # Copy dataset.py file in hash folder if needed if not os.path.exists(importable_file): shutil.copyfile(original_local_path, importable_file) # Record metadata associating original dataset path with local unique folder # Use os.path.splitext to split extension from importable_local_file meta_path = os.path.splitext(importable_file)[0] + ".json" if not os.path.exists(meta_path): meta = {"original file path": original_local_path, "local file path": importable_file} # the filename is *.py in our case, so better rename to filename.json instead of filename.py.json with open(meta_path, "w", encoding="utf-8") as meta_file: json.dump(meta, meta_file) # Copy all the additional imports for import_name, import_path in local_imports: if os.path.isfile(import_path): full_path_local_import = os.path.join(importable_subdirectory, import_name + ".py") if not os.path.exists(full_path_local_import): shutil.copyfile(import_path, full_path_local_import) elif os.path.isdir(import_path): full_path_local_import = os.path.join(importable_subdirectory, import_name) if not os.path.exists(full_path_local_import): shutil.copytree(import_path, full_path_local_import) else: raise ImportError(f"Error with local import at {import_path}") # Copy additional files like dataset_infos.json file if needed for file_name, original_path in additional_files: destination_additional_path = os.path.join(importable_subdirectory, file_name) if not os.path.exists(destination_additional_path) or not filecmp.cmp( original_path, destination_additional_path ): shutil.copyfile(original_path, destination_additional_path) return importable_file def _get_importable_file_path( dynamic_modules_path: str, module_namespace: str, subdirectory_name: str, name: str, ) -> str: importable_directory_path = os.path.join(dynamic_modules_path, module_namespace, name.replace("/", "--")) return os.path.join(importable_directory_path, subdirectory_name, name.split("/")[-1] + ".py") def _create_importable_file( local_path: str, local_imports: List[Tuple[str, str]], additional_files: List[Tuple[str, str]], dynamic_modules_path: str, module_namespace: str, subdirectory_name: str, name: str, download_mode: DownloadMode, ) -> None: importable_directory_path = os.path.join(dynamic_modules_path, module_namespace, name.replace("/", "--")) Path(importable_directory_path).mkdir(parents=True, exist_ok=True) (Path(importable_directory_path).parent / "__init__.py").touch(exist_ok=True) importable_local_file = _copy_script_and_other_resources_in_importable_dir( name=name.split("/")[-1], importable_directory_path=importable_directory_path, subdirectory_name=subdirectory_name, original_local_path=local_path, local_imports=local_imports, additional_files=additional_files, download_mode=download_mode, ) logger.debug(f"Created importable dataset file at {importable_local_file}") def _load_importable_file( dynamic_modules_path: str, module_namespace: str, subdirectory_name: str, name: str, ) -> Tuple[str, str]: module_path = ".".join( [ os.path.basename(dynamic_modules_path), module_namespace, name.replace("/", "--"), subdirectory_name, name.split("/")[-1], ] ) return module_path, subdirectory_name def infer_module_for_data_files_list( data_files_list: DataFilesList, download_config: Optional[DownloadConfig] = None ) -> Tuple[Optional[str], dict]: """Infer module (and builder kwargs) from list of data files. It picks the module based on the most common file extension. In case of a draw ".parquet" is the favorite, and then alphabetical order. Args: data_files_list (DataFilesList): List of data files. download_config (bool or str, optional): mainly use use_auth_token or storage_options to support different platforms and auth types. Returns: tuple[str, dict[str, Any]]: Tuple with - inferred module name - dict of builder kwargs """ extensions_counter = Counter( ("." + suffix.lower(), xbasename(filepath) in ("metadata.jsonl", "metadata.csv")) for filepath in data_files_list[: config.DATA_FILES_MAX_NUMBER_FOR_MODULE_INFERENCE] for suffix in xbasename(filepath).split(".")[1:] ) if extensions_counter: def sort_key(ext_count: Tuple[Tuple[str, bool], int]) -> Tuple[int, bool]: """Sort by count and set ".parquet" as the favorite in case of a draw, and ignore metadata files""" (ext, is_metadata), count = ext_count return (not is_metadata, count, ext == ".parquet", ext) for (ext, _), _ in sorted(extensions_counter.items(), key=sort_key, reverse=True): if ext in _EXTENSION_TO_MODULE: return _EXTENSION_TO_MODULE[ext] elif ext == ".zip": return infer_module_for_data_files_list_in_archives(data_files_list, download_config=download_config) return None, {} def infer_module_for_data_files_list_in_archives( data_files_list: DataFilesList, download_config: Optional[DownloadConfig] = None ) -> Tuple[Optional[str], dict]: """Infer module (and builder kwargs) from list of archive data files. Args: data_files_list (DataFilesList): List of data files. download_config (bool or str, optional): mainly use use_auth_token or storage_options to support different platforms and auth types. Returns: tuple[str, dict[str, Any]]: Tuple with - inferred module name - dict of builder kwargs """ archived_files = [] archive_files_counter = 0 for filepath in data_files_list: if str(filepath).endswith(".zip"): archive_files_counter += 1 if archive_files_counter > config.GLOBBED_DATA_FILES_MAX_NUMBER_FOR_MODULE_INFERENCE: break extracted = xjoin(StreamingDownloadManager().extract(filepath), "**") archived_files += [ f.split("::")[0] for f in xglob(extracted, recursive=True, download_config=download_config)[ : config.ARCHIVED_DATA_FILES_MAX_NUMBER_FOR_MODULE_INFERENCE ] ] extensions_counter = Counter( "." + suffix.lower() for filepath in archived_files for suffix in xbasename(filepath).split(".")[1:] ) if extensions_counter: most_common = extensions_counter.most_common(1)[0][0] if most_common in _EXTENSION_TO_MODULE: return _EXTENSION_TO_MODULE[most_common] return None, {} def infer_module_for_data_files( data_files: DataFilesDict, path: Optional[str] = None, download_config: Optional[DownloadConfig] = None ) -> Tuple[Optional[str], Dict[str, Any]]: """Infer module (and builder kwargs) from data files. Raise if module names for different splits don't match. Args: data_files ([`DataFilesDict`]): Dict of list of data files. path (str, *optional*): Dataset name or path. download_config ([`DownloadConfig`], *optional*): Specific download configuration parameters to authenticate on the Hugging Face Hub for private remote files. Returns: tuple[str, dict[str, Any]]: Tuple with - inferred module name - builder kwargs """ split_modules = { split: infer_module_for_data_files_list(data_files_list, download_config=download_config) for split, data_files_list in data_files.items() } module_name, default_builder_kwargs = next(iter(split_modules.values())) if any((module_name, default_builder_kwargs) != split_module for split_module in split_modules.values()): raise ValueError(f"Couldn't infer the same data file format for all splits. Got {split_modules}") if not module_name: raise DataFilesNotFoundError("No (supported) data files found" + (f" in {path}" if path else "")) return module_name, default_builder_kwargs def create_builder_configs_from_metadata_configs( module_path: str, metadata_configs: MetadataConfigs, supports_metadata: bool, base_path: Optional[str] = None, default_builder_kwargs: Dict[str, Any] = None, download_config: Optional[DownloadConfig] = None, ) -> Tuple[List[BuilderConfig], str]: builder_cls = import_main_class(module_path) builder_config_cls = builder_cls.BUILDER_CONFIG_CLASS default_config_name = metadata_configs.get_default_config_name() builder_configs = [] default_builder_kwargs = {} if default_builder_kwargs is None else default_builder_kwargs base_path = base_path if base_path is not None else "" for config_name, config_params in metadata_configs.items(): config_data_files = config_params.get("data_files") config_data_dir = config_params.get("data_dir") config_base_path = xjoin(base_path, config_data_dir) if config_data_dir else base_path try: config_patterns = ( sanitize_patterns(config_data_files) if config_data_files is not None else get_data_patterns(config_base_path, download_config=download_config) ) config_data_files_dict = DataFilesPatternsDict.from_patterns( config_patterns, allowed_extensions=ALL_ALLOWED_EXTENSIONS, ) except EmptyDatasetError as e: raise EmptyDatasetError( f"Dataset at '{base_path}' doesn't contain data files matching the patterns for config '{config_name}'," f" check `data_files` and `data_fir` parameters in the `configs` YAML field in README.md. " ) from e if config_data_files is None and supports_metadata and config_patterns != DEFAULT_PATTERNS_ALL: try: config_metadata_patterns = get_metadata_patterns(base_path, download_config=download_config) except FileNotFoundError: config_metadata_patterns = None if config_metadata_patterns is not None: config_metadata_data_files_list = DataFilesPatternsList.from_patterns(config_metadata_patterns) config_data_files_dict = DataFilesPatternsDict( { split: data_files_list + config_metadata_data_files_list for split, data_files_list in config_data_files_dict.items() } ) ignored_params = [ param for param in config_params if not hasattr(builder_config_cls, param) and param != "default" ] if ignored_params: logger.warning( f"Some datasets params were ignored: {ignored_params}. " "Make sure to use only valid params for the dataset builder and to have " "a up-to-date version of the `datasets` library." ) builder_configs.append( builder_config_cls( name=config_name, data_files=config_data_files_dict, data_dir=config_data_dir, **{ param: value for param, value in {**default_builder_kwargs, **config_params}.items() if hasattr(builder_config_cls, param) and param not in ("default", "data_files", "data_dir") }, ) ) return builder_configs, default_config_name @dataclass class BuilderConfigsParameters: """Dataclass containing objects related to creation of builder configurations from yaml's metadata content. Attributes: metadata_configs (`MetadataConfigs`, *optional*): Configs parsed from yaml's metadata. builder_configs (`list[BuilderConfig]`, *optional*): List of BuilderConfig objects created from metadata_configs above. default_config_name (`str`): Name of default config taken from yaml's metadata. """ metadata_configs: Optional[MetadataConfigs] = None builder_configs: Optional[List[BuilderConfig]] = None default_config_name: Optional[str] = None @dataclass class DatasetModule: module_path: str hash: str builder_kwargs: dict builder_configs_parameters: BuilderConfigsParameters = field(default_factory=BuilderConfigsParameters) dataset_infos: Optional[DatasetInfosDict] = None importable_file_path: Optional[str] = None @dataclass class MetricModule: module_path: str hash: str class _DatasetModuleFactory: def get_module(self) -> DatasetModule: raise NotImplementedError class _MetricModuleFactory: def get_module(self) -> MetricModule: raise NotImplementedError class GithubMetricModuleFactory(_MetricModuleFactory): """Get the module of a metric. The metric script is downloaded from GitHub. <Deprecated version="2.5.0"> Use the new library 🤗 Evaluate instead: https://huggingface.co/docs/evaluate </Deprecated> """ @deprecated("Use the new library 🤗 Evaluate instead: https://huggingface.co/docs/evaluate") def __init__( self, name: str, revision: Optional[Union[str, Version]] = None, download_config: Optional[DownloadConfig] = None, download_mode: Optional[Union[DownloadMode, str]] = None, dynamic_modules_path: Optional[str] = None, trust_remote_code: Optional[str] = None, ): self.name = name self.revision = revision self.download_config = download_config.copy() if download_config else DownloadConfig() if self.download_config.max_retries < 3: self.download_config.max_retries = 3 self.download_mode = download_mode self.dynamic_modules_path = dynamic_modules_path self.trust_remote_code = trust_remote_code assert self.name.count("/") == 0 increase_load_count(name, resource_type="metric") def download_loading_script(self, revision: Optional[str]) -> str: file_path = hf_github_url(path=self.name, name=self.name + ".py", revision=revision, dataset=False) download_config = self.download_config.copy() if download_config.download_desc is None: download_config.download_desc = "Downloading builder script" return cached_path(file_path, download_config=download_config) def get_module(self) -> MetricModule: if config.HF_DATASETS_TRUST_REMOTE_CODE and self.trust_remote_code is None: _loading_script_url = hf_github_url( path=self.name, name=self.name + ".py", revision=self.revision, dataset=False ) warnings.warn( f"The repository for {self.name} contains custom code which must be executed to correctly " f"load the metric. You can inspect the repository content at {_loading_script_url}\n" f"You can avoid this message in future by passing the argument `trust_remote_code=True`.\n" f"Passing `trust_remote_code=True` will be mandatory to load this metric from the next major release of `datasets`.", FutureWarning, ) # get script and other files revision = self.revision try: local_path = self.download_loading_script(revision) revision = self.revision except FileNotFoundError: if revision is not None: raise else: revision = "main" local_path = self.download_loading_script(revision) logger.warning( f"Couldn't find a directory or a metric named '{self.name}' in this version. " f"It was picked from the main branch on github instead." ) imports = get_imports(local_path) local_imports = _download_additional_modules( name=self.name, base_path=hf_github_url(path=self.name, name="", revision=revision, dataset=False), imports=imports, download_config=self.download_config, ) # copy the script and the files in an importable directory dynamic_modules_path = self.dynamic_modules_path if self.dynamic_modules_path else init_dynamic_modules() hash = files_to_hash([local_path] + [loc[1] for loc in local_imports]) importable_file_path = _get_importable_file_path( dynamic_modules_path=dynamic_modules_path, module_namespace="metrics", subdirectory_name=hash, name=self.name, ) if not os.path.exists(importable_file_path): trust_remote_code = resolve_trust_remote_code(self.trust_remote_code, self.name) if trust_remote_code: _create_importable_file( local_path=local_path, local_imports=local_imports, additional_files=[], dynamic_modules_path=dynamic_modules_path, module_namespace="metrics", subdirectory_name=hash, name=self.name, download_mode=self.download_mode, ) else: raise ValueError( f"Loading {self.name} requires you to execute the dataset script in that" " repo on your local machine. Make sure you have read the code there to avoid malicious use, then" " set the option `trust_remote_code=True` to remove this error." ) module_path, hash = _load_importable_file( dynamic_modules_path=dynamic_modules_path, module_namespace="metrics", subdirectory_name=hash, name=self.name, ) # make the new module to be noticed by the import system importlib.invalidate_caches() return MetricModule(module_path, hash) class LocalMetricModuleFactory(_MetricModuleFactory): """Get the module of a local metric. The metric script is loaded from a local script. <Deprecated version="2.5.0"> Use the new library 🤗 Evaluate instead: https://huggingface.co/docs/evaluate </Deprecated> """ @deprecated("Use the new library 🤗 Evaluate instead: https://huggingface.co/docs/evaluate") def __init__( self, path: str, download_config: Optional[DownloadConfig] = None, download_mode: Optional[Union[DownloadMode, str]] = None, dynamic_modules_path: Optional[str] = None, trust_remote_code: Optional[str] = None, ): self.path = path self.name = Path(path).stem self.download_config = download_config or DownloadConfig() self.download_mode = download_mode self.dynamic_modules_path = dynamic_modules_path self.trust_remote_code = trust_remote_code def get_module(self) -> MetricModule: if config.HF_DATASETS_TRUST_REMOTE_CODE and self.trust_remote_code is None: warnings.warn( f"The repository for {self.name} contains custom code which must be executed to correctly " f"load the metric. You can inspect the repository content at {self.path}\n" f"You can avoid this message in future by passing the argument `trust_remote_code=True`.\n" f"Passing `trust_remote_code=True` will be mandatory to load this metric from the next major release of `datasets`.", FutureWarning, ) # get script and other files imports = get_imports(self.path) local_imports = _download_additional_modules( name=self.name, base_path=str(Path(self.path).parent), imports=imports, download_config=self.download_config, ) # copy the script and the files in an importable directory dynamic_modules_path = self.dynamic_modules_path if self.dynamic_modules_path else init_dynamic_modules() hash = files_to_hash([self.path] + [loc[1] for loc in local_imports]) importable_file_path = _get_importable_file_path( dynamic_modules_path=dynamic_modules_path, module_namespace="metrics", subdirectory_name=hash, name=self.name, ) if not os.path.exists(importable_file_path): trust_remote_code = resolve_trust_remote_code(self.trust_remote_code, self.name) if trust_remote_code: _create_importable_file( local_path=self.path, local_imports=local_imports, additional_files=[], dynamic_modules_path=dynamic_modules_path, module_namespace="metrics", subdirectory_name=hash, name=self.name, download_mode=self.download_mode, ) else: raise ValueError( f"Loading {self.name} requires you to execute the dataset script in that" " repo on your local machine. Make sure you have read the code there to avoid malicious use, then" " set the option `trust_remote_code=True` to remove this error." ) module_path, hash = _load_importable_file( dynamic_modules_path=dynamic_modules_path, module_namespace="metrics", subdirectory_name=hash, name=self.name, ) # make the new module to be noticed by the import system importlib.invalidate_caches() return MetricModule(module_path, hash) class LocalDatasetModuleFactoryWithScript(_DatasetModuleFactory): """Get the module of a local dataset. The dataset script is loaded from a local script.""" def __init__( self, path: str, download_config: Optional[DownloadConfig] = None, download_mode: Optional[Union[DownloadMode, str]] = None, dynamic_modules_path: Optional[str] = None, trust_remote_code: Optional[bool] = None, ): self.path = path self.name = Path(path).stem self.download_config = download_config or DownloadConfig() self.download_mode = download_mode self.dynamic_modules_path = dynamic_modules_path self.trust_remote_code = trust_remote_code def get_module(self) -> DatasetModule: if config.HF_DATASETS_TRUST_REMOTE_CODE and self.trust_remote_code is None: warnings.warn( f"The repository for {self.name} contains custom code which must be executed to correctly " f"load the dataset. You can inspect the repository content at {self.path}\n" f"You can avoid this message in future by passing the argument `trust_remote_code=True`.\n" f"Passing `trust_remote_code=True` will be mandatory to load this dataset from the next major release of `datasets`.", FutureWarning, ) # get script and other files dataset_infos_path = Path(self.path).parent / config.DATASETDICT_INFOS_FILENAME dataset_readme_path = Path(self.path).parent / config.REPOCARD_FILENAME imports = get_imports(self.path) local_imports = _download_additional_modules( name=self.name, base_path=str(Path(self.path).parent), imports=imports, download_config=self.download_config, ) additional_files = [] if dataset_infos_path.is_file(): additional_files.append((config.DATASETDICT_INFOS_FILENAME, str(dataset_infos_path))) if dataset_readme_path.is_file(): additional_files.append((config.REPOCARD_FILENAME, dataset_readme_path)) # copy the script and the files in an importable directory dynamic_modules_path = self.dynamic_modules_path if self.dynamic_modules_path else init_dynamic_modules() hash = files_to_hash([self.path] + [loc[1] for loc in local_imports]) importable_file_path = _get_importable_file_path( dynamic_modules_path=dynamic_modules_path, module_namespace="datasets", subdirectory_name=hash, name=self.name, ) if not os.path.exists(importable_file_path): trust_remote_code = resolve_trust_remote_code(self.trust_remote_code, self.name) if trust_remote_code: _create_importable_file( local_path=self.path, local_imports=local_imports, additional_files=additional_files, dynamic_modules_path=dynamic_modules_path, module_namespace="datasets", subdirectory_name=hash, name=self.name, download_mode=self.download_mode, ) else: raise ValueError( f"Loading {self.name} requires you to execute the dataset script in that" " repo on your local machine. Make sure you have read the code there to avoid malicious use, then" " set the option `trust_remote_code=True` to remove this error." ) module_path, hash = _load_importable_file( dynamic_modules_path=dynamic_modules_path, module_namespace="datasets", subdirectory_name=hash, name=self.name, ) # make the new module to be noticed by the import system importlib.invalidate_caches() builder_kwargs = {"base_path": str(Path(self.path).parent)} return DatasetModule(module_path, hash, builder_kwargs, importable_file_path=importable_file_path) class LocalDatasetModuleFactoryWithoutScript(_DatasetModuleFactory): """Get the module of a dataset loaded from the user's data files. The dataset builder module to use is inferred from the data files extensions.""" def __init__( self, path: str, data_dir: Optional[str] = None, data_files: Optional[Union[str, List, Dict]] = None, download_mode: Optional[Union[DownloadMode, str]] = None, ): if data_dir and os.path.isabs(data_dir): raise ValueError(f"`data_dir` must be relative to a dataset directory's root: {path}") self.path = Path(path).as_posix() self.name = Path(path).stem self.data_files = data_files self.data_dir = data_dir self.download_mode = download_mode def get_module(self) -> DatasetModule: readme_path = os.path.join(self.path, config.REPOCARD_FILENAME) standalone_yaml_path = os.path.join(self.path, config.REPOYAML_FILENAME) dataset_card_data = DatasetCard.load(readme_path).data if os.path.isfile(readme_path) else DatasetCardData() if os.path.exists(standalone_yaml_path): with open(standalone_yaml_path, "r", encoding="utf-8") as f: standalone_yaml_data = yaml.safe_load(f.read()) if standalone_yaml_data: _dataset_card_data_dict = dataset_card_data.to_dict() _dataset_card_data_dict.update(standalone_yaml_data) dataset_card_data = DatasetCardData(**_dataset_card_data_dict) metadata_configs = MetadataConfigs.from_dataset_card_data(dataset_card_data) dataset_infos = DatasetInfosDict.from_dataset_card_data(dataset_card_data) # we need a set of data files to find which dataset builder to use # because we need to infer module name by files extensions base_path = Path(self.path, self.data_dir or "").expanduser().resolve().as_posix() if self.data_files is not None: patterns = sanitize_patterns(self.data_files) elif metadata_configs and not self.data_dir and "data_files" in next(iter(metadata_configs.values())): patterns = sanitize_patterns(next(iter(metadata_configs.values()))["data_files"]) else: patterns = get_data_patterns(base_path) data_files = DataFilesDict.from_patterns( patterns, base_path=base_path, allowed_extensions=ALL_ALLOWED_EXTENSIONS, ) module_name, default_builder_kwargs = infer_module_for_data_files( data_files=data_files, path=self.path, ) data_files = data_files.filter_extensions(_MODULE_TO_EXTENSIONS[module_name]) # Collect metadata files if the module supports them supports_metadata = module_name in _MODULE_SUPPORTS_METADATA if self.data_files is None and supports_metadata: try: metadata_patterns = get_metadata_patterns(base_path) except FileNotFoundError: metadata_patterns = None if metadata_patterns is not None: metadata_data_files_list = DataFilesList.from_patterns(metadata_patterns, base_path=base_path) if metadata_data_files_list: data_files = DataFilesDict( { split: data_files_list + metadata_data_files_list for split, data_files_list in data_files.items() } ) module_path, _ = _PACKAGED_DATASETS_MODULES[module_name] if metadata_configs: builder_configs, default_config_name = create_builder_configs_from_metadata_configs( module_path, metadata_configs, base_path=base_path, supports_metadata=supports_metadata, default_builder_kwargs=default_builder_kwargs, ) else: builder_configs: List[BuilderConfig] = [ import_main_class(module_path).BUILDER_CONFIG_CLASS( data_files=data_files, **default_builder_kwargs, ) ] default_config_name = None builder_kwargs = { "base_path": self.path, "dataset_name": camelcase_to_snakecase(Path(self.path).name), } if self.data_dir: builder_kwargs["data_files"] = data_files # this file is deprecated and was created automatically in old versions of push_to_hub if os.path.isfile(os.path.join(self.path, config.DATASETDICT_INFOS_FILENAME)): with open(os.path.join(self.path, config.DATASETDICT_INFOS_FILENAME), encoding="utf-8") as f: legacy_dataset_infos = DatasetInfosDict( { config_name: DatasetInfo.from_dict(dataset_info_dict) for config_name, dataset_info_dict in json.load(f).items() } ) if len(legacy_dataset_infos) == 1: # old config e.g. named "username--dataset_name" legacy_config_name = next(iter(legacy_dataset_infos)) legacy_dataset_infos["default"] = legacy_dataset_infos.pop(legacy_config_name) legacy_dataset_infos.update(dataset_infos) dataset_infos = legacy_dataset_infos if default_config_name is None and len(dataset_infos) == 1: default_config_name = next(iter(dataset_infos)) hash = Hasher.hash({"dataset_infos": dataset_infos, "builder_configs": builder_configs}) return DatasetModule( module_path, hash, builder_kwargs, dataset_infos=dataset_infos, builder_configs_parameters=BuilderConfigsParameters( metadata_configs=metadata_configs, builder_configs=builder_configs, default_config_name=default_config_name, ), ) class PackagedDatasetModuleFactory(_DatasetModuleFactory): """Get the dataset builder module from the ones that are packaged with the library: csv, json, etc.""" def __init__( self, name: str, data_dir: Optional[str] = None, data_files: Optional[Union[str, List, Dict]] = None, download_config: Optional[DownloadConfig] = None, download_mode: Optional[Union[DownloadMode, str]] = None, ): self.name = name self.data_files = data_files self.data_dir = data_dir self.download_config = download_config self.download_mode = download_mode increase_load_count(name, resource_type="dataset") def get_module(self) -> DatasetModule: base_path = Path(self.data_dir or "").expanduser().resolve().as_posix() patterns = ( sanitize_patterns(self.data_files) if self.data_files is not None else get_data_patterns(base_path, download_config=self.download_config) ) data_files = DataFilesDict.from_patterns( patterns, download_config=self.download_config, base_path=base_path, ) supports_metadata = self.name in _MODULE_SUPPORTS_METADATA if self.data_files is None and supports_metadata and patterns != DEFAULT_PATTERNS_ALL: try: metadata_patterns = get_metadata_patterns(base_path, download_config=self.download_config) except FileNotFoundError: metadata_patterns = None if metadata_patterns is not None: metadata_data_files_list = DataFilesList.from_patterns( metadata_patterns, download_config=self.download_config, base_path=base_path ) if metadata_data_files_list: data_files = DataFilesDict( { split: data_files_list + metadata_data_files_list for split, data_files_list in data_files.items() } ) module_path, hash = _PACKAGED_DATASETS_MODULES[self.name] builder_kwargs = { "data_files": data_files, "dataset_name": self.name, } return DatasetModule(module_path, hash, builder_kwargs) class HubDatasetModuleFactoryWithoutScript(_DatasetModuleFactory): """ Get the module of a dataset loaded from data files of a dataset repository. The dataset builder module to use is inferred from the data files extensions. """ def __init__( self, name: str, revision: Optional[Union[str, Version]] = None, data_dir: Optional[str] = None, data_files: Optional[Union[str, List, Dict]] = None, download_config: Optional[DownloadConfig] = None, download_mode: Optional[Union[DownloadMode, str]] = None, ): self.name = name self.revision = revision self.data_files = data_files self.data_dir = data_dir self.download_config = download_config or DownloadConfig() self.download_mode = download_mode increase_load_count(name, resource_type="dataset") def get_module(self) -> DatasetModule: hfh_dataset_info = HfApi(config.HF_ENDPOINT).dataset_info( self.name, revision=self.revision, token=self.download_config.token, timeout=100.0, ) # even if metadata_configs is not None (which means that we will resolve files for each config later) # we cannot skip resolving all files because we need to infer module name by files extensions revision = hfh_dataset_info.sha # fix the revision in case there are new commits in the meantime base_path = f"hf://datasets/{self.name}@{revision}/{self.data_dir or ''}".rstrip("/") download_config = self.download_config.copy() if download_config.download_desc is None: download_config.download_desc = "Downloading readme" try: dataset_readme_path = cached_path( hf_hub_url(self.name, config.REPOCARD_FILENAME, revision=revision), download_config=download_config, ) dataset_card_data = DatasetCard.load(Path(dataset_readme_path)).data except FileNotFoundError: dataset_card_data = DatasetCardData() download_config = self.download_config.copy() if download_config.download_desc is None: download_config.download_desc = "Downloading standalone yaml" try: standalone_yaml_path = cached_path( hf_hub_url(self.name, config.REPOYAML_FILENAME, revision=revision), download_config=download_config, ) with open(standalone_yaml_path, "r", encoding="utf-8") as f: standalone_yaml_data = yaml.safe_load(f.read()) if standalone_yaml_data: _dataset_card_data_dict = dataset_card_data.to_dict() _dataset_card_data_dict.update(standalone_yaml_data) dataset_card_data = DatasetCardData(**_dataset_card_data_dict) except FileNotFoundError: pass metadata_configs = MetadataConfigs.from_dataset_card_data(dataset_card_data) dataset_infos = DatasetInfosDict.from_dataset_card_data(dataset_card_data) try: exported_dataset_infos = _datasets_server.get_exported_dataset_infos( dataset=self.name, revision=self.revision, token=self.download_config.token ) exported_dataset_infos = DatasetInfosDict( { config_name: DatasetInfo.from_dict(exported_dataset_infos[config_name]) for config_name in exported_dataset_infos } ) except _datasets_server.DatasetsServerError: exported_dataset_infos = None if exported_dataset_infos: exported_dataset_infos.update(dataset_infos) dataset_infos = exported_dataset_infos # we need a set of data files to find which dataset builder to use # because we need to infer module name by files extensions if self.data_files is not None: patterns = sanitize_patterns(self.data_files) elif metadata_configs and not self.data_dir and "data_files" in next(iter(metadata_configs.values())): patterns = sanitize_patterns(next(iter(metadata_configs.values()))["data_files"]) else: patterns = get_data_patterns(base_path, download_config=self.download_config) data_files = DataFilesDict.from_patterns( patterns, base_path=base_path, allowed_extensions=ALL_ALLOWED_EXTENSIONS, download_config=self.download_config, ) module_name, default_builder_kwargs = infer_module_for_data_files( data_files=data_files, path=self.name, download_config=self.download_config, ) data_files = data_files.filter_extensions(_MODULE_TO_EXTENSIONS[module_name]) # Collect metadata files if the module supports them supports_metadata = module_name in _MODULE_SUPPORTS_METADATA if self.data_files is None and supports_metadata: try: metadata_patterns = get_metadata_patterns(base_path, download_config=self.download_config) except FileNotFoundError: metadata_patterns = None if metadata_patterns is not None: metadata_data_files_list = DataFilesList.from_patterns( metadata_patterns, download_config=self.download_config, base_path=base_path ) if metadata_data_files_list: data_files = DataFilesDict( { split: data_files_list + metadata_data_files_list for split, data_files_list in data_files.items() } ) module_path, _ = _PACKAGED_DATASETS_MODULES[module_name] if metadata_configs: builder_configs, default_config_name = create_builder_configs_from_metadata_configs( module_path, metadata_configs, base_path=base_path, supports_metadata=supports_metadata, default_builder_kwargs=default_builder_kwargs, download_config=self.download_config, ) else: builder_configs: List[BuilderConfig] = [ import_main_class(module_path).BUILDER_CONFIG_CLASS( data_files=data_files, **default_builder_kwargs, ) ] default_config_name = None builder_kwargs = { "base_path": hf_hub_url(self.name, "", revision=revision).rstrip("/"), "repo_id": self.name, "dataset_name": camelcase_to_snakecase(Path(self.name).name), } if self.data_dir: builder_kwargs["data_files"] = data_files download_config = self.download_config.copy() if download_config.download_desc is None: download_config.download_desc = "Downloading metadata" try: # this file is deprecated and was created automatically in old versions of push_to_hub dataset_infos_path = cached_path( hf_hub_url(self.name, config.DATASETDICT_INFOS_FILENAME, revision=revision), download_config=download_config, ) with open(dataset_infos_path, encoding="utf-8") as f: legacy_dataset_infos = DatasetInfosDict( { config_name: DatasetInfo.from_dict(dataset_info_dict) for config_name, dataset_info_dict in json.load(f).items() } ) if len(legacy_dataset_infos) == 1: # old config e.g. named "username--dataset_name" legacy_config_name = next(iter(legacy_dataset_infos)) legacy_dataset_infos["default"] = legacy_dataset_infos.pop(legacy_config_name) legacy_dataset_infos.update(dataset_infos) dataset_infos = legacy_dataset_infos except FileNotFoundError: pass if default_config_name is None and len(dataset_infos) == 1: default_config_name = next(iter(dataset_infos)) hash = revision return DatasetModule( module_path, hash, builder_kwargs, dataset_infos=dataset_infos, builder_configs_parameters=BuilderConfigsParameters( metadata_configs=metadata_configs, builder_configs=builder_configs, default_config_name=default_config_name, ), ) class HubDatasetModuleFactoryWithParquetExport(_DatasetModuleFactory): """ Get the module of a dataset loaded from parquet files of a dataset repository parquet export. """ def __init__( self, name: str, revision: Optional[str] = None, download_config: Optional[DownloadConfig] = None, ): self.name = name self.revision = revision self.download_config = download_config or DownloadConfig() increase_load_count(name, resource_type="dataset") def get_module(self) -> DatasetModule: exported_parquet_files = _datasets_server.get_exported_parquet_files( dataset=self.name, revision=self.revision, token=self.download_config.token ) exported_dataset_infos = _datasets_server.get_exported_dataset_infos( dataset=self.name, revision=self.revision, token=self.download_config.token ) dataset_infos = DatasetInfosDict( { config_name: DatasetInfo.from_dict(exported_dataset_infos[config_name]) for config_name in exported_dataset_infos } ) hfh_dataset_info = HfApi(config.HF_ENDPOINT).dataset_info( self.name, revision="refs/convert/parquet", token=self.download_config.token, timeout=100.0, ) revision = hfh_dataset_info.sha # fix the revision in case there are new commits in the meantime metadata_configs = MetadataConfigs._from_exported_parquet_files_and_dataset_infos( revision=revision, exported_parquet_files=exported_parquet_files, dataset_infos=dataset_infos ) module_path, _ = _PACKAGED_DATASETS_MODULES["parquet"] builder_configs, default_config_name = create_builder_configs_from_metadata_configs( module_path, metadata_configs, supports_metadata=False, download_config=self.download_config, ) hash = self.revision builder_kwargs = { "repo_id": self.name, "dataset_name": camelcase_to_snakecase(Path(self.name).name), } return DatasetModule( module_path, hash, builder_kwargs, dataset_infos=dataset_infos, builder_configs_parameters=BuilderConfigsParameters( metadata_configs=metadata_configs, builder_configs=builder_configs, default_config_name=default_config_name, ), ) class HubDatasetModuleFactoryWithScript(_DatasetModuleFactory): """ Get the module of a dataset from a dataset repository. The dataset script comes from the script inside the dataset repository. """ def __init__( self, name: str, revision: Optional[Union[str, Version]] = None, download_config: Optional[DownloadConfig] = None, download_mode: Optional[Union[DownloadMode, str]] = None, dynamic_modules_path: Optional[str] = None, trust_remote_code: Optional[bool] = None, ): self.name = name self.revision = revision self.download_config = download_config or DownloadConfig() self.download_mode = download_mode self.dynamic_modules_path = dynamic_modules_path self.trust_remote_code = trust_remote_code increase_load_count(name, resource_type="dataset") def download_loading_script(self) -> str: file_path = hf_hub_url(self.name, self.name.split("/")[-1] + ".py", revision=self.revision) download_config = self.download_config.copy() if download_config.download_desc is None: download_config.download_desc = "Downloading builder script" return cached_path(file_path, download_config=download_config) def download_dataset_infos_file(self) -> str: dataset_infos = hf_hub_url(self.name, config.DATASETDICT_INFOS_FILENAME, revision=self.revision) # Download the dataset infos file if available download_config = self.download_config.copy() if download_config.download_desc is None: download_config.download_desc = "Downloading metadata" try: return cached_path( dataset_infos, download_config=download_config, ) except (FileNotFoundError, ConnectionError): return None def download_dataset_readme_file(self) -> str: readme_url = hf_hub_url(self.name, config.REPOCARD_FILENAME, revision=self.revision) # Download the dataset infos file if available download_config = self.download_config.copy() if download_config.download_desc is None: download_config.download_desc = "Downloading readme" try: return cached_path( readme_url, download_config=download_config, ) except (FileNotFoundError, ConnectionError): return None def get_module(self) -> DatasetModule: if config.HF_DATASETS_TRUST_REMOTE_CODE and self.trust_remote_code is None: warnings.warn( f"The repository for {self.name} contains custom code which must be executed to correctly " f"load the dataset. You can inspect the repository content at https://hf.co/datasets/{self.name}\n" f"You can avoid this message in future by passing the argument `trust_remote_code=True`.\n" f"Passing `trust_remote_code=True` will be mandatory to load this dataset from the next major release of `datasets`.", FutureWarning, ) # get script and other files local_path = self.download_loading_script() dataset_infos_path = self.download_dataset_infos_file() dataset_readme_path = self.download_dataset_readme_file() imports = get_imports(local_path) local_imports = _download_additional_modules( name=self.name, base_path=hf_hub_url(self.name, "", revision=self.revision), imports=imports, download_config=self.download_config, ) additional_files = [] if dataset_infos_path: additional_files.append((config.DATASETDICT_INFOS_FILENAME, dataset_infos_path)) if dataset_readme_path: additional_files.append((config.REPOCARD_FILENAME, dataset_readme_path)) # copy the script and the files in an importable directory dynamic_modules_path = self.dynamic_modules_path if self.dynamic_modules_path else init_dynamic_modules() hash = files_to_hash([local_path] + [loc[1] for loc in local_imports]) importable_file_path = _get_importable_file_path( dynamic_modules_path=dynamic_modules_path, module_namespace="datasets", subdirectory_name=hash, name=self.name, ) if not os.path.exists(importable_file_path): trust_remote_code = resolve_trust_remote_code(self.trust_remote_code, self.name) if trust_remote_code: _create_importable_file( local_path=local_path, local_imports=local_imports, additional_files=additional_files, dynamic_modules_path=dynamic_modules_path, module_namespace="datasets", subdirectory_name=hash, name=self.name, download_mode=self.download_mode, ) else: raise ValueError( f"Loading {self.name} requires you to execute the dataset script in that" " repo on your local machine. Make sure you have read the code there to avoid malicious use, then" " set the option `trust_remote_code=True` to remove this error." ) module_path, hash = _load_importable_file( dynamic_modules_path=dynamic_modules_path, module_namespace="datasets", subdirectory_name=hash, name=self.name, ) # make the new module to be noticed by the import system importlib.invalidate_caches() builder_kwargs = { "base_path": hf_hub_url(self.name, "", revision=self.revision).rstrip("/"), "repo_id": self.name, } return DatasetModule(module_path, hash, builder_kwargs, importable_file_path=importable_file_path) class CachedDatasetModuleFactory(_DatasetModuleFactory): """ Get the module of a dataset that has been loaded once already and cached. The script that is loaded from the cache is the most recent one with a matching name. """ def __init__( self, name: str, cache_dir: Optional[str] = None, dynamic_modules_path: Optional[str] = None, ): self.name = name self.cache_dir = cache_dir self.dynamic_modules_path = dynamic_modules_path assert self.name.count("/") <= 1 def get_module(self) -> DatasetModule: dynamic_modules_path = self.dynamic_modules_path if self.dynamic_modules_path else init_dynamic_modules() importable_directory_path = os.path.join(dynamic_modules_path, "datasets", self.name.replace("/", "--")) hashes = ( [h for h in os.listdir(importable_directory_path) if len(h) == 64] if os.path.isdir(importable_directory_path) else None ) if hashes: # get most recent def _get_modification_time(module_hash): return ( (Path(importable_directory_path) / module_hash / (self.name.split("/")[-1] + ".py")) .stat() .st_mtime ) hash = sorted(hashes, key=_get_modification_time)[-1] warning_msg = ( f"Using the latest cached version of the module from {os.path.join(importable_directory_path, hash)} " f"(last modified on {time.ctime(_get_modification_time(hash))}) since it " f"couldn't be found locally at {self.name}" ) if not config.HF_DATASETS_OFFLINE: warning_msg += ", or remotely on the Hugging Face Hub." logger.warning(warning_msg) importable_file_path = _get_importable_file_path( dynamic_modules_path=dynamic_modules_path, module_namespace="datasets", subdirectory_name=hash, name=self.name, ) module_path, hash = _load_importable_file( dynamic_modules_path=dynamic_modules_path, module_namespace="datasets", subdirectory_name=hash, name=self.name, ) # make the new module to be noticed by the import system importlib.invalidate_caches() builder_kwargs = { "repo_id": self.name, } return DatasetModule(module_path, hash, builder_kwargs, importable_file_path=importable_file_path) cache_dir = os.path.expanduser(str(self.cache_dir or config.HF_DATASETS_CACHE)) cached_datasets_directory_path_root = os.path.join(cache_dir, self.name.replace("/", "___")) cached_directory_paths = [ cached_directory_path for cached_directory_path in glob.glob(os.path.join(cached_datasets_directory_path_root, "*", "*", "*")) if os.path.isdir(cached_directory_path) ] if cached_directory_paths: builder_kwargs = { "repo_id": self.name, "dataset_name": self.name.split("/")[-1], } warning_msg = f"Using the latest cached version of the dataset since {self.name} couldn't be found on the Hugging Face Hub" if config.HF_DATASETS_OFFLINE: warning_msg += " (offline mode is enabled)." logger.warning(warning_msg) return DatasetModule( "datasets.packaged_modules.cache.cache", "auto", {**builder_kwargs, "version": "auto"}, ) raise FileNotFoundError(f"Dataset {self.name} is not cached in {self.cache_dir}") class CachedMetricModuleFactory(_MetricModuleFactory): """ Get the module of a metric that has been loaded once already and cached. The script that is loaded from the cache is the most recent one with a matching name. <Deprecated version="2.5.0"> Use the new library 🤗 Evaluate instead: https://huggingface.co/docs/evaluate </Deprecated> """ @deprecated("Use the new library 🤗 Evaluate instead: https://huggingface.co/docs/evaluate") def __init__( self, name: str, dynamic_modules_path: Optional[str] = None, ): self.name = name self.dynamic_modules_path = dynamic_modules_path assert self.name.count("/") == 0 def get_module(self) -> MetricModule: dynamic_modules_path = self.dynamic_modules_path if self.dynamic_modules_path else init_dynamic_modules() importable_directory_path = os.path.join(dynamic_modules_path, "metrics", self.name) hashes = ( [h for h in os.listdir(importable_directory_path) if len(h) == 64] if os.path.isdir(importable_directory_path) else None ) if not hashes: raise FileNotFoundError(f"Metric {self.name} is not cached in {dynamic_modules_path}") # get most recent def _get_modification_time(module_hash): return (Path(importable_directory_path) / module_hash / (self.name + ".py")).stat().st_mtime hash = sorted(hashes, key=_get_modification_time)[-1] logger.warning( f"Using the latest cached version of the module from {os.path.join(importable_directory_path, hash)} " f"(last modified on {time.ctime(_get_modification_time(hash))}) since it " f"couldn't be found locally at {self.name}, or remotely on the Hugging Face Hub." ) # make the new module to be noticed by the import system module_path = ".".join([os.path.basename(dynamic_modules_path), "metrics", self.name, hash, self.name]) importlib.invalidate_caches() return MetricModule(module_path, hash) def dataset_module_factory( path: str, revision: Optional[Union[str, Version]] = None, download_config: Optional[DownloadConfig] = None, download_mode: Optional[Union[DownloadMode, str]] = None, dynamic_modules_path: Optional[str] = None, data_dir: Optional[str] = None, data_files: Optional[Union[Dict, List, str, DataFilesDict]] = None, cache_dir: Optional[str] = None, trust_remote_code: Optional[bool] = None, _require_default_config_name=True, _require_custom_configs=False, **download_kwargs, ) -> DatasetModule: """ Download/extract/cache a dataset module. Dataset codes are cached inside the dynamic modules cache to allow easy import (avoid ugly sys.path tweaks). Args: path (str): Path or name of the dataset. Depending on ``path``, the dataset builder that is used comes from a generic dataset script (JSON, CSV, Parquet, text etc.) or from the dataset script (a python file) inside the dataset directory. For local datasets: - if ``path`` is a local directory (containing data files only) -> load a generic dataset builder (csv, json, text etc.) based on the content of the directory e.g. ``'./path/to/directory/with/my/csv/data'``. - if ``path`` is a local dataset script or a directory containing a local dataset script (if the script has the same name as the directory): -> load the dataset builder from the dataset script e.g. ``'./dataset/squad'`` or ``'./dataset/squad/squad.py'``. For datasets on the Hugging Face Hub (list all available datasets with ``huggingface_hub.list_datasets()``) - if ``path`` is a dataset repository on the HF hub (containing data files only) -> load a generic dataset builder (csv, text etc.) based on the content of the repository e.g. ``'username/dataset_name'``, a dataset repository on the HF hub containing your data files. - if ``path`` is a dataset repository on the HF hub with a dataset script (if the script has the same name as the directory) -> load the dataset builder from the dataset script in the dataset repository e.g. ``glue``, ``squad``, ``'username/dataset_name'``, a dataset repository on the HF hub containing a dataset script `'dataset_name.py'`. revision (:class:`~utils.Version` or :obj:`str`, optional): Version of the dataset script to load. As datasets have their own git repository on the Datasets Hub, the default version "main" corresponds to their "main" branch. You can specify a different version than the default "main" by using a commit SHA or a git tag of the dataset repository. download_config (:class:`DownloadConfig`, optional): Specific download configuration parameters. download_mode (:class:`DownloadMode` or :obj:`str`, default ``REUSE_DATASET_IF_EXISTS``): Download/generate mode. dynamic_modules_path (Optional str, defaults to HF_MODULES_CACHE / "datasets_modules", i.e. ~/.cache/huggingface/modules/datasets_modules): Optional path to the directory in which the dynamic modules are saved. It must have been initialized with :obj:`init_dynamic_modules`. By default, the datasets and metrics are stored inside the `datasets_modules` module. data_dir (:obj:`str`, optional): Directory with the data files. Used only if `data_files` is not specified, in which case it's equal to pass `os.path.join(data_dir, "**")` as `data_files`. data_files (:obj:`Union[Dict, List, str]`, optional): Defining the data_files of the dataset configuration. cache_dir (`str`, *optional*): Directory to read/write data. Defaults to `"~/.cache/huggingface/datasets"`. <Added version="2.16.0"/> trust_remote_code (`bool`, defaults to `True`): Whether or not to allow for datasets defined on the Hub using a dataset script. This option should only be set to `True` for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. <Tip warning={true}> `trust_remote_code` will default to False in the next major release. </Tip> <Added version="2.16.0"/> **download_kwargs (additional keyword arguments): optional attributes for DownloadConfig() which will override the attributes in download_config if supplied. Returns: DatasetModule """ if download_config is None: download_config = DownloadConfig(**download_kwargs) download_mode = DownloadMode(download_mode or DownloadMode.REUSE_DATASET_IF_EXISTS) download_config.extract_compressed_file = True download_config.force_extract = True download_config.force_download = download_mode == DownloadMode.FORCE_REDOWNLOAD filename = list(filter(lambda x: x, path.replace(os.sep, "/").split("/")))[-1] if not filename.endswith(".py"): filename = filename + ".py" combined_path = os.path.join(path, filename) # We have several ways to get a dataset builder: # # - if path is the name of a packaged dataset module # -> use the packaged module (json, csv, etc.) # # - if os.path.join(path, name) is a local python file # -> use the module from the python file # - if path is a local directory (but no python file) # -> use a packaged module (csv, text etc.) based on content of the directory # # - if path has one "/" and is dataset repository on the HF hub with a python file # -> the module from the python file in the dataset repository # - if path has one "/" and is dataset repository on the HF hub without a python file # -> use a packaged module (csv, text etc.) based on content of the repository # Try packaged if path in _PACKAGED_DATASETS_MODULES: return PackagedDatasetModuleFactory( path, data_dir=data_dir, data_files=data_files, download_config=download_config, download_mode=download_mode, ).get_module() # Try locally elif path.endswith(filename): if os.path.isfile(path): return LocalDatasetModuleFactoryWithScript( path, download_mode=download_mode, dynamic_modules_path=dynamic_modules_path, trust_remote_code=trust_remote_code, ).get_module() else: raise FileNotFoundError(f"Couldn't find a dataset script at {relative_to_absolute_path(path)}") elif os.path.isfile(combined_path): return LocalDatasetModuleFactoryWithScript( combined_path, download_mode=download_mode, dynamic_modules_path=dynamic_modules_path, trust_remote_code=trust_remote_code, ).get_module() elif os.path.isdir(path): return LocalDatasetModuleFactoryWithoutScript( path, data_dir=data_dir, data_files=data_files, download_mode=download_mode ).get_module() # Try remotely elif is_relative_path(path) and path.count("/") <= 1: try: _raise_if_offline_mode_is_enabled() hf_api = HfApi(config.HF_ENDPOINT) try: dataset_info = hf_api.dataset_info( repo_id=path, revision=revision, token=download_config.token, timeout=100.0, ) except Exception as e: # noqa catch any exception of hf_hub and consider that the dataset doesn't exist if isinstance( e, ( OfflineModeIsEnabled, requests.exceptions.ConnectTimeout, requests.exceptions.ConnectionError, ), ): raise ConnectionError(f"Couldn't reach '{path}' on the Hub ({type(e).__name__})") elif "404" in str(e): msg = f"Dataset '{path}' doesn't exist on the Hub or cannot be accessed" raise DatasetNotFoundError(msg + f" at revision '{revision}'" if revision else msg) elif "401" in str(e): msg = f"Dataset '{path}' doesn't exist on the Hub or cannot be accessed" msg = msg + f" at revision '{revision}'" if revision else msg raise DatasetNotFoundError( msg + f". If the dataset is private or gated, make sure to log in with `huggingface-cli login` or visit the dataset page at https://huggingface.co/datasets/{path} to ask for access." ) else: raise e if filename in [sibling.rfilename for sibling in dataset_info.siblings]: # contains a dataset script fs = HfFileSystem(endpoint=config.HF_ENDPOINT, token=download_config.token) if _require_custom_configs or (revision and revision != "main"): can_load_config_from_parquet_export = False elif _require_default_config_name: with fs.open(f"datasets/{path}/{filename}", "r", encoding="utf-8") as f: can_load_config_from_parquet_export = "DEFAULT_CONFIG_NAME" not in f.read() else: can_load_config_from_parquet_export = True if config.USE_PARQUET_EXPORT and can_load_config_from_parquet_export: # If the parquet export is ready (parquet files + info available for the current sha), we can use it instead # This fails when the dataset has multiple configs and a default config and # the user didn't specify a configuration name (_require_default_config_name=True). try: return HubDatasetModuleFactoryWithParquetExport( path, download_config=download_config, revision=dataset_info.sha ).get_module() except _datasets_server.DatasetsServerError: pass # Otherwise we must use the dataset script if the user trusts it return HubDatasetModuleFactoryWithScript( path, revision=revision, download_config=download_config, download_mode=download_mode, dynamic_modules_path=dynamic_modules_path, trust_remote_code=trust_remote_code, ).get_module() else: return HubDatasetModuleFactoryWithoutScript( path, revision=revision, data_dir=data_dir, data_files=data_files, download_config=download_config, download_mode=download_mode, ).get_module() except Exception as e1: # All the attempts failed, before raising the error we should check if the module is already cached try: return CachedDatasetModuleFactory( path, dynamic_modules_path=dynamic_modules_path, cache_dir=cache_dir ).get_module() except Exception: # If it's not in the cache, then it doesn't exist. if isinstance(e1, OfflineModeIsEnabled): raise ConnectionError(f"Couldn't reach the Hugging Face Hub for dataset '{path}': {e1}") from None if isinstance(e1, (DataFilesNotFoundError, DatasetNotFoundError, EmptyDatasetError)): raise e1 from None if isinstance(e1, FileNotFoundError): raise FileNotFoundError( f"Couldn't find a dataset script at {relative_to_absolute_path(combined_path)} or any data file in the same directory. " f"Couldn't find '{path}' on the Hugging Face Hub either: {type(e1).__name__}: {e1}" ) from None raise e1 from None else: raise FileNotFoundError( f"Couldn't find a dataset script at {relative_to_absolute_path(combined_path)} or any data file in the same directory." ) @deprecated("Use the new library 🤗 Evaluate instead: https://huggingface.co/docs/evaluate") def metric_module_factory( path: str, revision: Optional[Union[str, Version]] = None, download_config: Optional[DownloadConfig] = None, download_mode: Optional[Union[DownloadMode, str]] = None, dynamic_modules_path: Optional[str] = None, trust_remote_code: Optional[bool] = None, **download_kwargs, ) -> MetricModule: """ Download/extract/cache a metric module. <Deprecated version="2.5.0"> Use the new library 🤗 Evaluate instead: https://huggingface.co/docs/evaluate </Deprecated> Metrics codes are cached inside the dynamic modules cache to allow easy import (avoid ugly sys.path tweaks). Args: path (str): Path or name of the metric script. - if ``path`` is a local metric script or a directory containing a local metric script (if the script has the same name as the directory): -> load the module from the metric script e.g. ``'./metrics/accuracy'`` or ``'./metrics/accuracy/accuracy.py'``. - if ``path`` is a metric on the Hugging Face Hub (ex: `glue`, `squad`) -> load the module from the metric script in the GitHub repository at huggingface/datasets e.g. ``'accuracy'`` or ``'rouge'``. revision (Optional ``Union[str, datasets.Version]``): If specified, the module will be loaded from the datasets repository at this version. By default: - it is set to the local version of the lib. - it will also try to load it from the main branch if it's not available at the local version of the lib. Specifying a version that is different from your local version of the lib might cause compatibility issues. download_config (:class:`DownloadConfig`, optional): Specific download configuration parameters. download_mode (:class:`DownloadMode` or :obj:`str`, default ``REUSE_DATASET_IF_EXISTS``): Download/generate mode. dynamic_modules_path (Optional str, defaults to HF_MODULES_CACHE / "datasets_modules", i.e. ~/.cache/huggingface/modules/datasets_modules): Optional path to the directory in which the dynamic modules are saved. It must have been initialized with :obj:`init_dynamic_modules`. By default, the datasets and metrics are stored inside the `datasets_modules` module. trust_remote_code (`bool`, defaults to `True`): Whether or not to allow for datasets defined on the Hub using a dataset script. This option should only be set to `True` for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. <Tip warning={true}> `trust_remote_code` will default to False in the next major release. </Tip> <Added version="2.16.0"/> **download_kwargs (additional keyword arguments): optional attributes for DownloadConfig() which will override the attributes in download_config if supplied. Returns: MetricModule """ with warnings.catch_warnings(): # Ignore equivalent warnings to the one already issued warnings.filterwarnings("ignore", message=".*https://huggingface.co/docs/evaluate$", category=FutureWarning) if download_config is None: download_config = DownloadConfig(**download_kwargs) download_mode = DownloadMode(download_mode or DownloadMode.REUSE_DATASET_IF_EXISTS) download_config.extract_compressed_file = True download_config.force_extract = True filename = list(filter(lambda x: x, path.replace(os.sep, "/").split("/")))[-1] if not filename.endswith(".py"): filename = filename + ".py" combined_path = os.path.join(path, filename) # Try locally if path.endswith(filename): if os.path.isfile(path): return LocalMetricModuleFactory( path, download_mode=download_mode, dynamic_modules_path=dynamic_modules_path, trust_remote_code=trust_remote_code, ).get_module() else: raise FileNotFoundError(f"Couldn't find a metric script at {relative_to_absolute_path(path)}") elif os.path.isfile(combined_path): return LocalMetricModuleFactory( combined_path, download_mode=download_mode, dynamic_modules_path=dynamic_modules_path ).get_module() elif is_relative_path(path) and path.count("/") == 0: try: return GithubMetricModuleFactory( path, revision=revision, download_config=download_config, download_mode=download_mode, dynamic_modules_path=dynamic_modules_path, trust_remote_code=trust_remote_code, ).get_module() except Exception as e1: # noqa all the attempts failed, before raising the error we should check if the module is already cached. try: return CachedMetricModuleFactory(path, dynamic_modules_path=dynamic_modules_path).get_module() except Exception: # noqa if it's not in the cache, then it doesn't exist. if not isinstance(e1, FileNotFoundError): raise e1 from None raise FileNotFoundError( f"Couldn't find a metric script at {relative_to_absolute_path(combined_path)}. " f"Metric '{path}' doesn't exist on the Hugging Face Hub either." ) from None else: raise FileNotFoundError(f"Couldn't find a metric script at {relative_to_absolute_path(combined_path)}.") @deprecated("Use 'evaluate.load' instead, from the new library 🤗 Evaluate: https://huggingface.co/docs/evaluate") def load_metric( path: str, config_name: Optional[str] = None, process_id: int = 0, num_process: int = 1, cache_dir: Optional[str] = None, experiment_id: Optional[str] = None, keep_in_memory: bool = False, download_config: Optional[DownloadConfig] = None, download_mode: Optional[Union[DownloadMode, str]] = None, revision: Optional[Union[str, Version]] = None, trust_remote_code: Optional[bool] = None, **metric_init_kwargs, ) -> Metric: """Load a `datasets.Metric`. <Deprecated version="2.5.0"> Use `evaluate.load` instead, from the new library 🤗 Evaluate: https://huggingface.co/docs/evaluate </Deprecated> Args: path (``str``): path to the metric processing script with the metric builder. Can be either: - a local path to processing script or the directory containing the script (if the script has the same name as the directory), e.g. ``'./metrics/rouge'`` or ``'./metrics/rogue/rouge.py'`` - a metric identifier on the HuggingFace datasets repo (list all available metrics with ``datasets.list_metrics()``) e.g. ``'rouge'`` or ``'bleu'`` config_name (:obj:`str`, optional): selecting a configuration for the metric (e.g. the GLUE metric has a configuration for each subset) process_id (:obj:`int`, optional): for distributed evaluation: id of the process num_process (:obj:`int`, optional): for distributed evaluation: total number of processes cache_dir (Optional str): path to store the temporary predictions and references (default to `~/.cache/huggingface/metrics/`) experiment_id (``str``): A specific experiment id. This is used if several distributed evaluations share the same file system. This is useful to compute metrics in distributed setups (in particular non-additive metrics like F1). keep_in_memory (bool): Whether to store the temporary results in memory (defaults to False) download_config (Optional ``datasets.DownloadConfig``: specific download configuration parameters. download_mode (:class:`DownloadMode` or :obj:`str`, default ``REUSE_DATASET_IF_EXISTS``): Download/generate mode. revision (Optional ``Union[str, datasets.Version]``): if specified, the module will be loaded from the datasets repository at this version. By default, it is set to the local version of the lib. Specifying a version that is different from your local version of the lib might cause compatibility issues. trust_remote_code (`bool`, defaults to `True`): Whether or not to allow for datasets defined on the Hub using a dataset script. This option should only be set to `True` for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. <Tip warning={true}> `trust_remote_code` will default to False in the next major release. </Tip> <Added version="2.16.0"/> Returns: `datasets.Metric` Example: ```py >>> from datasets import load_metric >>> accuracy = load_metric('accuracy') >>> accuracy.compute(references=[1, 0], predictions=[1, 1]) {'accuracy': 0.5} ``` """ with warnings.catch_warnings(): # Ignore equivalent warnings to the one already issued warnings.filterwarnings("ignore", message=".*https://huggingface.co/docs/evaluate$", category=FutureWarning) download_mode = DownloadMode(download_mode or DownloadMode.REUSE_DATASET_IF_EXISTS) metric_module = metric_module_factory( path, revision=revision, download_config=download_config, download_mode=download_mode, trust_remote_code=trust_remote_code, ).module_path metric_cls = import_main_class(metric_module, dataset=False) metric = metric_cls( config_name=config_name, process_id=process_id, num_process=num_process, cache_dir=cache_dir, keep_in_memory=keep_in_memory, experiment_id=experiment_id, **metric_init_kwargs, ) # Download and prepare resources for the metric metric.download_and_prepare(download_config=download_config) return metric def load_dataset_builder( path: str, name: Optional[str] = None, data_dir: Optional[str] = None, data_files: Optional[Union[str, Sequence[str], Mapping[str, Union[str, Sequence[str]]]]] = None, cache_dir: Optional[str] = None, features: Optional[Features] = None, download_config: Optional[DownloadConfig] = None, download_mode: Optional[Union[DownloadMode, str]] = None, revision: Optional[Union[str, Version]] = None, token: Optional[Union[bool, str]] = None, use_auth_token="deprecated", storage_options: Optional[Dict] = None, trust_remote_code: Optional[bool] = None, _require_default_config_name=True, **config_kwargs, ) -> DatasetBuilder: """Load a dataset builder from the Hugging Face Hub, or a local dataset. A dataset builder can be used to inspect general information that is required to build a dataset (cache directory, config, dataset info, etc.) without downloading the dataset itself. You can find the list of datasets on the [Hub](https://huggingface.co/datasets) or with [`huggingface_hub.list_datasets`]. A dataset is a directory that contains: - some data files in generic formats (JSON, CSV, Parquet, text, etc.) - and optionally a dataset script, if it requires some code to read the data files. This is used to load any kind of formats or structures. Note that dataset scripts can also download and read data files from anywhere - in case your data files already exist online. Args: path (`str`): Path or name of the dataset. Depending on `path`, the dataset builder that is used comes from a generic dataset script (JSON, CSV, Parquet, text etc.) or from the dataset script (a python file) inside the dataset directory. For local datasets: - if `path` is a local directory (containing data files only) -> load a generic dataset builder (csv, json, text etc.) based on the content of the directory e.g. `'./path/to/directory/with/my/csv/data'`. - if `path` is a local dataset script or a directory containing a local dataset script (if the script has the same name as the directory) -> load the dataset builder from the dataset script e.g. `'./dataset/squad'` or `'./dataset/squad/squad.py'`. For datasets on the Hugging Face Hub (list all available datasets with [`huggingface_hub.list_datasets`]) - if `path` is a dataset repository on the HF hub (containing data files only) -> load a generic dataset builder (csv, text etc.) based on the content of the repository e.g. `'username/dataset_name'`, a dataset repository on the HF hub containing your data files. - if `path` is a dataset repository on the HF hub with a dataset script (if the script has the same name as the directory) -> load the dataset builder from the dataset script in the dataset repository e.g. `glue`, `squad`, `'username/dataset_name'`, a dataset repository on the HF hub containing a dataset script `'dataset_name.py'`. name (`str`, *optional*): Defining the name of the dataset configuration. data_dir (`str`, *optional*): Defining the `data_dir` of the dataset configuration. If specified for the generic builders (csv, text etc.) or the Hub datasets and `data_files` is `None`, the behavior is equal to passing `os.path.join(data_dir, **)` as `data_files` to reference all the files in a directory. data_files (`str` or `Sequence` or `Mapping`, *optional*): Path(s) to source data file(s). cache_dir (`str`, *optional*): Directory to read/write data. Defaults to `"~/.cache/huggingface/datasets"`. features ([`Features`], *optional*): Set the features type to use for this dataset. download_config ([`DownloadConfig`], *optional*): Specific download configuration parameters. download_mode ([`DownloadMode`] or `str`, defaults to `REUSE_DATASET_IF_EXISTS`): Download/generate mode. revision ([`Version`] or `str`, *optional*): Version of the dataset script to load. As datasets have their own git repository on the Datasets Hub, the default version "main" corresponds to their "main" branch. You can specify a different version than the default "main" by using a commit SHA or a git tag of the dataset repository. token (`str` or `bool`, *optional*): Optional string or boolean to use as Bearer token for remote files on the Datasets Hub. If `True`, or not specified, will get token from `"~/.huggingface"`. use_auth_token (`str` or `bool`, *optional*): Optional string or boolean to use as Bearer token for remote files on the Datasets Hub. If `True`, or not specified, will get token from `"~/.huggingface"`. <Deprecated version="2.14.0"> `use_auth_token` was deprecated in favor of `token` in version 2.14.0 and will be removed in 3.0.0. </Deprecated> storage_options (`dict`, *optional*, defaults to `None`): **Experimental**. Key/value pairs to be passed on to the dataset file-system backend, if any. <Added version="2.11.0"/> trust_remote_code (`bool`, defaults to `True`): Whether or not to allow for datasets defined on the Hub using a dataset script. This option should only be set to `True` for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. <Tip warning={true}> `trust_remote_code` will default to False in the next major release. </Tip> <Added version="2.16.0"/> **config_kwargs (additional keyword arguments): Keyword arguments to be passed to the [`BuilderConfig`] and used in the [`DatasetBuilder`]. Returns: [`DatasetBuilder`] Example: ```py >>> from datasets import load_dataset_builder >>> ds_builder = load_dataset_builder('rotten_tomatoes') >>> ds_builder.info.features {'label': ClassLabel(num_classes=2, names=['neg', 'pos'], id=None), 'text': Value(dtype='string', id=None)} ``` """ if use_auth_token != "deprecated": warnings.warn( "'use_auth_token' was deprecated in favor of 'token' in version 2.14.0 and will be removed in 3.0.0.\n" "You can remove this warning by passing 'token=<use_auth_token>' instead.", FutureWarning, ) token = use_auth_token download_mode = DownloadMode(download_mode or DownloadMode.REUSE_DATASET_IF_EXISTS) if token is not None: download_config = download_config.copy() if download_config else DownloadConfig() download_config.token = token if storage_options is not None: download_config = download_config.copy() if download_config else DownloadConfig() download_config.storage_options.update(storage_options) dataset_module = dataset_module_factory( path, revision=revision, download_config=download_config, download_mode=download_mode, data_dir=data_dir, data_files=data_files, cache_dir=cache_dir, trust_remote_code=trust_remote_code, _require_default_config_name=_require_default_config_name, _require_custom_configs=bool(config_kwargs), ) # Get dataset builder class from the processing script builder_kwargs = dataset_module.builder_kwargs data_dir = builder_kwargs.pop("data_dir", data_dir) data_files = builder_kwargs.pop("data_files", data_files) config_name = builder_kwargs.pop( "config_name", name or dataset_module.builder_configs_parameters.default_config_name ) dataset_name = builder_kwargs.pop("dataset_name", None) info = dataset_module.dataset_infos.get(config_name) if dataset_module.dataset_infos else None if ( path in _PACKAGED_DATASETS_MODULES and data_files is None and dataset_module.builder_configs_parameters.builder_configs[0].data_files is None ): error_msg = f"Please specify the data files or data directory to load for the {path} dataset builder." example_extensions = [ extension for extension in _EXTENSION_TO_MODULE if _EXTENSION_TO_MODULE[extension] == path ] if example_extensions: error_msg += f'\nFor example `data_files={{"train": "path/to/data/train/*.{example_extensions[0]}"}}`' raise ValueError(error_msg) builder_cls = get_dataset_builder_class(dataset_module, dataset_name=dataset_name) # Instantiate the dataset builder builder_instance: DatasetBuilder = builder_cls( cache_dir=cache_dir, dataset_name=dataset_name, config_name=config_name, data_dir=data_dir, data_files=data_files, hash=dataset_module.hash, info=info, features=features, token=token, storage_options=storage_options, **builder_kwargs, **config_kwargs, ) builder_instance._use_legacy_cache_dir_if_possible(dataset_module) return builder_instance def load_dataset( path: str, name: Optional[str] = None, data_dir: Optional[str] = None, data_files: Optional[Union[str, Sequence[str], Mapping[str, Union[str, Sequence[str]]]]] = None, split: Optional[Union[str, Split]] = None, cache_dir: Optional[str] = None, features: Optional[Features] = None, download_config: Optional[DownloadConfig] = None, download_mode: Optional[Union[DownloadMode, str]] = None, verification_mode: Optional[Union[VerificationMode, str]] = None, ignore_verifications="deprecated", keep_in_memory: Optional[bool] = None, save_infos: bool = False, revision: Optional[Union[str, Version]] = None, token: Optional[Union[bool, str]] = None, use_auth_token="deprecated", task="deprecated", streaming: bool = False, num_proc: Optional[int] = None, storage_options: Optional[Dict] = None, trust_remote_code: bool = None, **config_kwargs, ) -> Union[DatasetDict, Dataset, IterableDatasetDict, IterableDataset]: """Load a dataset from the Hugging Face Hub, or a local dataset. You can find the list of datasets on the [Hub](https://huggingface.co/datasets) or with [`huggingface_hub.list_datasets`]. A dataset is a directory that contains: - some data files in generic formats (JSON, CSV, Parquet, text, etc.). - and optionally a dataset script, if it requires some code to read the data files. This is used to load any kind of formats or structures. Note that dataset scripts can also download and read data files from anywhere - in case your data files already exist online. This function does the following under the hood: 1. Download and import in the library the dataset script from `path` if it's not already cached inside the library. If the dataset has no dataset script, then a generic dataset script is imported instead (JSON, CSV, Parquet, text, etc.) Dataset scripts are small python scripts that define dataset builders. They define the citation, info and format of the dataset, contain the path or URL to the original data files and the code to load examples from the original data files. You can find the complete list of datasets in the Datasets [Hub](https://huggingface.co/datasets). 2. Run the dataset script which will: * Download the dataset file from the original URL (see the script) if it's not already available locally or cached. * Process and cache the dataset in typed Arrow tables for caching. Arrow table are arbitrarily long, typed tables which can store nested objects and be mapped to numpy/pandas/python generic types. They can be directly accessed from disk, loaded in RAM or even streamed over the web. 3. Return a dataset built from the requested splits in `split` (default: all). It also allows to load a dataset from a local directory or a dataset repository on the Hugging Face Hub without dataset script. In this case, it automatically loads all the data files from the directory or the dataset repository. Args: path (`str`): Path or name of the dataset. Depending on `path`, the dataset builder that is used comes from a generic dataset script (JSON, CSV, Parquet, text etc.) or from the dataset script (a python file) inside the dataset directory. For local datasets: - if `path` is a local directory (containing data files only) -> load a generic dataset builder (csv, json, text etc.) based on the content of the directory e.g. `'./path/to/directory/with/my/csv/data'`. - if `path` is a local dataset script or a directory containing a local dataset script (if the script has the same name as the directory) -> load the dataset builder from the dataset script e.g. `'./dataset/squad'` or `'./dataset/squad/squad.py'`. For datasets on the Hugging Face Hub (list all available datasets with [`huggingface_hub.list_datasets`]) - if `path` is a dataset repository on the HF hub (containing data files only) -> load a generic dataset builder (csv, text etc.) based on the content of the repository e.g. `'username/dataset_name'`, a dataset repository on the HF hub containing your data files. - if `path` is a dataset repository on the HF hub with a dataset script (if the script has the same name as the directory) -> load the dataset builder from the dataset script in the dataset repository e.g. `glue`, `squad`, `'username/dataset_name'`, a dataset repository on the HF hub containing a dataset script `'dataset_name.py'`. name (`str`, *optional*): Defining the name of the dataset configuration. data_dir (`str`, *optional*): Defining the `data_dir` of the dataset configuration. If specified for the generic builders (csv, text etc.) or the Hub datasets and `data_files` is `None`, the behavior is equal to passing `os.path.join(data_dir, **)` as `data_files` to reference all the files in a directory. data_files (`str` or `Sequence` or `Mapping`, *optional*): Path(s) to source data file(s). split (`Split` or `str`): Which split of the data to load. If `None`, will return a `dict` with all splits (typically `datasets.Split.TRAIN` and `datasets.Split.TEST`). If given, will return a single Dataset. Splits can be combined and specified like in tensorflow-datasets. cache_dir (`str`, *optional*): Directory to read/write data. Defaults to `"~/.cache/huggingface/datasets"`. features (`Features`, *optional*): Set the features type to use for this dataset. download_config ([`DownloadConfig`], *optional*): Specific download configuration parameters. download_mode ([`DownloadMode`] or `str`, defaults to `REUSE_DATASET_IF_EXISTS`): Download/generate mode. verification_mode ([`VerificationMode`] or `str`, defaults to `BASIC_CHECKS`): Verification mode determining the checks to run on the downloaded/processed dataset information (checksums/size/splits/...). <Added version="2.9.1"/> ignore_verifications (`bool`, defaults to `False`): Ignore the verifications of the downloaded/processed dataset information (checksums/size/splits/...). <Deprecated version="2.9.1"> `ignore_verifications` was deprecated in version 2.9.1 and will be removed in 3.0.0. Please use `verification_mode` instead. </Deprecated> keep_in_memory (`bool`, defaults to `None`): Whether to copy the dataset in-memory. If `None`, the dataset will not be copied in-memory unless explicitly enabled by setting `datasets.config.IN_MEMORY_MAX_SIZE` to nonzero. See more details in the [improve performance](../cache#improve-performance) section. save_infos (`bool`, defaults to `False`): Save the dataset information (checksums/size/splits/...). revision ([`Version`] or `str`, *optional*): Version of the dataset script to load. As datasets have their own git repository on the Datasets Hub, the default version "main" corresponds to their "main" branch. You can specify a different version than the default "main" by using a commit SHA or a git tag of the dataset repository. token (`str` or `bool`, *optional*): Optional string or boolean to use as Bearer token for remote files on the Datasets Hub. If `True`, or not specified, will get token from `"~/.huggingface"`. use_auth_token (`str` or `bool`, *optional*): Optional string or boolean to use as Bearer token for remote files on the Datasets Hub. If `True`, or not specified, will get token from `"~/.huggingface"`. <Deprecated version="2.14.0"> `use_auth_token` was deprecated in favor of `token` in version 2.14.0 and will be removed in 3.0.0. </Deprecated> task (`str`): The task to prepare the dataset for during training and evaluation. Casts the dataset's [`Features`] to standardized column names and types as detailed in `datasets.tasks`. <Deprecated version="2.13.0"> `task` was deprecated in version 2.13.0 and will be removed in 3.0.0. </Deprecated> streaming (`bool`, defaults to `False`): If set to `True`, don't download the data files. Instead, it streams the data progressively while iterating on the dataset. An [`IterableDataset`] or [`IterableDatasetDict`] is returned instead in this case. Note that streaming works for datasets that use data formats that support being iterated over like txt, csv, jsonl for example. Json files may be downloaded completely. Also streaming from remote zip or gzip files is supported but other compressed formats like rar and xz are not yet supported. The tgz format doesn't allow streaming. num_proc (`int`, *optional*, defaults to `None`): Number of processes when downloading and generating the dataset locally. Multiprocessing is disabled by default. <Added version="2.7.0"/> storage_options (`dict`, *optional*, defaults to `None`): **Experimental**. Key/value pairs to be passed on to the dataset file-system backend, if any. <Added version="2.11.0"/> trust_remote_code (`bool`, defaults to `True`): Whether or not to allow for datasets defined on the Hub using a dataset script. This option should only be set to `True` for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. <Tip warning={true}> `trust_remote_code` will default to False in the next major release. </Tip> <Added version="2.16.0"/> **config_kwargs (additional keyword arguments): Keyword arguments to be passed to the `BuilderConfig` and used in the [`DatasetBuilder`]. Returns: [`Dataset`] or [`DatasetDict`]: - if `split` is not `None`: the dataset requested, - if `split` is `None`, a [`~datasets.DatasetDict`] with each split. or [`IterableDataset`] or [`IterableDatasetDict`]: if `streaming=True` - if `split` is not `None`, the dataset is requested - if `split` is `None`, a [`~datasets.streaming.IterableDatasetDict`] with each split. Example: Load a dataset from the Hugging Face Hub: ```py >>> from datasets import load_dataset >>> ds = load_dataset('rotten_tomatoes', split='train') # Map data files to splits >>> data_files = {'train': 'train.csv', 'test': 'test.csv'} >>> ds = load_dataset('namespace/your_dataset_name', data_files=data_files) ``` Load a local dataset: ```py # Load a CSV file >>> from datasets import load_dataset >>> ds = load_dataset('csv', data_files='path/to/local/my_dataset.csv') # Load a JSON file >>> from datasets import load_dataset >>> ds = load_dataset('json', data_files='path/to/local/my_dataset.json') # Load from a local loading script >>> from datasets import load_dataset >>> ds = load_dataset('path/to/local/loading_script/loading_script.py', split='train') ``` Load an [`~datasets.IterableDataset`]: ```py >>> from datasets import load_dataset >>> ds = load_dataset('rotten_tomatoes', split='train', streaming=True) ``` Load an image dataset with the `ImageFolder` dataset builder: ```py >>> from datasets import load_dataset >>> ds = load_dataset('imagefolder', data_dir='/path/to/images', split='train') ``` """ if use_auth_token != "deprecated": warnings.warn( "'use_auth_token' was deprecated in favor of 'token' in version 2.14.0 and will be removed in 3.0.0.\n" "You can remove this warning by passing 'token=<use_auth_token>' instead.", FutureWarning, ) token = use_auth_token if ignore_verifications != "deprecated": verification_mode = VerificationMode.NO_CHECKS if ignore_verifications else VerificationMode.ALL_CHECKS warnings.warn( "'ignore_verifications' was deprecated in favor of 'verification_mode' in version 2.9.1 and will be removed in 3.0.0.\n" f"You can remove this warning by passing 'verification_mode={verification_mode.value}' instead.", FutureWarning, ) if task != "deprecated": warnings.warn( "'task' was deprecated in version 2.13.0 and will be removed in 3.0.0.\n", FutureWarning, ) else: task = None if data_files is not None and not data_files: raise ValueError(f"Empty 'data_files': '{data_files}'. It should be either non-empty or None (default).") if Path(path, config.DATASET_STATE_JSON_FILENAME).exists(): raise ValueError( "You are trying to load a dataset that was saved using `save_to_disk`. " "Please use `load_from_disk` instead." ) if streaming and num_proc is not None: raise NotImplementedError( "Loading a streaming dataset in parallel with `num_proc` is not implemented. " "To parallelize streaming, you can wrap the dataset with a PyTorch DataLoader using `num_workers` > 1 instead." ) download_mode = DownloadMode(download_mode or DownloadMode.REUSE_DATASET_IF_EXISTS) verification_mode = VerificationMode( (verification_mode or VerificationMode.BASIC_CHECKS) if not save_infos else VerificationMode.ALL_CHECKS ) # Create a dataset builder builder_instance = load_dataset_builder( path=path, name=name, data_dir=data_dir, data_files=data_files, cache_dir=cache_dir, features=features, download_config=download_config, download_mode=download_mode, revision=revision, token=token, storage_options=storage_options, trust_remote_code=trust_remote_code, _require_default_config_name=name is None, **config_kwargs, ) # Return iterable dataset in case of streaming if streaming: return builder_instance.as_streaming_dataset(split=split) # Download and prepare data builder_instance.download_and_prepare( download_config=download_config, download_mode=download_mode, verification_mode=verification_mode, num_proc=num_proc, storage_options=storage_options, ) # Build dataset for splits keep_in_memory = ( keep_in_memory if keep_in_memory is not None else is_small_dataset(builder_instance.info.dataset_size) ) ds = builder_instance.as_dataset(split=split, verification_mode=verification_mode, in_memory=keep_in_memory) # Rename and cast features to match task schema if task is not None: # To avoid issuing the same warning twice with warnings.catch_warnings(): warnings.simplefilter("ignore", FutureWarning) ds = ds.prepare_for_task(task) if save_infos: builder_instance._save_infos() return ds def load_from_disk( dataset_path: str, fs="deprecated", keep_in_memory: Optional[bool] = None, storage_options: Optional[dict] = None ) -> Union[Dataset, DatasetDict]: """ Loads a dataset that was previously saved using [`~Dataset.save_to_disk`] from a dataset directory, or from a filesystem using any implementation of `fsspec.spec.AbstractFileSystem`. Args: dataset_path (`str`): Path (e.g. `"dataset/train"`) or remote URI (e.g. `"s3://my-bucket/dataset/train"`) of the [`Dataset`] or [`DatasetDict`] directory where the dataset will be loaded from. fs (`~filesystems.S3FileSystem` or `fsspec.spec.AbstractFileSystem`, *optional*): Instance of the remote filesystem used to download the files from. <Deprecated version="2.9.0"> `fs` was deprecated in version 2.9.0 and will be removed in 3.0.0. Please use `storage_options` instead, e.g. `storage_options=fs.storage_options`. </Deprecated> keep_in_memory (`bool`, defaults to `None`): Whether to copy the dataset in-memory. If `None`, the dataset will not be copied in-memory unless explicitly enabled by setting `datasets.config.IN_MEMORY_MAX_SIZE` to nonzero. See more details in the [improve performance](../cache#improve-performance) section. storage_options (`dict`, *optional*): Key/value pairs to be passed on to the file-system backend, if any. <Added version="2.9.0"/> Returns: [`Dataset`] or [`DatasetDict`]: - If `dataset_path` is a path of a dataset directory: the dataset requested. - If `dataset_path` is a path of a dataset dict directory, a [`DatasetDict`] with each split. Example: ```py >>> from datasets import load_from_disk >>> ds = load_from_disk('path/to/dataset/directory') ``` """ if fs != "deprecated": warnings.warn( "'fs' was deprecated in favor of 'storage_options' in version 2.9.0 and will be removed in 3.0.0.\n" "You can remove this warning by passing 'storage_options=fs.storage_options' instead.", FutureWarning, ) storage_options = fs.storage_options fs: fsspec.AbstractFileSystem fs, *_ = url_to_fs(dataset_path, **(storage_options or {})) if not fs.exists(dataset_path): raise FileNotFoundError(f"Directory {dataset_path} not found") if fs.isfile(posixpath.join(dataset_path, config.DATASET_INFO_FILENAME)) and fs.isfile( posixpath.join(dataset_path, config.DATASET_STATE_JSON_FILENAME) ): return Dataset.load_from_disk(dataset_path, keep_in_memory=keep_in_memory, storage_options=storage_options) elif fs.isfile(posixpath.join(dataset_path, config.DATASETDICT_JSON_FILENAME)): return DatasetDict.load_from_disk(dataset_path, keep_in_memory=keep_in_memory, storage_options=storage_options) else: raise FileNotFoundError( f"Directory {dataset_path} is neither a `Dataset` directory nor a `DatasetDict` directory." )
datasets/src/datasets/load.py/0
{ "file_path": "datasets/src/datasets/load.py", "repo_id": "datasets", "token_count": 53030 }
73
import io import json from itertools import islice from typing import Any, Callable, Dict, List import numpy as np import pyarrow as pa import datasets logger = datasets.utils.logging.get_logger(__name__) class WebDataset(datasets.GeneratorBasedBuilder): DEFAULT_WRITER_BATCH_SIZE = 100 IMAGE_EXTENSIONS: List[str] # definition at the bottom of the script AUDIO_EXTENSIONS: List[str] # definition at the bottom of the script DECODERS: Dict[str, Callable[[Any], Any]] # definition at the bottom of the script NUM_EXAMPLES_FOR_FEATURES_INFERENCE = 5 @classmethod def _get_pipeline_from_tar(cls, tar_path, tar_iterator): current_example = {} for filename, f in tar_iterator: if "." in filename: example_key, field_name = filename.split(".", 1) if current_example and current_example["__key__"] != example_key: yield current_example current_example = {} current_example["__key__"] = example_key current_example["__url__"] = tar_path current_example[field_name.lower()] = f.read() if field_name in cls.DECODERS: current_example[field_name] = cls.DECODERS[field_name](current_example[field_name]) if current_example: yield current_example def _info(self) -> datasets.DatasetInfo: return datasets.DatasetInfo() def _split_generators(self, dl_manager): """We handle string, list and dicts in datafiles""" # Download the data files if not self.config.data_files: raise ValueError(f"At least one data file must be specified, but got data_files={self.config.data_files}") data_files = dl_manager.download(self.config.data_files) if isinstance(data_files, (str, list, tuple)): tar_paths = data_files if isinstance(tar_paths, str): tar_paths = [tar_paths] tar_iterators = [dl_manager.iter_archive(tar_path) for tar_path in tar_paths] splits = [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={"tar_paths": tar_paths, "tar_iterators": tar_iterators} ) ] else: splits = [] for split_name, tar_paths in data_files.items(): if isinstance(tar_paths, str): tar_paths = [tar_paths] tar_iterators = [dl_manager.iter_archive(tar_path) for tar_path in tar_paths] splits.append( datasets.SplitGenerator( name=split_name, gen_kwargs={"tar_paths": tar_paths, "tar_iterators": tar_iterators} ) ) if not self.info.features: # Get one example to get the feature types pipeline = self._get_pipeline_from_tar(tar_paths[0], tar_iterators[0]) first_examples = list(islice(pipeline, self.NUM_EXAMPLES_FOR_FEATURES_INFERENCE)) if any(example.keys() != first_examples[0].keys() for example in first_examples): raise ValueError( "The TAR archives of the dataset should be in WebDataset format, " "but the files in the archive don't share the same prefix or the same types." ) pa_tables = [pa.Table.from_pylist([example]) for example in first_examples] if datasets.config.PYARROW_VERSION.major < 14: inferred_arrow_schema = pa.concat_tables(pa_tables, promote=True).schema else: inferred_arrow_schema = pa.concat_tables(pa_tables, promote_options="default").schema features = datasets.Features.from_arrow_schema(inferred_arrow_schema) # Set Image types for field_name in first_examples[0]: extension = field_name.rsplit(".", 1)[-1] if extension in self.IMAGE_EXTENSIONS: features[field_name] = datasets.Image() # Set Audio types for field_name in first_examples[0]: extension = field_name.rsplit(".", 1)[-1] if extension in self.AUDIO_EXTENSIONS: features[field_name] = datasets.Audio() self.info.features = features return splits def _generate_examples(self, tar_paths, tar_iterators): image_field_names = [ field_name for field_name, feature in self.info.features.items() if isinstance(feature, datasets.Image) ] audio_field_names = [ field_name for field_name, feature in self.info.features.items() if isinstance(feature, datasets.Audio) ] for tar_idx, (tar_path, tar_iterator) in enumerate(zip(tar_paths, tar_iterators)): for example_idx, example in enumerate(self._get_pipeline_from_tar(tar_path, tar_iterator)): for field_name in image_field_names + audio_field_names: example[field_name] = {"path": example["__key__"] + "." + field_name, "bytes": example[field_name]} yield f"{tar_idx}_{example_idx}", example # Obtained with: # ``` # import PIL.Image # IMAGE_EXTENSIONS = [] # PIL.Image.init() # for ext, format in PIL.Image.EXTENSION.items(): # if format in PIL.Image.OPEN: # IMAGE_EXTENSIONS.append(ext[1:]) # ``` # We intentionally do not run this code on launch because: # (1) Pillow is an optional dependency, so importing Pillow in global namespace is not allowed # (2) To ensure the list of supported extensions is deterministic IMAGE_EXTENSIONS = [ "blp", "bmp", "dib", "bufr", "cur", "pcx", "dcx", "dds", "ps", "eps", "fit", "fits", "fli", "flc", "ftc", "ftu", "gbr", "gif", "grib", "h5", "hdf", "png", "apng", "jp2", "j2k", "jpc", "jpf", "jpx", "j2c", "icns", "ico", "im", "iim", "tif", "tiff", "jfif", "jpe", "jpg", "jpeg", "mpg", "mpeg", "msp", "pcd", "pxr", "pbm", "pgm", "ppm", "pnm", "psd", "bw", "rgb", "rgba", "sgi", "ras", "tga", "icb", "vda", "vst", "webp", "wmf", "emf", "xbm", "xpm", ] WebDataset.IMAGE_EXTENSIONS = IMAGE_EXTENSIONS # Obtained with: # ``` # import soundfile as sf # # AUDIO_EXTENSIONS = [f".{format.lower()}" for format in sf.available_formats().keys()] # # # .mp3 is currently decoded via `torchaudio`, .opus decoding is supported if version of `libsndfile` >= 1.0.30: # AUDIO_EXTENSIONS.extend([".mp3", ".opus"]) # ``` # We intentionally do not run this code on launch because: # (1) Soundfile is an optional dependency, so importing it in global namespace is not allowed # (2) To ensure the list of supported extensions is deterministic AUDIO_EXTENSIONS = [ "aiff", "au", "avr", "caf", "flac", "htk", "svx", "mat4", "mat5", "mpc2k", "ogg", "paf", "pvf", "raw", "rf64", "sd2", "sds", "ircam", "voc", "w64", "wav", "nist", "wavex", "wve", "xi", "mp3", "opus", ] WebDataset.AUDIO_EXTENSIONS = AUDIO_EXTENSIONS def text_loads(data: bytes): return data.decode("utf-8") def tenbin_loads(data: bytes): from . import _tenbin return _tenbin.decode_buffer(data) def msgpack_loads(data: bytes): import msgpack return msgpack.unpackb(data) def npy_loads(data: bytes): import numpy.lib.format stream = io.BytesIO(data) return numpy.lib.format.read_array(stream, allow_pickle=False) def npz_loads(data: bytes): return np.load(io.BytesIO(data), allow_pickle=False) def cbor_loads(data: bytes): import cbor return cbor.loads(data) # Obtained by checking `decoders` in `webdataset.autodecode` # and removing unsafe extension decoders. # Removed Pickle decoders: # - "pyd": lambda data: pickle.loads(data) # - "pickle": lambda data: pickle.loads(data) # Removed Torch decoders: # - "pth": lambda data: torch_loads(data) # Modified NumPy decoders to fix CVE-2019-6446 (add allow_pickle=False): # - "npy": npy_loads, # - "npz": lambda data: np.load(io.BytesIO(data)), DECODERS = { "txt": text_loads, "text": text_loads, "transcript": text_loads, "cls": int, "cls2": int, "index": int, "inx": int, "id": int, "json": json.loads, "jsn": json.loads, "ten": tenbin_loads, "tb": tenbin_loads, "mp": msgpack_loads, "msg": msgpack_loads, "npy": npy_loads, "npz": npz_loads, "cbor": cbor_loads, } WebDataset.DECODERS = DECODERS
datasets/src/datasets/packaged_modules/webdataset/webdataset.py/0
{ "file_path": "datasets/src/datasets/packaged_modules/webdataset/webdataset.py", "repo_id": "datasets", "token_count": 4107 }
74
from importlib import import_module from .logging import get_logger logger = get_logger(__name__) class _PatchedModuleObj: """Set all the modules components as attributes of the _PatchedModuleObj object.""" def __init__(self, module, attrs=None): attrs = attrs or [] if module is not None: for key in module.__dict__: if key in attrs or not key.startswith("__"): setattr(self, key, getattr(module, key)) self._original_module = module._original_module if isinstance(module, _PatchedModuleObj) else module class patch_submodule: """ Patch a submodule attribute of an object, by keeping all other submodules intact at all levels. Example:: >>> import importlib >>> from datasets.load import dataset_module_factory >>> from datasets.streaming import patch_submodule, xjoin >>> >>> dataset_module = dataset_module_factory("snli") >>> snli_module = importlib.import_module(dataset_module.module_path) >>> patcher = patch_submodule(snli_module, "os.path.join", xjoin) >>> patcher.start() >>> assert snli_module.os.path.join is xjoin """ _active_patches = [] def __init__(self, obj, target: str, new, attrs=None): self.obj = obj self.target = target self.new = new self.key = target.split(".")[0] self.original = {} self.attrs = attrs or [] def __enter__(self): *submodules, target_attr = self.target.split(".") # Patch modules: # it's used to patch attributes of submodules like "os.path.join"; # in this case we need to patch "os" and "os.path" for i in range(len(submodules)): try: submodule = import_module(".".join(submodules[: i + 1])) except ModuleNotFoundError: continue # We iterate over all the globals in self.obj in case we find "os" or "os.path" for attr in self.obj.__dir__(): obj_attr = getattr(self.obj, attr) # We don't check for the name of the global, but rather if its value *is* "os" or "os.path". # This allows to patch renamed modules like "from os import path as ospath". if obj_attr is submodule or ( isinstance(obj_attr, _PatchedModuleObj) and obj_attr._original_module is submodule ): self.original[attr] = obj_attr # patch at top level setattr(self.obj, attr, _PatchedModuleObj(obj_attr, attrs=self.attrs)) patched = getattr(self.obj, attr) # construct lower levels patches for key in submodules[i + 1 :]: setattr(patched, key, _PatchedModuleObj(getattr(patched, key, None), attrs=self.attrs)) patched = getattr(patched, key) # finally set the target attribute setattr(patched, target_attr, self.new) # Patch attribute itself: # it's used for builtins like "open", # and also to patch "os.path.join" we may also need to patch "join" # itself if it was imported as "from os.path import join". if submodules: # if it's an attribute of a submodule like "os.path.join" try: attr_value = getattr(import_module(".".join(submodules)), target_attr) except (AttributeError, ModuleNotFoundError): return # We iterate over all the globals in self.obj in case we find "os.path.join" for attr in self.obj.__dir__(): # We don't check for the name of the global, but rather if its value *is* "os.path.join". # This allows to patch renamed attributes like "from os.path import join as pjoin". if getattr(self.obj, attr) is attr_value: self.original[attr] = getattr(self.obj, attr) setattr(self.obj, attr, self.new) elif target_attr in globals()["__builtins__"]: # if it'a s builtin like "open" self.original[target_attr] = globals()["__builtins__"][target_attr] setattr(self.obj, target_attr, self.new) else: raise RuntimeError(f"Tried to patch attribute {target_attr} instead of a submodule.") def __exit__(self, *exc_info): for attr in list(self.original): setattr(self.obj, attr, self.original.pop(attr)) def start(self): """Activate a patch.""" self.__enter__() self._active_patches.append(self) def stop(self): """Stop an active patch.""" try: self._active_patches.remove(self) except ValueError: # If the patch hasn't been started this will fail return None return self.__exit__()
datasets/src/datasets/utils/patching.py/0
{ "file_path": "datasets/src/datasets/utils/patching.py", "repo_id": "datasets", "token_count": 2222 }
75