text
stringlengths
7
1.24M
id
stringlengths
14
166
metadata
dict
__index_level_0__
int64
0
519
# coding=utf-8 # Copyright 2024 HuggingFace Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import gc import random import tempfile import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNet2DConditionModel from diffusers.pipelines.semantic_stable_diffusion import SemanticStableDiffusionPipeline as StableDiffusionPipeline from diffusers.utils.testing_utils import ( enable_full_determinism, floats_tensor, nightly, require_torch_gpu, torch_device, ) enable_full_determinism() class SafeDiffusionPipelineFastTests(unittest.TestCase): def setUp(self): # clean up the VRAM before each test super().setUp() gc.collect() torch.cuda.empty_cache() def tearDown(self): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def dummy_image(self): batch_size = 1 num_channels = 3 sizes = (32, 32) image = floats_tensor((batch_size, num_channels) + sizes, rng=random.Random(0)).to(torch_device) return image @property def dummy_cond_unet(self): torch.manual_seed(0) model = UNet2DConditionModel( block_out_channels=(32, 64), layers_per_block=2, sample_size=32, in_channels=4, out_channels=4, down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"), up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"), cross_attention_dim=32, ) return model @property def dummy_vae(self): torch.manual_seed(0) model = AutoencoderKL( block_out_channels=[32, 64], in_channels=3, out_channels=3, down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"], up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"], latent_channels=4, ) return model @property def dummy_text_encoder(self): torch.manual_seed(0) config = CLIPTextConfig( bos_token_id=0, eos_token_id=2, hidden_size=32, intermediate_size=37, layer_norm_eps=1e-05, num_attention_heads=4, num_hidden_layers=5, pad_token_id=1, vocab_size=1000, ) return CLIPTextModel(config) @property def dummy_extractor(self): def extract(*args, **kwargs): class Out: def __init__(self): self.pixel_values = torch.ones([0]) def to(self, device): self.pixel_values.to(device) return self return Out() return extract def test_semantic_diffusion_ddim(self): device = "cpu" # ensure determinism for the device-dependent torch.Generator unet = self.dummy_cond_unet scheduler = DDIMScheduler( beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", clip_sample=False, set_alpha_to_one=False, ) vae = self.dummy_vae bert = self.dummy_text_encoder tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip") # make sure here that pndm scheduler skips prk sd_pipe = StableDiffusionPipeline( unet=unet, scheduler=scheduler, vae=vae, text_encoder=bert, tokenizer=tokenizer, safety_checker=None, feature_extractor=self.dummy_extractor, ) sd_pipe = sd_pipe.to(device) sd_pipe.set_progress_bar_config(disable=None) prompt = "A painting of a squirrel eating a burger" generator = torch.Generator(device=device).manual_seed(0) output = sd_pipe([prompt], generator=generator, guidance_scale=6.0, num_inference_steps=2, output_type="np") image = output.images generator = torch.Generator(device=device).manual_seed(0) image_from_tuple = sd_pipe( [prompt], generator=generator, guidance_scale=6.0, num_inference_steps=2, output_type="np", return_dict=False, )[0] image_slice = image[0, -3:, -3:, -1] image_from_tuple_slice = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) expected_slice = np.array([0.5753, 0.6114, 0.5001, 0.5034, 0.5470, 0.4729, 0.4971, 0.4867, 0.4867]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2 def test_semantic_diffusion_pndm(self): device = "cpu" # ensure determinism for the device-dependent torch.Generator unet = self.dummy_cond_unet scheduler = PNDMScheduler(skip_prk_steps=True) vae = self.dummy_vae bert = self.dummy_text_encoder tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip") # make sure here that pndm scheduler skips prk sd_pipe = StableDiffusionPipeline( unet=unet, scheduler=scheduler, vae=vae, text_encoder=bert, tokenizer=tokenizer, safety_checker=None, feature_extractor=self.dummy_extractor, ) sd_pipe = sd_pipe.to(device) sd_pipe.set_progress_bar_config(disable=None) prompt = "A painting of a squirrel eating a burger" generator = torch.Generator(device=device).manual_seed(0) output = sd_pipe([prompt], generator=generator, guidance_scale=6.0, num_inference_steps=2, output_type="np") image = output.images generator = torch.Generator(device=device).manual_seed(0) image_from_tuple = sd_pipe( [prompt], generator=generator, guidance_scale=6.0, num_inference_steps=2, output_type="np", return_dict=False, )[0] image_slice = image[0, -3:, -3:, -1] image_from_tuple_slice = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) expected_slice = np.array([0.5122, 0.5712, 0.4825, 0.5053, 0.5646, 0.4769, 0.5179, 0.4894, 0.4994]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2 def test_semantic_diffusion_no_safety_checker(self): pipe = StableDiffusionPipeline.from_pretrained( "hf-internal-testing/tiny-stable-diffusion-lms-pipe", safety_checker=None ) assert isinstance(pipe, StableDiffusionPipeline) assert isinstance(pipe.scheduler, LMSDiscreteScheduler) assert pipe.safety_checker is None image = pipe("example prompt", num_inference_steps=2).images[0] assert image is not None # check that there's no error when saving a pipeline with one of the models being None with tempfile.TemporaryDirectory() as tmpdirname: pipe.save_pretrained(tmpdirname) pipe = StableDiffusionPipeline.from_pretrained(tmpdirname) # sanity check that the pipeline still works assert pipe.safety_checker is None image = pipe("example prompt", num_inference_steps=2).images[0] assert image is not None @unittest.skipIf(torch_device != "cuda", "This test requires a GPU") def test_semantic_diffusion_fp16(self): """Test that stable diffusion works with fp16""" unet = self.dummy_cond_unet scheduler = PNDMScheduler(skip_prk_steps=True) vae = self.dummy_vae bert = self.dummy_text_encoder tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip") # put models in fp16 unet = unet.half() vae = vae.half() bert = bert.half() # make sure here that pndm scheduler skips prk sd_pipe = StableDiffusionPipeline( unet=unet, scheduler=scheduler, vae=vae, text_encoder=bert, tokenizer=tokenizer, safety_checker=None, feature_extractor=self.dummy_extractor, ) sd_pipe = sd_pipe.to(torch_device) sd_pipe.set_progress_bar_config(disable=None) prompt = "A painting of a squirrel eating a burger" image = sd_pipe([prompt], num_inference_steps=2, output_type="np").images assert image.shape == (1, 64, 64, 3) @nightly @require_torch_gpu class SemanticDiffusionPipelineIntegrationTests(unittest.TestCase): def setUp(self): # clean up the VRAM before each test super().setUp() gc.collect() torch.cuda.empty_cache() def tearDown(self): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def test_positive_guidance(self): torch_device = "cuda" pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5") pipe = pipe.to(torch_device) pipe.set_progress_bar_config(disable=None) prompt = "a photo of a cat" edit = { "editing_prompt": ["sunglasses"], "reverse_editing_direction": [False], "edit_warmup_steps": 10, "edit_guidance_scale": 6, "edit_threshold": 0.95, "edit_momentum_scale": 0.5, "edit_mom_beta": 0.6, } seed = 3 guidance_scale = 7 # no sega enabled generator = torch.Generator(torch_device) generator.manual_seed(seed) output = pipe( [prompt], generator=generator, guidance_scale=guidance_scale, num_inference_steps=50, output_type="np", width=512, height=512, ) image = output.images image_slice = image[0, -3:, -3:, -1] expected_slice = [ 0.34673113, 0.38492733, 0.37597352, 0.34086335, 0.35650748, 0.35579205, 0.3384763, 0.34340236, 0.3573271, ] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 # with sega enabled # generator = torch.manual_seed(seed) generator.manual_seed(seed) output = pipe( [prompt], generator=generator, guidance_scale=guidance_scale, num_inference_steps=50, output_type="np", width=512, height=512, **edit, ) image = output.images image_slice = image[0, -3:, -3:, -1] expected_slice = [ 0.41887826, 0.37728766, 0.30138272, 0.41416335, 0.41664985, 0.36283392, 0.36191246, 0.43364465, 0.43001732, ] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 def test_negative_guidance(self): torch_device = "cuda" pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5") pipe = pipe.to(torch_device) pipe.set_progress_bar_config(disable=None) prompt = "an image of a crowded boulevard, realistic, 4k" edit = { "editing_prompt": "crowd, crowded, people", "reverse_editing_direction": True, "edit_warmup_steps": 10, "edit_guidance_scale": 8.3, "edit_threshold": 0.9, "edit_momentum_scale": 0.5, "edit_mom_beta": 0.6, } seed = 9 guidance_scale = 7 # no sega enabled generator = torch.Generator(torch_device) generator.manual_seed(seed) output = pipe( [prompt], generator=generator, guidance_scale=guidance_scale, num_inference_steps=50, output_type="np", width=512, height=512, ) image = output.images image_slice = image[0, -3:, -3:, -1] expected_slice = [ 0.43497998, 0.91814065, 0.7540739, 0.55580205, 0.8467265, 0.5389691, 0.62574506, 0.58897763, 0.50926757, ] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 # with sega enabled # generator = torch.manual_seed(seed) generator.manual_seed(seed) output = pipe( [prompt], generator=generator, guidance_scale=guidance_scale, num_inference_steps=50, output_type="np", width=512, height=512, **edit, ) image = output.images image_slice = image[0, -3:, -3:, -1] expected_slice = [ 0.3089719, 0.30500144, 0.29016042, 0.30630964, 0.325687, 0.29419225, 0.2908091, 0.28723598, 0.27696294, ] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 def test_multi_cond_guidance(self): torch_device = "cuda" pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5") pipe = pipe.to(torch_device) pipe.set_progress_bar_config(disable=None) prompt = "a castle next to a river" edit = { "editing_prompt": ["boat on a river, boat", "monet, impression, sunrise"], "reverse_editing_direction": False, "edit_warmup_steps": [15, 18], "edit_guidance_scale": 6, "edit_threshold": [0.9, 0.8], "edit_momentum_scale": 0.5, "edit_mom_beta": 0.6, } seed = 48 guidance_scale = 7 # no sega enabled generator = torch.Generator(torch_device) generator.manual_seed(seed) output = pipe( [prompt], generator=generator, guidance_scale=guidance_scale, num_inference_steps=50, output_type="np", width=512, height=512, ) image = output.images image_slice = image[0, -3:, -3:, -1] expected_slice = [ 0.75163555, 0.76037145, 0.61785, 0.9189673, 0.8627701, 0.85189694, 0.8512813, 0.87012076, 0.8312857, ] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 # with sega enabled # generator = torch.manual_seed(seed) generator.manual_seed(seed) output = pipe( [prompt], generator=generator, guidance_scale=guidance_scale, num_inference_steps=50, output_type="np", width=512, height=512, **edit, ) image = output.images image_slice = image[0, -3:, -3:, -1] expected_slice = [ 0.73553365, 0.7537271, 0.74341905, 0.66480356, 0.6472925, 0.63039416, 0.64812905, 0.6749717, 0.6517102, ] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 def test_guidance_fp16(self): torch_device = "cuda" pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16) pipe = pipe.to(torch_device) pipe.set_progress_bar_config(disable=None) prompt = "a photo of a cat" edit = { "editing_prompt": ["sunglasses"], "reverse_editing_direction": [False], "edit_warmup_steps": 10, "edit_guidance_scale": 6, "edit_threshold": 0.95, "edit_momentum_scale": 0.5, "edit_mom_beta": 0.6, } seed = 3 guidance_scale = 7 # no sega enabled generator = torch.Generator(torch_device) generator.manual_seed(seed) output = pipe( [prompt], generator=generator, guidance_scale=guidance_scale, num_inference_steps=50, output_type="np", width=512, height=512, ) image = output.images image_slice = image[0, -3:, -3:, -1] expected_slice = [ 0.34887695, 0.3876953, 0.375, 0.34423828, 0.3581543, 0.35717773, 0.3383789, 0.34570312, 0.359375, ] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2 # with sega enabled # generator = torch.manual_seed(seed) generator.manual_seed(seed) output = pipe( [prompt], generator=generator, guidance_scale=guidance_scale, num_inference_steps=50, output_type="np", width=512, height=512, **edit, ) image = output.images image_slice = image[0, -3:, -3:, -1] expected_slice = [ 0.42285156, 0.36914062, 0.29077148, 0.42041016, 0.41918945, 0.35498047, 0.3618164, 0.4423828, 0.43115234, ] assert image.shape == (1, 512, 512, 3) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
diffusers/tests/pipelines/semantic_stable_diffusion/test_semantic_diffusion.py/0
{ "file_path": "diffusers/tests/pipelines/semantic_stable_diffusion/test_semantic_diffusion.py", "repo_id": "diffusers", "token_count": 9744 }
154
# coding=utf-8 # Copyright 2024 HuggingFace Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import gc import random import traceback import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, AutoencoderTiny, DDIMScheduler, DPMSolverMultistepScheduler, HeunDiscreteScheduler, LCMScheduler, LMSDiscreteScheduler, PNDMScheduler, StableDiffusionImg2ImgPipeline, UNet2DConditionModel, ) from diffusers.utils.testing_utils import ( enable_full_determinism, floats_tensor, is_torch_compile, load_image, load_numpy, nightly, require_torch_2, require_torch_gpu, run_test_in_subprocess, skip_mps, slow, torch_device, ) from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, TEXT_TO_IMAGE_CALLBACK_CFG_PARAMS, ) from ..test_pipelines_common import ( IPAdapterTesterMixin, PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, ) enable_full_determinism() # Will be run via run_test_in_subprocess def _test_img2img_compile(in_queue, out_queue, timeout): error = None try: inputs = in_queue.get(timeout=timeout) torch_device = inputs.pop("torch_device") seed = inputs.pop("seed") inputs["generator"] = torch.Generator(device=torch_device).manual_seed(seed) pipe = StableDiffusionImg2ImgPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", safety_checker=None) pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config) pipe.unet.set_default_attn_processor() pipe.to(torch_device) pipe.set_progress_bar_config(disable=None) pipe.unet.to(memory_format=torch.channels_last) pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True) image = pipe(**inputs).images image_slice = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 768, 3) expected_slice = np.array([0.0606, 0.0570, 0.0805, 0.0579, 0.0628, 0.0623, 0.0843, 0.1115, 0.0806]) assert np.abs(expected_slice - image_slice).max() < 1e-3 except Exception: error = f"{traceback.format_exc()}" results = {"error": error} out_queue.put(results, timeout=timeout) out_queue.join() class StableDiffusionImg2ImgPipelineFastTests( IPAdapterTesterMixin, PipelineLatentTesterMixin, PipelineKarrasSchedulerTesterMixin, PipelineTesterMixin, unittest.TestCase, ): pipeline_class = StableDiffusionImg2ImgPipeline params = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"} required_optional_params = PipelineTesterMixin.required_optional_params - {"latents"} batch_params = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS image_params = IMAGE_TO_IMAGE_IMAGE_PARAMS image_latents_params = IMAGE_TO_IMAGE_IMAGE_PARAMS callback_cfg_params = TEXT_TO_IMAGE_CALLBACK_CFG_PARAMS def get_dummy_components(self, time_cond_proj_dim=None): torch.manual_seed(0) unet = UNet2DConditionModel( block_out_channels=(32, 64), layers_per_block=2, time_cond_proj_dim=time_cond_proj_dim, sample_size=32, in_channels=4, out_channels=4, down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"), up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"), cross_attention_dim=32, ) scheduler = PNDMScheduler(skip_prk_steps=True) torch.manual_seed(0) vae = AutoencoderKL( block_out_channels=[32, 64], in_channels=3, out_channels=3, down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"], up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"], latent_channels=4, ) torch.manual_seed(0) text_encoder_config = CLIPTextConfig( bos_token_id=0, eos_token_id=2, hidden_size=32, intermediate_size=37, layer_norm_eps=1e-05, num_attention_heads=4, num_hidden_layers=5, pad_token_id=1, vocab_size=1000, ) text_encoder = CLIPTextModel(text_encoder_config) tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip") components = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, "safety_checker": None, "feature_extractor": None, "image_encoder": None, } return components def get_dummy_tiny_autoencoder(self): return AutoencoderTiny(in_channels=3, out_channels=3, latent_channels=4) def get_dummy_inputs(self, device, seed=0): image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device) image = image / 2 + 0.5 if str(device).startswith("mps"): generator = torch.manual_seed(seed) else: generator = torch.Generator(device=device).manual_seed(seed) inputs = { "prompt": "A painting of a squirrel eating a burger", "image": image, "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "np", } return inputs def test_stable_diffusion_img2img_default_case(self): device = "cpu" # ensure determinism for the device-dependent torch.Generator components = self.get_dummy_components() sd_pipe = StableDiffusionImg2ImgPipeline(**components) sd_pipe = sd_pipe.to(device) sd_pipe.set_progress_bar_config(disable=None) inputs = self.get_dummy_inputs(device) image = sd_pipe(**inputs).images image_slice = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) expected_slice = np.array([0.4555, 0.3216, 0.4049, 0.4620, 0.4618, 0.4126, 0.4122, 0.4629, 0.4579]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3 def test_stable_diffusion_img2img_default_case_lcm(self): device = "cpu" # ensure determinism for the device-dependent torch.Generator components = self.get_dummy_components(time_cond_proj_dim=256) sd_pipe = StableDiffusionImg2ImgPipeline(**components) sd_pipe.scheduler = LCMScheduler.from_config(sd_pipe.scheduler.config) sd_pipe = sd_pipe.to(device) sd_pipe.set_progress_bar_config(disable=None) inputs = self.get_dummy_inputs(device) image = sd_pipe(**inputs).images image_slice = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) expected_slice = np.array([0.5709, 0.4614, 0.4587, 0.5978, 0.5298, 0.6910, 0.6240, 0.5212, 0.5454]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3 def test_stable_diffusion_img2img_default_case_lcm_custom_timesteps(self): device = "cpu" # ensure determinism for the device-dependent torch.Generator components = self.get_dummy_components(time_cond_proj_dim=256) sd_pipe = StableDiffusionImg2ImgPipeline(**components) sd_pipe.scheduler = LCMScheduler.from_config(sd_pipe.scheduler.config) sd_pipe = sd_pipe.to(device) sd_pipe.set_progress_bar_config(disable=None) inputs = self.get_dummy_inputs(device) del inputs["num_inference_steps"] inputs["timesteps"] = [999, 499] image = sd_pipe(**inputs).images image_slice = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) expected_slice = np.array([0.5709, 0.4614, 0.4587, 0.5978, 0.5298, 0.6910, 0.6240, 0.5212, 0.5454]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3 def test_stable_diffusion_img2img_negative_prompt(self): device = "cpu" # ensure determinism for the device-dependent torch.Generator components = self.get_dummy_components() sd_pipe = StableDiffusionImg2ImgPipeline(**components) sd_pipe = sd_pipe.to(device) sd_pipe.set_progress_bar_config(disable=None) inputs = self.get_dummy_inputs(device) negative_prompt = "french fries" output = sd_pipe(**inputs, negative_prompt=negative_prompt) image = output.images image_slice = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) expected_slice = np.array([0.4593, 0.3408, 0.4232, 0.4749, 0.4476, 0.4115, 0.4357, 0.4733, 0.4663]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3 def test_ip_adapter_single(self): expected_pipe_slice = None if torch_device == "cpu": expected_pipe_slice = np.array([0.4932, 0.5092, 0.5135, 0.5517, 0.5626, 0.6621, 0.6490, 0.5021, 0.5441]) return super().test_ip_adapter_single(expected_pipe_slice=expected_pipe_slice) def test_stable_diffusion_img2img_multiple_init_images(self): device = "cpu" # ensure determinism for the device-dependent torch.Generator components = self.get_dummy_components() sd_pipe = StableDiffusionImg2ImgPipeline(**components) sd_pipe = sd_pipe.to(device) sd_pipe.set_progress_bar_config(disable=None) inputs = self.get_dummy_inputs(device) inputs["prompt"] = [inputs["prompt"]] * 2 inputs["image"] = inputs["image"].repeat(2, 1, 1, 1) image = sd_pipe(**inputs).images image_slice = image[-1, -3:, -3:, -1] assert image.shape == (2, 32, 32, 3) expected_slice = np.array([0.4241, 0.5576, 0.5711, 0.4792, 0.4311, 0.5952, 0.5827, 0.5138, 0.5109]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3 def test_stable_diffusion_img2img_k_lms(self): device = "cpu" # ensure determinism for the device-dependent torch.Generator components = self.get_dummy_components() components["scheduler"] = LMSDiscreteScheduler( beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear" ) sd_pipe = StableDiffusionImg2ImgPipeline(**components) sd_pipe = sd_pipe.to(device) sd_pipe.set_progress_bar_config(disable=None) inputs = self.get_dummy_inputs(device) image = sd_pipe(**inputs).images image_slice = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) expected_slice = np.array([0.4398, 0.4949, 0.4337, 0.6580, 0.5555, 0.4338, 0.5769, 0.5955, 0.5175]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3 def test_stable_diffusion_img2img_tiny_autoencoder(self): device = "cpu" # ensure determinism for the device-dependent torch.Generator components = self.get_dummy_components() sd_pipe = StableDiffusionImg2ImgPipeline(**components) sd_pipe.vae = self.get_dummy_tiny_autoencoder() sd_pipe = sd_pipe.to(device) sd_pipe.set_progress_bar_config(disable=None) inputs = self.get_dummy_inputs(device) image = sd_pipe(**inputs).images image_slice = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) expected_slice = np.array([0.00669, 0.00669, 0.0, 0.00693, 0.00858, 0.0, 0.00567, 0.00515, 0.00125]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3 @skip_mps def test_save_load_local(self): return super().test_save_load_local() @skip_mps def test_dict_tuple_outputs_equivalent(self): return super().test_dict_tuple_outputs_equivalent() @skip_mps def test_save_load_optional_components(self): return super().test_save_load_optional_components() @skip_mps def test_attention_slicing_forward_pass(self): return super().test_attention_slicing_forward_pass(expected_max_diff=5e-3) def test_inference_batch_single_identical(self): super().test_inference_batch_single_identical(expected_max_diff=3e-3) def test_float16_inference(self): super().test_float16_inference(expected_max_diff=5e-1) def test_pipeline_interrupt(self): components = self.get_dummy_components() sd_pipe = StableDiffusionImg2ImgPipeline(**components) sd_pipe = sd_pipe.to(torch_device) sd_pipe.set_progress_bar_config(disable=None) inputs = self.get_dummy_inputs(torch_device) prompt = "hey" num_inference_steps = 3 # store intermediate latents from the generation process class PipelineState: def __init__(self): self.state = [] def apply(self, pipe, i, t, callback_kwargs): self.state.append(callback_kwargs["latents"]) return callback_kwargs pipe_state = PipelineState() sd_pipe( prompt, image=inputs["image"], num_inference_steps=num_inference_steps, output_type="np", generator=torch.Generator("cpu").manual_seed(0), callback_on_step_end=pipe_state.apply, ).images # interrupt generation at step index interrupt_step_idx = 1 def callback_on_step_end(pipe, i, t, callback_kwargs): if i == interrupt_step_idx: pipe._interrupt = True return callback_kwargs output_interrupted = sd_pipe( prompt, image=inputs["image"], num_inference_steps=num_inference_steps, output_type="latent", generator=torch.Generator("cpu").manual_seed(0), callback_on_step_end=callback_on_step_end, ).images # fetch intermediate latents at the interrupted step # from the completed generation process intermediate_latent = pipe_state.state[interrupt_step_idx] # compare the intermediate latent to the output of the interrupted process # they should be the same assert torch.allclose(intermediate_latent, output_interrupted, atol=1e-4) @slow @require_torch_gpu class StableDiffusionImg2ImgPipelineSlowTests(unittest.TestCase): def setUp(self): super().setUp() gc.collect() torch.cuda.empty_cache() def tearDown(self): super().tearDown() gc.collect() torch.cuda.empty_cache() def get_inputs(self, device, generator_device="cpu", dtype=torch.float32, seed=0): generator = torch.Generator(device=generator_device).manual_seed(seed) init_image = load_image( "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main" "/stable_diffusion_img2img/sketch-mountains-input.png" ) inputs = { "prompt": "a fantasy landscape, concept art, high resolution", "image": init_image, "generator": generator, "num_inference_steps": 3, "strength": 0.75, "guidance_scale": 7.5, "output_type": "np", } return inputs def test_stable_diffusion_img2img_default(self): pipe = StableDiffusionImg2ImgPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", safety_checker=None) pipe.to(torch_device) pipe.set_progress_bar_config(disable=None) pipe.enable_attention_slicing() inputs = self.get_inputs(torch_device) image = pipe(**inputs).images image_slice = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 768, 3) expected_slice = np.array([0.4300, 0.4662, 0.4930, 0.3990, 0.4307, 0.4525, 0.3719, 0.4064, 0.3923]) assert np.abs(expected_slice - image_slice).max() < 1e-3 def test_stable_diffusion_img2img_k_lms(self): pipe = StableDiffusionImg2ImgPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", safety_checker=None) pipe.scheduler = LMSDiscreteScheduler.from_config(pipe.scheduler.config) pipe.to(torch_device) pipe.set_progress_bar_config(disable=None) pipe.enable_attention_slicing() inputs = self.get_inputs(torch_device) image = pipe(**inputs).images image_slice = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 768, 3) expected_slice = np.array([0.0389, 0.0346, 0.0415, 0.0290, 0.0218, 0.0210, 0.0408, 0.0567, 0.0271]) assert np.abs(expected_slice - image_slice).max() < 1e-3 def test_stable_diffusion_img2img_ddim(self): pipe = StableDiffusionImg2ImgPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", safety_checker=None) pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config) pipe.to(torch_device) pipe.set_progress_bar_config(disable=None) pipe.enable_attention_slicing() inputs = self.get_inputs(torch_device) image = pipe(**inputs).images image_slice = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 768, 3) expected_slice = np.array([0.0593, 0.0607, 0.0851, 0.0582, 0.0636, 0.0721, 0.0751, 0.0981, 0.0781]) assert np.abs(expected_slice - image_slice).max() < 1e-3 def test_stable_diffusion_img2img_intermediate_state(self): number_of_steps = 0 def callback_fn(step: int, timestep: int, latents: torch.Tensor) -> None: callback_fn.has_been_called = True nonlocal number_of_steps number_of_steps += 1 if step == 1: latents = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 96) latents_slice = latents[0, -3:, -3:, -1] expected_slice = np.array([-0.4958, 0.5107, 1.1045, 2.7539, 4.6680, 3.8320, 1.5049, 1.8633, 2.6523]) assert np.abs(latents_slice.flatten() - expected_slice).max() < 5e-2 elif step == 2: latents = latents.detach().cpu().numpy() assert latents.shape == (1, 4, 64, 96) latents_slice = latents[0, -3:, -3:, -1] expected_slice = np.array([-0.4956, 0.5078, 1.0918, 2.7520, 4.6484, 3.8125, 1.5146, 1.8633, 2.6367]) assert np.abs(latents_slice.flatten() - expected_slice).max() < 5e-2 callback_fn.has_been_called = False pipe = StableDiffusionImg2ImgPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4", safety_checker=None, torch_dtype=torch.float16 ) pipe = pipe.to(torch_device) pipe.set_progress_bar_config(disable=None) pipe.enable_attention_slicing() inputs = self.get_inputs(torch_device, dtype=torch.float16) pipe(**inputs, callback=callback_fn, callback_steps=1) assert callback_fn.has_been_called assert number_of_steps == 2 def test_stable_diffusion_pipeline_with_sequential_cpu_offloading(self): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() pipe = StableDiffusionImg2ImgPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4", safety_checker=None, torch_dtype=torch.float16 ) pipe.set_progress_bar_config(disable=None) pipe.enable_attention_slicing(1) pipe.enable_sequential_cpu_offload() inputs = self.get_inputs(torch_device, dtype=torch.float16) _ = pipe(**inputs) mem_bytes = torch.cuda.max_memory_allocated() # make sure that less than 2.2 GB is allocated assert mem_bytes < 2.2 * 10**9 def test_stable_diffusion_pipeline_with_model_offloading(self): torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() inputs = self.get_inputs(torch_device, dtype=torch.float16) # Normal inference pipe = StableDiffusionImg2ImgPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4", safety_checker=None, torch_dtype=torch.float16, ) pipe.to(torch_device) pipe.set_progress_bar_config(disable=None) pipe(**inputs) mem_bytes = torch.cuda.max_memory_allocated() # With model offloading # Reload but don't move to cuda pipe = StableDiffusionImg2ImgPipeline.from_pretrained( "CompVis/stable-diffusion-v1-4", safety_checker=None, torch_dtype=torch.float16, ) torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() pipe.enable_model_cpu_offload() pipe.set_progress_bar_config(disable=None) _ = pipe(**inputs) mem_bytes_offloaded = torch.cuda.max_memory_allocated() assert mem_bytes_offloaded < mem_bytes for module in pipe.text_encoder, pipe.unet, pipe.vae: assert module.device == torch.device("cpu") def test_img2img_2nd_order(self): sd_pipe = StableDiffusionImg2ImgPipeline.from_pretrained("runwayml/stable-diffusion-v1-5") sd_pipe.scheduler = HeunDiscreteScheduler.from_config(sd_pipe.scheduler.config) sd_pipe.to(torch_device) sd_pipe.set_progress_bar_config(disable=None) inputs = self.get_inputs(torch_device) inputs["num_inference_steps"] = 10 inputs["strength"] = 0.75 image = sd_pipe(**inputs).images[0] expected_image = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/img2img_heun.npy" ) max_diff = np.abs(expected_image - image).max() assert max_diff < 5e-2 inputs = self.get_inputs(torch_device) inputs["num_inference_steps"] = 11 inputs["strength"] = 0.75 image_other = sd_pipe(**inputs).images[0] mean_diff = np.abs(image - image_other).mean() # images should be very similar assert mean_diff < 5e-2 def test_stable_diffusion_img2img_pipeline_multiple_of_8(self): init_image = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/img2img/sketch-mountains-input.jpg" ) # resize to resolution that is divisible by 8 but not 16 or 32 init_image = init_image.resize((760, 504)) model_id = "CompVis/stable-diffusion-v1-4" pipe = StableDiffusionImg2ImgPipeline.from_pretrained( model_id, safety_checker=None, ) pipe.to(torch_device) pipe.set_progress_bar_config(disable=None) pipe.enable_attention_slicing() prompt = "A fantasy landscape, trending on artstation" generator = torch.manual_seed(0) output = pipe( prompt=prompt, image=init_image, strength=0.75, guidance_scale=7.5, generator=generator, output_type="np", ) image = output.images[0] image_slice = image[255:258, 383:386, -1] assert image.shape == (504, 760, 3) expected_slice = np.array([0.9393, 0.9500, 0.9399, 0.9438, 0.9458, 0.9400, 0.9455, 0.9414, 0.9423]) assert np.abs(image_slice.flatten() - expected_slice).max() < 5e-3 def test_img2img_safety_checker_works(self): sd_pipe = StableDiffusionImg2ImgPipeline.from_pretrained("runwayml/stable-diffusion-v1-5") sd_pipe.to(torch_device) sd_pipe.set_progress_bar_config(disable=None) inputs = self.get_inputs(torch_device) inputs["num_inference_steps"] = 20 # make sure the safety checker is activated inputs["prompt"] = "naked, sex, porn" out = sd_pipe(**inputs) assert out.nsfw_content_detected[0], f"Safety checker should work for prompt: {inputs['prompt']}" assert np.abs(out.images[0]).sum() < 1e-5 # should be all zeros @is_torch_compile @require_torch_2 def test_img2img_compile(self): seed = 0 inputs = self.get_inputs(torch_device, seed=seed) # Can't pickle a Generator object del inputs["generator"] inputs["torch_device"] = torch_device inputs["seed"] = seed run_test_in_subprocess(test_case=self, target_func=_test_img2img_compile, inputs=inputs) @nightly @require_torch_gpu class StableDiffusionImg2ImgPipelineNightlyTests(unittest.TestCase): def setUp(self): super().setUp() gc.collect() torch.cuda.empty_cache() def tearDown(self): super().tearDown() gc.collect() torch.cuda.empty_cache() def get_inputs(self, device, generator_device="cpu", dtype=torch.float32, seed=0): generator = torch.Generator(device=generator_device).manual_seed(seed) init_image = load_image( "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main" "/stable_diffusion_img2img/sketch-mountains-input.png" ) inputs = { "prompt": "a fantasy landscape, concept art, high resolution", "image": init_image, "generator": generator, "num_inference_steps": 50, "strength": 0.75, "guidance_scale": 7.5, "output_type": "np", } return inputs def test_img2img_pndm(self): sd_pipe = StableDiffusionImg2ImgPipeline.from_pretrained("runwayml/stable-diffusion-v1-5") sd_pipe.to(torch_device) sd_pipe.set_progress_bar_config(disable=None) inputs = self.get_inputs(torch_device) image = sd_pipe(**inputs).images[0] expected_image = load_numpy( "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main" "/stable_diffusion_img2img/stable_diffusion_1_5_pndm.npy" ) max_diff = np.abs(expected_image - image).max() assert max_diff < 1e-3 def test_img2img_ddim(self): sd_pipe = StableDiffusionImg2ImgPipeline.from_pretrained("runwayml/stable-diffusion-v1-5") sd_pipe.scheduler = DDIMScheduler.from_config(sd_pipe.scheduler.config) sd_pipe.to(torch_device) sd_pipe.set_progress_bar_config(disable=None) inputs = self.get_inputs(torch_device) image = sd_pipe(**inputs).images[0] expected_image = load_numpy( "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main" "/stable_diffusion_img2img/stable_diffusion_1_5_ddim.npy" ) max_diff = np.abs(expected_image - image).max() assert max_diff < 1e-3 def test_img2img_lms(self): sd_pipe = StableDiffusionImg2ImgPipeline.from_pretrained("runwayml/stable-diffusion-v1-5") sd_pipe.scheduler = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config) sd_pipe.to(torch_device) sd_pipe.set_progress_bar_config(disable=None) inputs = self.get_inputs(torch_device) image = sd_pipe(**inputs).images[0] expected_image = load_numpy( "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main" "/stable_diffusion_img2img/stable_diffusion_1_5_lms.npy" ) max_diff = np.abs(expected_image - image).max() assert max_diff < 1e-3 def test_img2img_dpm(self): sd_pipe = StableDiffusionImg2ImgPipeline.from_pretrained("runwayml/stable-diffusion-v1-5") sd_pipe.scheduler = DPMSolverMultistepScheduler.from_config(sd_pipe.scheduler.config) sd_pipe.to(torch_device) sd_pipe.set_progress_bar_config(disable=None) inputs = self.get_inputs(torch_device) inputs["num_inference_steps"] = 30 image = sd_pipe(**inputs).images[0] expected_image = load_numpy( "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main" "/stable_diffusion_img2img/stable_diffusion_1_5_dpm.npy" ) max_diff = np.abs(expected_image - image).max() assert max_diff < 1e-3
diffusers/tests/pipelines/stable_diffusion/test_stable_diffusion_img2img.py/0
{ "file_path": "diffusers/tests/pipelines/stable_diffusion/test_stable_diffusion_img2img.py", "repo_id": "diffusers", "token_count": 13393 }
155
import gc import random import unittest import numpy as np import torch from transformers import AutoTokenizer, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, T5EncoderModel from diffusers import ( AutoencoderKL, FlowMatchEulerDiscreteScheduler, SD3Transformer2DModel, StableDiffusion3Img2ImgPipeline, ) from diffusers.utils import load_image from diffusers.utils.testing_utils import ( floats_tensor, numpy_cosine_similarity_distance, require_torch_gpu, slow, torch_device, ) from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin class StableDiffusion3Img2ImgPipelineFastTests(PipelineLatentTesterMixin, unittest.TestCase, PipelineTesterMixin): pipeline_class = StableDiffusion3Img2ImgPipeline params = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"} required_optional_params = PipelineTesterMixin.required_optional_params batch_params = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS image_params = IMAGE_TO_IMAGE_IMAGE_PARAMS image_latents_params = IMAGE_TO_IMAGE_IMAGE_PARAMS def get_dummy_components(self): torch.manual_seed(0) transformer = SD3Transformer2DModel( sample_size=32, patch_size=1, in_channels=4, num_layers=1, attention_head_dim=8, num_attention_heads=4, joint_attention_dim=32, caption_projection_dim=32, pooled_projection_dim=64, out_channels=4, ) clip_text_encoder_config = CLIPTextConfig( bos_token_id=0, eos_token_id=2, hidden_size=32, intermediate_size=37, layer_norm_eps=1e-05, num_attention_heads=4, num_hidden_layers=5, pad_token_id=1, vocab_size=1000, hidden_act="gelu", projection_dim=32, ) torch.manual_seed(0) text_encoder = CLIPTextModelWithProjection(clip_text_encoder_config) torch.manual_seed(0) text_encoder_2 = CLIPTextModelWithProjection(clip_text_encoder_config) text_encoder_3 = T5EncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5") tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip") tokenizer_2 = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip") tokenizer_3 = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5") torch.manual_seed(0) vae = AutoencoderKL( sample_size=32, in_channels=3, out_channels=3, block_out_channels=(4,), layers_per_block=1, latent_channels=4, norm_num_groups=1, use_quant_conv=False, use_post_quant_conv=False, shift_factor=0.0609, scaling_factor=1.5035, ) scheduler = FlowMatchEulerDiscreteScheduler() return { "scheduler": scheduler, "text_encoder": text_encoder, "text_encoder_2": text_encoder_2, "text_encoder_3": text_encoder_3, "tokenizer": tokenizer, "tokenizer_2": tokenizer_2, "tokenizer_3": tokenizer_3, "transformer": transformer, "vae": vae, } def get_dummy_inputs(self, device, seed=0): image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device) if str(device).startswith("mps"): generator = torch.manual_seed(seed) else: generator = torch.Generator(device="cpu").manual_seed(seed) inputs = { "prompt": "A painting of a squirrel eating a burger", "image": image, "generator": generator, "num_inference_steps": 2, "guidance_scale": 5.0, "output_type": "np", "strength": 0.8, } return inputs def test_stable_diffusion_3_img2img_different_prompts(self): pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device) inputs = self.get_dummy_inputs(torch_device) output_same_prompt = pipe(**inputs).images[0] inputs = self.get_dummy_inputs(torch_device) inputs["prompt_2"] = "a different prompt" inputs["prompt_3"] = "another different prompt" output_different_prompts = pipe(**inputs).images[0] max_diff = np.abs(output_same_prompt - output_different_prompts).max() # Outputs should be different here assert max_diff > 1e-2 def test_stable_diffusion_3_img2img_different_negative_prompts(self): pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device) inputs = self.get_dummy_inputs(torch_device) output_same_prompt = pipe(**inputs).images[0] inputs = self.get_dummy_inputs(torch_device) inputs["negative_prompt_2"] = "deformed" inputs["negative_prompt_3"] = "blurry" output_different_prompts = pipe(**inputs).images[0] max_diff = np.abs(output_same_prompt - output_different_prompts).max() # Outputs should be different here assert max_diff > 1e-2 def test_stable_diffusion_3_img2img_prompt_embeds(self): pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device) inputs = self.get_dummy_inputs(torch_device) output_with_prompt = pipe(**inputs).images[0] inputs = self.get_dummy_inputs(torch_device) prompt = inputs.pop("prompt") do_classifier_free_guidance = inputs["guidance_scale"] > 1 ( prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds, ) = pipe.encode_prompt( prompt, prompt_2=None, prompt_3=None, do_classifier_free_guidance=do_classifier_free_guidance, device=torch_device, ) output_with_embeds = pipe( prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds, pooled_prompt_embeds=pooled_prompt_embeds, negative_pooled_prompt_embeds=negative_pooled_prompt_embeds, **inputs, ).images[0] max_diff = np.abs(output_with_prompt - output_with_embeds).max() assert max_diff < 1e-4 def test_multi_vae(self): pass @slow @require_torch_gpu class StableDiffusion3Img2ImgPipelineSlowTests(unittest.TestCase): pipeline_class = StableDiffusion3Img2ImgPipeline repo_id = "stabilityai/stable-diffusion-3-medium-diffusers" def setUp(self): super().setUp() gc.collect() torch.cuda.empty_cache() def tearDown(self): super().tearDown() gc.collect() torch.cuda.empty_cache() def get_inputs(self, device, seed=0): init_image = load_image( "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main" "/stable_diffusion_img2img/sketch-mountains-input.png" ) if str(device).startswith("mps"): generator = torch.manual_seed(seed) else: generator = torch.Generator(device="cpu").manual_seed(seed) return { "prompt": "A photo of a cat", "num_inference_steps": 2, "guidance_scale": 5.0, "output_type": "np", "generator": generator, "image": init_image, } def test_sd3_img2img_inference(self): pipe = self.pipeline_class.from_pretrained(self.repo_id, torch_dtype=torch.float16) pipe.enable_model_cpu_offload() inputs = self.get_inputs(torch_device) image = pipe(**inputs).images[0] image_slice = image[0, :10, :10] expected_slice = np.array( [ [0.50097656, 0.44726562, 0.40429688], [0.5048828, 0.45703125, 0.38110352], [0.4987793, 0.45141602, 0.38134766], [0.49682617, 0.45336914, 0.38354492], [0.49804688, 0.4555664, 0.39379883], [0.5083008, 0.4645996, 0.40039062], [0.50341797, 0.46240234, 0.39770508], [0.49926758, 0.4572754, 0.39575195], [0.50634766, 0.46435547, 0.39794922], [0.50341797, 0.4572754, 0.39746094], ], dtype=np.float32, ) max_diff = numpy_cosine_similarity_distance(expected_slice.flatten(), image_slice.flatten()) assert max_diff < 1e-4, f"Outputs are not close enough, got {image_slice}"
diffusers/tests/pipelines/stable_diffusion_3/test_pipeline_stable_diffusion_3_img2img.py/0
{ "file_path": "diffusers/tests/pipelines/stable_diffusion_3/test_pipeline_stable_diffusion_3_img2img.py", "repo_id": "diffusers", "token_count": 4397 }
156
import unittest from diffusers.pipelines.pipeline_utils import is_safetensors_compatible class IsSafetensorsCompatibleTests(unittest.TestCase): def test_all_is_compatible(self): filenames = [ "safety_checker/pytorch_model.bin", "safety_checker/model.safetensors", "vae/diffusion_pytorch_model.bin", "vae/diffusion_pytorch_model.safetensors", "text_encoder/pytorch_model.bin", "text_encoder/model.safetensors", "unet/diffusion_pytorch_model.bin", "unet/diffusion_pytorch_model.safetensors", ] self.assertTrue(is_safetensors_compatible(filenames)) def test_diffusers_model_is_compatible(self): filenames = [ "unet/diffusion_pytorch_model.bin", "unet/diffusion_pytorch_model.safetensors", ] self.assertTrue(is_safetensors_compatible(filenames)) def test_diffusers_model_is_not_compatible(self): filenames = [ "safety_checker/pytorch_model.bin", "safety_checker/model.safetensors", "vae/diffusion_pytorch_model.bin", "vae/diffusion_pytorch_model.safetensors", "text_encoder/pytorch_model.bin", "text_encoder/model.safetensors", "unet/diffusion_pytorch_model.bin", # Removed: 'unet/diffusion_pytorch_model.safetensors', ] self.assertFalse(is_safetensors_compatible(filenames)) def test_transformer_model_is_compatible(self): filenames = [ "text_encoder/pytorch_model.bin", "text_encoder/model.safetensors", ] self.assertTrue(is_safetensors_compatible(filenames)) def test_transformer_model_is_not_compatible(self): filenames = [ "safety_checker/pytorch_model.bin", "safety_checker/model.safetensors", "vae/diffusion_pytorch_model.bin", "vae/diffusion_pytorch_model.safetensors", "text_encoder/pytorch_model.bin", # Removed: 'text_encoder/model.safetensors', "unet/diffusion_pytorch_model.bin", "unet/diffusion_pytorch_model.safetensors", ] self.assertFalse(is_safetensors_compatible(filenames)) def test_all_is_compatible_variant(self): filenames = [ "safety_checker/pytorch_model.fp16.bin", "safety_checker/model.fp16.safetensors", "vae/diffusion_pytorch_model.fp16.bin", "vae/diffusion_pytorch_model.fp16.safetensors", "text_encoder/pytorch_model.fp16.bin", "text_encoder/model.fp16.safetensors", "unet/diffusion_pytorch_model.fp16.bin", "unet/diffusion_pytorch_model.fp16.safetensors", ] self.assertTrue(is_safetensors_compatible(filenames)) def test_diffusers_model_is_compatible_variant(self): filenames = [ "unet/diffusion_pytorch_model.fp16.bin", "unet/diffusion_pytorch_model.fp16.safetensors", ] self.assertTrue(is_safetensors_compatible(filenames)) def test_diffusers_model_is_compatible_variant_mixed(self): filenames = [ "unet/diffusion_pytorch_model.bin", "unet/diffusion_pytorch_model.fp16.safetensors", ] self.assertTrue(is_safetensors_compatible(filenames)) def test_diffusers_model_is_not_compatible_variant(self): filenames = [ "safety_checker/pytorch_model.fp16.bin", "safety_checker/model.fp16.safetensors", "vae/diffusion_pytorch_model.fp16.bin", "vae/diffusion_pytorch_model.fp16.safetensors", "text_encoder/pytorch_model.fp16.bin", "text_encoder/model.fp16.safetensors", "unet/diffusion_pytorch_model.fp16.bin", # Removed: 'unet/diffusion_pytorch_model.fp16.safetensors', ] self.assertFalse(is_safetensors_compatible(filenames)) def test_transformer_model_is_compatible_variant(self): filenames = [ "text_encoder/pytorch_model.fp16.bin", "text_encoder/model.fp16.safetensors", ] self.assertTrue(is_safetensors_compatible(filenames)) def test_transformer_model_is_not_compatible_variant(self): filenames = [ "safety_checker/pytorch_model.fp16.bin", "safety_checker/model.fp16.safetensors", "vae/diffusion_pytorch_model.fp16.bin", "vae/diffusion_pytorch_model.fp16.safetensors", "text_encoder/pytorch_model.fp16.bin", "unet/diffusion_pytorch_model.fp16.bin", "unet/diffusion_pytorch_model.fp16.safetensors", ] self.assertFalse(is_safetensors_compatible(filenames)) def test_transformer_model_is_compatible_variant_extra_folder(self): filenames = [ "safety_checker/pytorch_model.fp16.bin", "safety_checker/model.fp16.safetensors", "vae/diffusion_pytorch_model.fp16.bin", "vae/diffusion_pytorch_model.fp16.safetensors", "text_encoder/pytorch_model.fp16.bin", "unet/diffusion_pytorch_model.fp16.bin", "unet/diffusion_pytorch_model.fp16.safetensors", ] self.assertTrue(is_safetensors_compatible(filenames, folder_names={"vae", "unet"})) def test_transformer_model_is_not_compatible_variant_extra_folder(self): filenames = [ "safety_checker/pytorch_model.fp16.bin", "safety_checker/model.fp16.safetensors", "vae/diffusion_pytorch_model.fp16.bin", "vae/diffusion_pytorch_model.fp16.safetensors", "text_encoder/pytorch_model.fp16.bin", "unet/diffusion_pytorch_model.fp16.bin", "unet/diffusion_pytorch_model.fp16.safetensors", ] self.assertFalse(is_safetensors_compatible(filenames, folder_names={"text_encoder"})) def test_transformers_is_compatible_sharded(self): filenames = [ "text_encoder/pytorch_model.bin", "text_encoder/model-00001-of-00002.safetensors", "text_encoder/model-00002-of-00002.safetensors", ] self.assertTrue(is_safetensors_compatible(filenames)) def test_transformers_is_compatible_variant_sharded(self): filenames = [ "text_encoder/pytorch_model.bin", "text_encoder/model.fp16-00001-of-00002.safetensors", "text_encoder/model.fp16-00001-of-00002.safetensors", ] self.assertTrue(is_safetensors_compatible(filenames)) def test_diffusers_is_compatible_sharded(self): filenames = [ "unet/diffusion_pytorch_model.bin", "unet/diffusion_pytorch_model-00001-of-00002.safetensors", "unet/diffusion_pytorch_model-00002-of-00002.safetensors", ] self.assertTrue(is_safetensors_compatible(filenames)) def test_diffusers_is_compatible_variant_sharded(self): filenames = [ "unet/diffusion_pytorch_model.bin", "unet/diffusion_pytorch_model.fp16-00001-of-00002.safetensors", "unet/diffusion_pytorch_model.fp16-00001-of-00002.safetensors", ] self.assertTrue(is_safetensors_compatible(filenames)) def test_diffusers_is_compatible_only_variants(self): filenames = [ "unet/diffusion_pytorch_model.fp16.safetensors", ] self.assertTrue(is_safetensors_compatible(filenames))
diffusers/tests/pipelines/test_pipeline_utils.py/0
{ "file_path": "diffusers/tests/pipelines/test_pipeline_utils.py", "repo_id": "diffusers", "token_count": 3793 }
157
import gc import random import traceback import unittest import numpy as np import torch from PIL import Image from transformers import ( CLIPImageProcessor, CLIPTextModel, CLIPTokenizer, CLIPVisionModelWithProjection, GPT2Tokenizer, ) from diffusers import ( AutoencoderKL, DPMSolverMultistepScheduler, UniDiffuserModel, UniDiffuserPipeline, UniDiffuserTextDecoder, ) from diffusers.utils.testing_utils import ( enable_full_determinism, floats_tensor, load_image, nightly, require_torch_2, require_torch_gpu, run_test_in_subprocess, torch_device, ) from diffusers.utils.torch_utils import randn_tensor from ..pipeline_params import ( IMAGE_TO_IMAGE_IMAGE_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() # Will be run via run_test_in_subprocess def _test_unidiffuser_compile(in_queue, out_queue, timeout): error = None try: inputs = in_queue.get(timeout=timeout) torch_device = inputs.pop("torch_device") seed = inputs.pop("seed") inputs["generator"] = torch.Generator(device=torch_device).manual_seed(seed) pipe = UniDiffuserPipeline.from_pretrained("thu-ml/unidiffuser-v1") # pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config) pipe = pipe.to(torch_device) pipe.unet.to(memory_format=torch.channels_last) pipe.unet = torch.compile(pipe.unet, mode="reduce-overhead", fullgraph=True) pipe.set_progress_bar_config(disable=None) image = pipe(**inputs).images image_slice = image[0, -3:, -3:, -1].flatten() assert image.shape == (1, 512, 512, 3) expected_slice = np.array([0.2402, 0.2375, 0.2285, 0.2378, 0.2407, 0.2263, 0.2354, 0.2307, 0.2520]) assert np.abs(image_slice - expected_slice).max() < 1e-1 except Exception: error = f"{traceback.format_exc()}" results = {"error": error} out_queue.put(results, timeout=timeout) out_queue.join() class UniDiffuserPipelineFastTests( PipelineTesterMixin, PipelineLatentTesterMixin, PipelineKarrasSchedulerTesterMixin, unittest.TestCase ): pipeline_class = UniDiffuserPipeline params = TEXT_GUIDED_IMAGE_VARIATION_PARAMS batch_params = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS image_params = IMAGE_TO_IMAGE_IMAGE_PARAMS # vae_latents, not latents, is the argument that corresponds to VAE latent inputs image_latents_params = frozenset(["vae_latents"]) def get_dummy_components(self): unet = UniDiffuserModel.from_pretrained( "hf-internal-testing/unidiffuser-diffusers-test", subfolder="unet", ) scheduler = DPMSolverMultistepScheduler( beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", solver_order=3, ) vae = AutoencoderKL.from_pretrained( "hf-internal-testing/unidiffuser-diffusers-test", subfolder="vae", ) text_encoder = CLIPTextModel.from_pretrained( "hf-internal-testing/unidiffuser-diffusers-test", subfolder="text_encoder", ) clip_tokenizer = CLIPTokenizer.from_pretrained( "hf-internal-testing/unidiffuser-diffusers-test", subfolder="clip_tokenizer", ) image_encoder = CLIPVisionModelWithProjection.from_pretrained( "hf-internal-testing/unidiffuser-diffusers-test", subfolder="image_encoder", ) # From the Stable Diffusion Image Variation pipeline tests clip_image_processor = CLIPImageProcessor(crop_size=32, size=32) # image_processor = CLIPImageProcessor.from_pretrained("hf-internal-testing/tiny-random-clip") text_tokenizer = GPT2Tokenizer.from_pretrained( "hf-internal-testing/unidiffuser-diffusers-test", subfolder="text_tokenizer", ) text_decoder = UniDiffuserTextDecoder.from_pretrained( "hf-internal-testing/unidiffuser-diffusers-test", subfolder="text_decoder", ) components = { "vae": vae, "text_encoder": text_encoder, "image_encoder": image_encoder, "clip_image_processor": clip_image_processor, "clip_tokenizer": clip_tokenizer, "text_decoder": text_decoder, "text_tokenizer": text_tokenizer, "unet": unet, "scheduler": scheduler, } return components def get_dummy_inputs(self, device, seed=0): image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device) image = image.cpu().permute(0, 2, 3, 1)[0] image = Image.fromarray(np.uint8(image)).convert("RGB") if str(device).startswith("mps"): generator = torch.manual_seed(seed) else: generator = torch.Generator(device=device).manual_seed(seed) inputs = { "prompt": "an elephant under the sea", "image": image, "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "np", } return inputs def get_fixed_latents(self, device, seed=0): if isinstance(device, str): device = torch.device(device) generator = torch.Generator(device=device).manual_seed(seed) # Hardcode the shapes for now. prompt_latents = randn_tensor((1, 77, 32), generator=generator, device=device, dtype=torch.float32) vae_latents = randn_tensor((1, 4, 16, 16), generator=generator, device=device, dtype=torch.float32) clip_latents = randn_tensor((1, 1, 32), generator=generator, device=device, dtype=torch.float32) latents = { "prompt_latents": prompt_latents, "vae_latents": vae_latents, "clip_latents": clip_latents, } return latents def get_dummy_inputs_with_latents(self, device, seed=0): # image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device) # image = image.cpu().permute(0, 2, 3, 1)[0] # image = Image.fromarray(np.uint8(image)).convert("RGB") image = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/unidiffuser/unidiffuser_example_image.jpg", ) image = image.resize((32, 32)) latents = self.get_fixed_latents(device, seed=seed) if str(device).startswith("mps"): generator = torch.manual_seed(seed) else: generator = torch.Generator(device=device).manual_seed(seed) inputs = { "prompt": "an elephant under the sea", "image": image, "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "np", "prompt_latents": latents.get("prompt_latents"), "vae_latents": latents.get("vae_latents"), "clip_latents": latents.get("clip_latents"), } return inputs def test_dict_tuple_outputs_equivalent(self): expected_slice = None if torch_device == "cpu": expected_slice = np.array([0.7489, 0.3722, 0.4475, 0.5630, 0.5923, 0.4992, 0.3936, 0.5844, 0.4975]) super().test_dict_tuple_outputs_equivalent(expected_slice=expected_slice) def test_unidiffuser_default_joint_v0(self): device = "cpu" # ensure determinism for the device-dependent torch.Generator components = self.get_dummy_components() unidiffuser_pipe = UniDiffuserPipeline(**components) unidiffuser_pipe = unidiffuser_pipe.to(device) unidiffuser_pipe.set_progress_bar_config(disable=None) # Set mode to 'joint' unidiffuser_pipe.set_joint_mode() assert unidiffuser_pipe.mode == "joint" # inputs = self.get_dummy_inputs(device) inputs = self.get_dummy_inputs_with_latents(device) # Delete prompt and image for joint inference. del inputs["prompt"] del inputs["image"] sample = unidiffuser_pipe(**inputs) image = sample.images text = sample.text assert image.shape == (1, 32, 32, 3) image_slice = image[0, -3:, -3:, -1] expected_img_slice = np.array([0.5760, 0.6270, 0.6571, 0.4965, 0.4638, 0.5663, 0.5254, 0.5068, 0.5716]) assert np.abs(image_slice.flatten() - expected_img_slice).max() < 1e-3 expected_text_prefix = " no no no " assert text[0][:10] == expected_text_prefix def test_unidiffuser_default_joint_no_cfg_v0(self): device = "cpu" # ensure determinism for the device-dependent torch.Generator components = self.get_dummy_components() unidiffuser_pipe = UniDiffuserPipeline(**components) unidiffuser_pipe = unidiffuser_pipe.to(device) unidiffuser_pipe.set_progress_bar_config(disable=None) # Set mode to 'joint' unidiffuser_pipe.set_joint_mode() assert unidiffuser_pipe.mode == "joint" # inputs = self.get_dummy_inputs(device) inputs = self.get_dummy_inputs_with_latents(device) # Delete prompt and image for joint inference. del inputs["prompt"] del inputs["image"] # Set guidance scale to 1.0 to turn off CFG inputs["guidance_scale"] = 1.0 sample = unidiffuser_pipe(**inputs) image = sample.images text = sample.text assert image.shape == (1, 32, 32, 3) image_slice = image[0, -3:, -3:, -1] expected_img_slice = np.array([0.5760, 0.6270, 0.6571, 0.4965, 0.4638, 0.5663, 0.5254, 0.5068, 0.5716]) assert np.abs(image_slice.flatten() - expected_img_slice).max() < 1e-3 expected_text_prefix = " no no no " assert text[0][:10] == expected_text_prefix def test_unidiffuser_default_text2img_v0(self): device = "cpu" # ensure determinism for the device-dependent torch.Generator components = self.get_dummy_components() unidiffuser_pipe = UniDiffuserPipeline(**components) unidiffuser_pipe = unidiffuser_pipe.to(device) unidiffuser_pipe.set_progress_bar_config(disable=None) # Set mode to 'text2img' unidiffuser_pipe.set_text_to_image_mode() assert unidiffuser_pipe.mode == "text2img" inputs = self.get_dummy_inputs_with_latents(device) # Delete image for text-conditioned image generation del inputs["image"] image = unidiffuser_pipe(**inputs).images assert image.shape == (1, 32, 32, 3) image_slice = image[0, -3:, -3:, -1] expected_slice = np.array([0.5758, 0.6269, 0.6570, 0.4967, 0.4639, 0.5664, 0.5257, 0.5067, 0.5715]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3 def test_unidiffuser_default_image_0(self): device = "cpu" # ensure determinism for the device-dependent torch.Generator components = self.get_dummy_components() unidiffuser_pipe = UniDiffuserPipeline(**components) unidiffuser_pipe = unidiffuser_pipe.to(device) unidiffuser_pipe.set_progress_bar_config(disable=None) # Set mode to 'img' unidiffuser_pipe.set_image_mode() assert unidiffuser_pipe.mode == "img" inputs = self.get_dummy_inputs(device) # Delete prompt and image for unconditional ("marginal") text generation. del inputs["prompt"] del inputs["image"] image = unidiffuser_pipe(**inputs).images assert image.shape == (1, 32, 32, 3) image_slice = image[0, -3:, -3:, -1] expected_slice = np.array([0.5760, 0.6270, 0.6571, 0.4966, 0.4638, 0.5663, 0.5254, 0.5068, 0.5715]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3 def test_unidiffuser_default_text_v0(self): device = "cpu" # ensure determinism for the device-dependent torch.Generator components = self.get_dummy_components() unidiffuser_pipe = UniDiffuserPipeline(**components) unidiffuser_pipe = unidiffuser_pipe.to(device) unidiffuser_pipe.set_progress_bar_config(disable=None) # Set mode to 'img' unidiffuser_pipe.set_text_mode() assert unidiffuser_pipe.mode == "text" inputs = self.get_dummy_inputs(device) # Delete prompt and image for unconditional ("marginal") text generation. del inputs["prompt"] del inputs["image"] text = unidiffuser_pipe(**inputs).text expected_text_prefix = " no no no " assert text[0][:10] == expected_text_prefix def test_unidiffuser_default_img2text_v0(self): device = "cpu" # ensure determinism for the device-dependent torch.Generator components = self.get_dummy_components() unidiffuser_pipe = UniDiffuserPipeline(**components) unidiffuser_pipe = unidiffuser_pipe.to(device) unidiffuser_pipe.set_progress_bar_config(disable=None) # Set mode to 'img2text' unidiffuser_pipe.set_image_to_text_mode() assert unidiffuser_pipe.mode == "img2text" inputs = self.get_dummy_inputs_with_latents(device) # Delete text for image-conditioned text generation del inputs["prompt"] text = unidiffuser_pipe(**inputs).text expected_text_prefix = " no no no " assert text[0][:10] == expected_text_prefix def test_unidiffuser_default_joint_v1(self): device = "cpu" # ensure determinism for the device-dependent torch.Generator unidiffuser_pipe = UniDiffuserPipeline.from_pretrained("hf-internal-testing/unidiffuser-test-v1") unidiffuser_pipe = unidiffuser_pipe.to(device) unidiffuser_pipe.set_progress_bar_config(disable=None) # Set mode to 'joint' unidiffuser_pipe.set_joint_mode() assert unidiffuser_pipe.mode == "joint" # inputs = self.get_dummy_inputs(device) inputs = self.get_dummy_inputs_with_latents(device) # Delete prompt and image for joint inference. del inputs["prompt"] del inputs["image"] inputs["data_type"] = 1 sample = unidiffuser_pipe(**inputs) image = sample.images text = sample.text assert image.shape == (1, 32, 32, 3) image_slice = image[0, -3:, -3:, -1] expected_img_slice = np.array([0.5760, 0.6270, 0.6571, 0.4965, 0.4638, 0.5663, 0.5254, 0.5068, 0.5716]) assert np.abs(image_slice.flatten() - expected_img_slice).max() < 1e-3 expected_text_prefix = " no no no " assert text[0][:10] == expected_text_prefix def test_unidiffuser_default_text2img_v1(self): device = "cpu" # ensure determinism for the device-dependent torch.Generator unidiffuser_pipe = UniDiffuserPipeline.from_pretrained("hf-internal-testing/unidiffuser-test-v1") unidiffuser_pipe = unidiffuser_pipe.to(device) unidiffuser_pipe.set_progress_bar_config(disable=None) # Set mode to 'text2img' unidiffuser_pipe.set_text_to_image_mode() assert unidiffuser_pipe.mode == "text2img" inputs = self.get_dummy_inputs_with_latents(device) # Delete image for text-conditioned image generation del inputs["image"] image = unidiffuser_pipe(**inputs).images assert image.shape == (1, 32, 32, 3) image_slice = image[0, -3:, -3:, -1] expected_slice = np.array([0.5758, 0.6269, 0.6570, 0.4967, 0.4639, 0.5664, 0.5257, 0.5067, 0.5715]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3 def test_unidiffuser_default_img2text_v1(self): device = "cpu" # ensure determinism for the device-dependent torch.Generator unidiffuser_pipe = UniDiffuserPipeline.from_pretrained("hf-internal-testing/unidiffuser-test-v1") unidiffuser_pipe = unidiffuser_pipe.to(device) unidiffuser_pipe.set_progress_bar_config(disable=None) # Set mode to 'img2text' unidiffuser_pipe.set_image_to_text_mode() assert unidiffuser_pipe.mode == "img2text" inputs = self.get_dummy_inputs_with_latents(device) # Delete text for image-conditioned text generation del inputs["prompt"] text = unidiffuser_pipe(**inputs).text expected_text_prefix = " no no no " assert text[0][:10] == expected_text_prefix def test_unidiffuser_text2img_multiple_images(self): device = "cpu" # ensure determinism for the device-dependent torch.Generator components = self.get_dummy_components() unidiffuser_pipe = UniDiffuserPipeline(**components) unidiffuser_pipe = unidiffuser_pipe.to(device) unidiffuser_pipe.set_progress_bar_config(disable=None) # Set mode to 'text2img' unidiffuser_pipe.set_text_to_image_mode() assert unidiffuser_pipe.mode == "text2img" inputs = self.get_dummy_inputs(device) # Delete image for text-conditioned image generation del inputs["image"] inputs["num_images_per_prompt"] = 2 inputs["num_prompts_per_image"] = 3 image = unidiffuser_pipe(**inputs).images assert image.shape == (2, 32, 32, 3) def test_unidiffuser_img2text_multiple_prompts(self): device = "cpu" # ensure determinism for the device-dependent torch.Generator components = self.get_dummy_components() unidiffuser_pipe = UniDiffuserPipeline(**components) unidiffuser_pipe = unidiffuser_pipe.to(device) unidiffuser_pipe.set_progress_bar_config(disable=None) # Set mode to 'img2text' unidiffuser_pipe.set_image_to_text_mode() assert unidiffuser_pipe.mode == "img2text" inputs = self.get_dummy_inputs(device) # Delete text for image-conditioned text generation del inputs["prompt"] inputs["num_images_per_prompt"] = 2 inputs["num_prompts_per_image"] = 3 text = unidiffuser_pipe(**inputs).text assert len(text) == 3 def test_unidiffuser_text2img_multiple_images_with_latents(self): device = "cpu" # ensure determinism for the device-dependent torch.Generator components = self.get_dummy_components() unidiffuser_pipe = UniDiffuserPipeline(**components) unidiffuser_pipe = unidiffuser_pipe.to(device) unidiffuser_pipe.set_progress_bar_config(disable=None) # Set mode to 'text2img' unidiffuser_pipe.set_text_to_image_mode() assert unidiffuser_pipe.mode == "text2img" inputs = self.get_dummy_inputs_with_latents(device) # Delete image for text-conditioned image generation del inputs["image"] inputs["num_images_per_prompt"] = 2 inputs["num_prompts_per_image"] = 3 image = unidiffuser_pipe(**inputs).images assert image.shape == (2, 32, 32, 3) def test_unidiffuser_img2text_multiple_prompts_with_latents(self): device = "cpu" # ensure determinism for the device-dependent torch.Generator components = self.get_dummy_components() unidiffuser_pipe = UniDiffuserPipeline(**components) unidiffuser_pipe = unidiffuser_pipe.to(device) unidiffuser_pipe.set_progress_bar_config(disable=None) # Set mode to 'img2text' unidiffuser_pipe.set_image_to_text_mode() assert unidiffuser_pipe.mode == "img2text" inputs = self.get_dummy_inputs_with_latents(device) # Delete text for image-conditioned text generation del inputs["prompt"] inputs["num_images_per_prompt"] = 2 inputs["num_prompts_per_image"] = 3 text = unidiffuser_pipe(**inputs).text assert len(text) == 3 def test_inference_batch_single_identical(self): super().test_inference_batch_single_identical(expected_max_diff=2e-4) @require_torch_gpu def test_unidiffuser_default_joint_v1_cuda_fp16(self): device = "cuda" unidiffuser_pipe = UniDiffuserPipeline.from_pretrained( "hf-internal-testing/unidiffuser-test-v1", torch_dtype=torch.float16 ) unidiffuser_pipe = unidiffuser_pipe.to(device) unidiffuser_pipe.set_progress_bar_config(disable=None) # Set mode to 'joint' unidiffuser_pipe.set_joint_mode() assert unidiffuser_pipe.mode == "joint" inputs = self.get_dummy_inputs_with_latents(device) # Delete prompt and image for joint inference. del inputs["prompt"] del inputs["image"] inputs["data_type"] = 1 sample = unidiffuser_pipe(**inputs) image = sample.images text = sample.text assert image.shape == (1, 32, 32, 3) image_slice = image[0, -3:, -3:, -1] expected_img_slice = np.array([0.5049, 0.5498, 0.5854, 0.3052, 0.4460, 0.6489, 0.5122, 0.4810, 0.6138]) assert np.abs(image_slice.flatten() - expected_img_slice).max() < 1e-3 expected_text_prefix = '" This This' assert text[0][: len(expected_text_prefix)] == expected_text_prefix @require_torch_gpu def test_unidiffuser_default_text2img_v1_cuda_fp16(self): device = "cuda" unidiffuser_pipe = UniDiffuserPipeline.from_pretrained( "hf-internal-testing/unidiffuser-test-v1", torch_dtype=torch.float16 ) unidiffuser_pipe = unidiffuser_pipe.to(device) unidiffuser_pipe.set_progress_bar_config(disable=None) # Set mode to 'text2img' unidiffuser_pipe.set_text_to_image_mode() assert unidiffuser_pipe.mode == "text2img" inputs = self.get_dummy_inputs_with_latents(device) # Delete prompt and image for joint inference. del inputs["image"] inputs["data_type"] = 1 sample = unidiffuser_pipe(**inputs) image = sample.images assert image.shape == (1, 32, 32, 3) image_slice = image[0, -3:, -3:, -1] expected_img_slice = np.array([0.5054, 0.5498, 0.5854, 0.3052, 0.4458, 0.6489, 0.5122, 0.4810, 0.6138]) assert np.abs(image_slice.flatten() - expected_img_slice).max() < 1e-3 @require_torch_gpu def test_unidiffuser_default_img2text_v1_cuda_fp16(self): device = "cuda" unidiffuser_pipe = UniDiffuserPipeline.from_pretrained( "hf-internal-testing/unidiffuser-test-v1", torch_dtype=torch.float16 ) unidiffuser_pipe = unidiffuser_pipe.to(device) unidiffuser_pipe.set_progress_bar_config(disable=None) # Set mode to 'img2text' unidiffuser_pipe.set_image_to_text_mode() assert unidiffuser_pipe.mode == "img2text" inputs = self.get_dummy_inputs_with_latents(device) # Delete prompt and image for joint inference. del inputs["prompt"] inputs["data_type"] = 1 text = unidiffuser_pipe(**inputs).text expected_text_prefix = '" This This' assert text[0][: len(expected_text_prefix)] == expected_text_prefix @nightly @require_torch_gpu class UniDiffuserPipelineSlowTests(unittest.TestCase): def setUp(self): super().setUp() gc.collect() torch.cuda.empty_cache() def tearDown(self): super().tearDown() gc.collect() torch.cuda.empty_cache() def get_inputs(self, device, seed=0, generate_latents=False): generator = torch.manual_seed(seed) image = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/unidiffuser/unidiffuser_example_image.jpg" ) inputs = { "prompt": "an elephant under the sea", "image": image, "generator": generator, "num_inference_steps": 3, "guidance_scale": 8.0, "output_type": "np", } if generate_latents: latents = self.get_fixed_latents(device, seed=seed) for latent_name, latent_tensor in latents.items(): inputs[latent_name] = latent_tensor return inputs def get_fixed_latents(self, device, seed=0): if isinstance(device, str): device = torch.device(device) latent_device = torch.device("cpu") generator = torch.Generator(device=latent_device).manual_seed(seed) # Hardcode the shapes for now. prompt_latents = randn_tensor((1, 77, 768), generator=generator, device=device, dtype=torch.float32) vae_latents = randn_tensor((1, 4, 64, 64), generator=generator, device=device, dtype=torch.float32) clip_latents = randn_tensor((1, 1, 512), generator=generator, device=device, dtype=torch.float32) # Move latents onto desired device. prompt_latents = prompt_latents.to(device) vae_latents = vae_latents.to(device) clip_latents = clip_latents.to(device) latents = { "prompt_latents": prompt_latents, "vae_latents": vae_latents, "clip_latents": clip_latents, } return latents def test_unidiffuser_default_joint_v1(self): pipe = UniDiffuserPipeline.from_pretrained("thu-ml/unidiffuser-v1") pipe.to(torch_device) pipe.set_progress_bar_config(disable=None) pipe.enable_attention_slicing() # inputs = self.get_dummy_inputs(device) inputs = self.get_inputs(device=torch_device, generate_latents=True) # Delete prompt and image for joint inference. del inputs["prompt"] del inputs["image"] sample = pipe(**inputs) image = sample.images text = sample.text assert image.shape == (1, 512, 512, 3) image_slice = image[0, -3:, -3:, -1] expected_img_slice = np.array([0.2402, 0.2375, 0.2285, 0.2378, 0.2407, 0.2263, 0.2354, 0.2307, 0.2520]) assert np.abs(image_slice.flatten() - expected_img_slice).max() < 1e-1 expected_text_prefix = "a living room" assert text[0][: len(expected_text_prefix)] == expected_text_prefix def test_unidiffuser_default_text2img_v1(self): pipe = UniDiffuserPipeline.from_pretrained("thu-ml/unidiffuser-v1") pipe.to(torch_device) pipe.set_progress_bar_config(disable=None) pipe.enable_attention_slicing() inputs = self.get_inputs(device=torch_device, generate_latents=True) del inputs["image"] sample = pipe(**inputs) image = sample.images assert image.shape == (1, 512, 512, 3) image_slice = image[0, -3:, -3:, -1] expected_slice = np.array([0.0242, 0.0103, 0.0022, 0.0129, 0.0000, 0.0090, 0.0376, 0.0508, 0.0005]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1 def test_unidiffuser_default_img2text_v1(self): pipe = UniDiffuserPipeline.from_pretrained("thu-ml/unidiffuser-v1") pipe.to(torch_device) pipe.set_progress_bar_config(disable=None) pipe.enable_attention_slicing() inputs = self.get_inputs(device=torch_device, generate_latents=True) del inputs["prompt"] sample = pipe(**inputs) text = sample.text expected_text_prefix = "An astronaut" assert text[0][: len(expected_text_prefix)] == expected_text_prefix @unittest.skip(reason="Skip torch.compile test to speed up the slow test suite.") @require_torch_2 def test_unidiffuser_compile(self, seed=0): inputs = self.get_inputs(torch_device, seed=seed, generate_latents=True) # Delete prompt and image for joint inference. del inputs["prompt"] del inputs["image"] # Can't pickle a Generator object del inputs["generator"] inputs["torch_device"] = torch_device inputs["seed"] = seed run_test_in_subprocess(test_case=self, target_func=_test_unidiffuser_compile, inputs=inputs) @nightly @require_torch_gpu class UniDiffuserPipelineNightlyTests(unittest.TestCase): def setUp(self): super().setUp() gc.collect() torch.cuda.empty_cache() def tearDown(self): super().tearDown() gc.collect() torch.cuda.empty_cache() def get_inputs(self, device, seed=0, generate_latents=False): generator = torch.manual_seed(seed) image = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/unidiffuser/unidiffuser_example_image.jpg" ) inputs = { "prompt": "an elephant under the sea", "image": image, "generator": generator, "num_inference_steps": 3, "guidance_scale": 8.0, "output_type": "np", } if generate_latents: latents = self.get_fixed_latents(device, seed=seed) for latent_name, latent_tensor in latents.items(): inputs[latent_name] = latent_tensor return inputs def get_fixed_latents(self, device, seed=0): if isinstance(device, str): device = torch.device(device) latent_device = torch.device("cpu") generator = torch.Generator(device=latent_device).manual_seed(seed) # Hardcode the shapes for now. prompt_latents = randn_tensor((1, 77, 768), generator=generator, device=device, dtype=torch.float32) vae_latents = randn_tensor((1, 4, 64, 64), generator=generator, device=device, dtype=torch.float32) clip_latents = randn_tensor((1, 1, 512), generator=generator, device=device, dtype=torch.float32) # Move latents onto desired device. prompt_latents = prompt_latents.to(device) vae_latents = vae_latents.to(device) clip_latents = clip_latents.to(device) latents = { "prompt_latents": prompt_latents, "vae_latents": vae_latents, "clip_latents": clip_latents, } return latents def test_unidiffuser_default_joint_v1_fp16(self): pipe = UniDiffuserPipeline.from_pretrained("thu-ml/unidiffuser-v1", torch_dtype=torch.float16) pipe.to(torch_device) pipe.set_progress_bar_config(disable=None) pipe.enable_attention_slicing() # inputs = self.get_dummy_inputs(device) inputs = self.get_inputs(device=torch_device, generate_latents=True) # Delete prompt and image for joint inference. del inputs["prompt"] del inputs["image"] sample = pipe(**inputs) image = sample.images text = sample.text assert image.shape == (1, 512, 512, 3) image_slice = image[0, -3:, -3:, -1] expected_img_slice = np.array([0.2402, 0.2375, 0.2285, 0.2378, 0.2407, 0.2263, 0.2354, 0.2307, 0.2520]) assert np.abs(image_slice.flatten() - expected_img_slice).max() < 2e-1 expected_text_prefix = "a living room" assert text[0][: len(expected_text_prefix)] == expected_text_prefix def test_unidiffuser_default_text2img_v1_fp16(self): pipe = UniDiffuserPipeline.from_pretrained("thu-ml/unidiffuser-v1", torch_dtype=torch.float16) pipe.to(torch_device) pipe.set_progress_bar_config(disable=None) pipe.enable_attention_slicing() inputs = self.get_inputs(device=torch_device, generate_latents=True) del inputs["image"] sample = pipe(**inputs) image = sample.images assert image.shape == (1, 512, 512, 3) image_slice = image[0, -3:, -3:, -1] expected_slice = np.array([0.0242, 0.0103, 0.0022, 0.0129, 0.0000, 0.0090, 0.0376, 0.0508, 0.0005]) assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-1 def test_unidiffuser_default_img2text_v1_fp16(self): pipe = UniDiffuserPipeline.from_pretrained("thu-ml/unidiffuser-v1", torch_dtype=torch.float16) pipe.to(torch_device) pipe.set_progress_bar_config(disable=None) pipe.enable_attention_slicing() inputs = self.get_inputs(device=torch_device, generate_latents=True) del inputs["prompt"] sample = pipe(**inputs) text = sample.text expected_text_prefix = "An astronaut" assert text[0][: len(expected_text_prefix)] == expected_text_prefix
diffusers/tests/pipelines/unidiffuser/test_unidiffuser.py/0
{ "file_path": "diffusers/tests/pipelines/unidiffuser/test_unidiffuser.py", "repo_id": "diffusers", "token_count": 14626 }
158
import torch from diffusers import UnCLIPScheduler from .test_schedulers import SchedulerCommonTest # UnCLIPScheduler is a modified DDPMScheduler with a subset of the configuration. class UnCLIPSchedulerTest(SchedulerCommonTest): scheduler_classes = (UnCLIPScheduler,) def get_scheduler_config(self, **kwargs): config = { "num_train_timesteps": 1000, "variance_type": "fixed_small_log", "clip_sample": True, "clip_sample_range": 1.0, "prediction_type": "epsilon", } config.update(**kwargs) return config def test_timesteps(self): for timesteps in [1, 5, 100, 1000]: self.check_over_configs(num_train_timesteps=timesteps) def test_variance_type(self): for variance in ["fixed_small_log", "learned_range"]: self.check_over_configs(variance_type=variance) def test_clip_sample(self): for clip_sample in [True, False]: self.check_over_configs(clip_sample=clip_sample) def test_clip_sample_range(self): for clip_sample_range in [1, 5, 10, 20]: self.check_over_configs(clip_sample_range=clip_sample_range) def test_prediction_type(self): for prediction_type in ["epsilon", "sample"]: self.check_over_configs(prediction_type=prediction_type) def test_time_indices(self): for time_step in [0, 500, 999]: for prev_timestep in [None, 5, 100, 250, 500, 750]: if prev_timestep is not None and prev_timestep >= time_step: continue self.check_over_forward(time_step=time_step, prev_timestep=prev_timestep) def test_variance_fixed_small_log(self): scheduler_class = self.scheduler_classes[0] scheduler_config = self.get_scheduler_config(variance_type="fixed_small_log") scheduler = scheduler_class(**scheduler_config) assert torch.sum(torch.abs(scheduler._get_variance(0) - 1.0000e-10)) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(487) - 0.0549625)) < 1e-5 assert torch.sum(torch.abs(scheduler._get_variance(999) - 0.9994987)) < 1e-5 def test_variance_learned_range(self): scheduler_class = self.scheduler_classes[0] scheduler_config = self.get_scheduler_config(variance_type="learned_range") scheduler = scheduler_class(**scheduler_config) predicted_variance = 0.5 assert scheduler._get_variance(1, predicted_variance=predicted_variance) - -10.1712790 < 1e-5 assert scheduler._get_variance(487, predicted_variance=predicted_variance) - -5.7998052 < 1e-5 assert scheduler._get_variance(999, predicted_variance=predicted_variance) - -0.0010011 < 1e-5 def test_full_loop(self): scheduler_class = self.scheduler_classes[0] scheduler_config = self.get_scheduler_config() scheduler = scheduler_class(**scheduler_config) timesteps = scheduler.timesteps model = self.dummy_model() sample = self.dummy_sample_deter generator = torch.manual_seed(0) for i, t in enumerate(timesteps): # 1. predict noise residual residual = model(sample, t) # 2. predict previous mean of sample x_t-1 pred_prev_sample = scheduler.step(residual, t, sample, generator=generator).prev_sample sample = pred_prev_sample result_sum = torch.sum(torch.abs(sample)) result_mean = torch.mean(torch.abs(sample)) assert abs(result_sum.item() - 252.2682495) < 1e-2 assert abs(result_mean.item() - 0.3284743) < 1e-3 def test_full_loop_skip_timesteps(self): scheduler_class = self.scheduler_classes[0] scheduler_config = self.get_scheduler_config() scheduler = scheduler_class(**scheduler_config) scheduler.set_timesteps(25) timesteps = scheduler.timesteps model = self.dummy_model() sample = self.dummy_sample_deter generator = torch.manual_seed(0) for i, t in enumerate(timesteps): # 1. predict noise residual residual = model(sample, t) if i + 1 == timesteps.shape[0]: prev_timestep = None else: prev_timestep = timesteps[i + 1] # 2. predict previous mean of sample x_t-1 pred_prev_sample = scheduler.step( residual, t, sample, prev_timestep=prev_timestep, generator=generator ).prev_sample sample = pred_prev_sample result_sum = torch.sum(torch.abs(sample)) result_mean = torch.mean(torch.abs(sample)) assert abs(result_sum.item() - 258.2044983) < 1e-2 assert abs(result_mean.item() - 0.3362038) < 1e-3 def test_trained_betas(self): pass def test_add_noise_device(self): pass
diffusers/tests/schedulers/test_scheduler_unclip.py/0
{ "file_path": "diffusers/tests/schedulers/test_scheduler_unclip.py", "repo_id": "diffusers", "token_count": 2227 }
159
import gc import unittest import torch from diffusers import ( StableDiffusionUpscalePipeline, ) from diffusers.utils import load_image from diffusers.utils.testing_utils import ( enable_full_determinism, numpy_cosine_similarity_distance, require_torch_gpu, slow, ) from .single_file_testing_utils import SDSingleFileTesterMixin enable_full_determinism() @slow @require_torch_gpu class StableDiffusionUpscalePipelineSingleFileSlowTests(unittest.TestCase, SDSingleFileTesterMixin): pipeline_class = StableDiffusionUpscalePipeline ckpt_path = "https://huggingface.co/stabilityai/stable-diffusion-x4-upscaler/blob/main/x4-upscaler-ema.safetensors" original_config = "https://raw.githubusercontent.com/Stability-AI/stablediffusion/main/configs/stable-diffusion/x4-upscaling.yaml" repo_id = "stabilityai/stable-diffusion-x4-upscaler" def setUp(self): super().setUp() gc.collect() torch.cuda.empty_cache() def tearDown(self): super().tearDown() gc.collect() torch.cuda.empty_cache() def test_single_file_format_inference_is_same_as_pretrained(self): image = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/sd2-upscale/low_res_cat.png" ) prompt = "a cat sitting on a park bench" pipe = StableDiffusionUpscalePipeline.from_pretrained(self.repo_id) pipe.enable_model_cpu_offload() generator = torch.Generator("cpu").manual_seed(0) output = pipe(prompt=prompt, image=image, generator=generator, output_type="np", num_inference_steps=3) image_from_pretrained = output.images[0] pipe_from_single_file = StableDiffusionUpscalePipeline.from_single_file(self.ckpt_path) pipe_from_single_file.enable_model_cpu_offload() generator = torch.Generator("cpu").manual_seed(0) output_from_single_file = pipe_from_single_file( prompt=prompt, image=image, generator=generator, output_type="np", num_inference_steps=3 ) image_from_single_file = output_from_single_file.images[0] assert image_from_pretrained.shape == (512, 512, 3) assert image_from_single_file.shape == (512, 512, 3) assert ( numpy_cosine_similarity_distance(image_from_pretrained.flatten(), image_from_single_file.flatten()) < 1e-3 )
diffusers/tests/single_file/test_stable_diffusion_upscale_single_file.py/0
{ "file_path": "diffusers/tests/single_file/test_stable_diffusion_upscale_single_file.py", "repo_id": "diffusers", "token_count": 1021 }
160
# coding=utf-8 # Copyright 2024 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys fork_point_sha = subprocess.check_output("git merge-base main HEAD".split()).decode("utf-8") modified_files = subprocess.check_output(f"git diff --name-only {fork_point_sha}".split()).decode("utf-8").split() joined_dirs = "|".join(sys.argv[1:]) regex = re.compile(rf"^({joined_dirs}).*?\.py$") relevant_modified_files = [x for x in modified_files if regex.match(x)] print(" ".join(relevant_modified_files), end="")
diffusers/utils/get_modified_files.py/0
{ "file_path": "diffusers/utils/get_modified_files.py", "repo_id": "diffusers", "token_count": 435 }
161
exclude: ^(tests/data) default_language_version: python: python3.10 repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.6.0 hooks: - id: check-added-large-files - id: debug-statements - id: check-merge-conflict - id: check-case-conflict - id: check-yaml - id: check-toml - id: end-of-file-fixer - id: trailing-whitespace - repo: https://github.com/asottile/pyupgrade rev: v3.16.0 hooks: - id: pyupgrade - repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.5.2 hooks: - id: ruff args: [--fix] - id: ruff-format - repo: https://github.com/python-poetry/poetry rev: 1.8.0 hooks: - id: poetry-check - id: poetry-lock args: - "--check" - "--no-update" - repo: https://github.com/gitleaks/gitleaks rev: v8.18.4 hooks: - id: gitleaks
lerobot/.pre-commit-config.yaml/0
{ "file_path": "lerobot/.pre-commit-config.yaml", "repo_id": "lerobot", "token_count": 461 }
162
This tutorial explains how to resume a training run that you've started with the training script. If you don't know how our training script and configuration system works, please read [4_train_policy_with_script.md](./4_train_policy_with_script.md) first. ## Basic training resumption Let's consider the example of training ACT for one of the ALOHA tasks. Here's a command that can achieve that: ```bash python lerobot/scripts/train.py \ hydra.run.dir=outputs/train/run_resumption \ policy=act \ dataset_repo_id=lerobot/aloha_sim_transfer_cube_human \ env=aloha \ env.task=AlohaTransferCube-v0 \ training.log_freq=25 \ training.save_checkpoint=true \ training.save_freq=100 ``` Here we're using the default dataset and environment for ACT, and we've taken care to set up the log frequency and checkpointing frequency to low numbers so we can test resumption. You should be able to see some logging and have a first checkpoint within 1 minute. Please interrupt the training after the first checkpoint. To resume, all that we have to do is run the training script, providing the run directory, and the resume option: ```bash python lerobot/scripts/train.py \ hydra.run.dir=outputs/train/run_resumption \ resume=true ``` You should see from the logging that your training picks up from where it left off. Note that with `resume=true`, the configuration file from the last checkpoint in the training output directory is loaded. So it doesn't matter that we haven't provided all the other configuration parameters from our previous command (although there may be warnings to notify you that your command has a different configuration than than the checkpoint). --- Now you should know how to resume your training run in case it gets interrupted or you want to extend a finished training run. Happy coding! 🤗
lerobot/examples/5_resume_training.md/0
{ "file_path": "lerobot/examples/5_resume_training.md", "repo_id": "lerobot", "token_count": 499 }
163
#!/usr/bin/env python # Copyright 2024 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ NOTE(YL): Adapted from: OpenVLA: https://github.com/openvla/openvla Octo: https://github.com/octo-models/octo transforms.py Defines a registry of per-dataset standardization transforms for each dataset in Open-X Embodiment. Transforms adopt the following structure: Input: Dictionary of *batched* features (i.e., has leading time dimension) Output: Dictionary `step` =>> { "observation": { <image_keys, depth_image_keys> State (in chosen state representation) }, "action": Action (in chosen action representation), "language_instruction": str } """ from typing import Any, Dict import tensorflow as tf from lerobot.common.datasets.push_dataset_to_hub.openx.data_utils import ( binarize_gripper_actions, invert_gripper_actions, rel2abs_gripper_actions, relabel_bridge_actions, ) def droid_baseact_transform_fn(): from lerobot.common.datasets.push_dataset_to_hub.openx.droid_utils import droid_baseact_transform return droid_baseact_transform def bridge_openx_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: """ Applies to version of Bridge V2 in Open X-Embodiment mixture. Note =>> In original Bridge V2 dataset, the first timestep has an all-zero action, so we remove it! """ for key in trajectory: if key == "traj_metadata": continue elif key in ["observation", "action"]: for key2 in trajectory[key]: trajectory[key][key2] = trajectory[key][key2][1:] else: trajectory[key] = trajectory[key][1:] trajectory["action"] = tf.concat( ( trajectory["action"]["world_vector"], trajectory["action"]["rotation_delta"], tf.cast(trajectory["action"]["open_gripper"][:, None], tf.float32), ), axis=-1, ) trajectory["language_instruction"] = trajectory["observation"]["natural_language_instruction"] trajectory = relabel_bridge_actions(trajectory) trajectory["observation"]["EEF_state"] = trajectory["observation"]["state"][:, :6] trajectory["observation"]["gripper_state"] = trajectory["observation"]["state"][:, -1:] return trajectory def bridge_orig_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: """ Applies to original version of Bridge V2 from the official project website. Note =>> In original Bridge V2 dataset, the first timestep has an all-zero action, so we remove it! """ for key in trajectory: if key == "traj_metadata": continue elif key == "observation": for key2 in trajectory[key]: trajectory[key][key2] = trajectory[key][key2][1:] else: trajectory[key] = trajectory[key][1:] trajectory["action"] = tf.concat( [ trajectory["action"][:, :6], binarize_gripper_actions(trajectory["action"][:, -1])[:, None], ], axis=1, ) trajectory = relabel_bridge_actions(trajectory) trajectory["observation"]["EEF_state"] = trajectory["observation"]["state"][:, :6] trajectory["observation"]["gripper_state"] = trajectory["observation"]["state"][:, -1:] return trajectory def ppgm_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["action"] = tf.concat( [ trajectory["action"][:, :6], binarize_gripper_actions(trajectory["action"][:, -1])[:, None], ], axis=1, ) trajectory["observation"]["EEF_state"] = trajectory["observation"]["cartesian_position"][:, :6] trajectory["observation"]["gripper_state"] = trajectory["observation"]["gripper_position"][:, -1:] return trajectory def rt1_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: # make gripper action absolute action, +1 = open, 0 = close gripper_action = trajectory["action"]["gripper_closedness_action"][:, 0] gripper_action = rel2abs_gripper_actions(gripper_action) trajectory["action"] = tf.concat( ( trajectory["action"]["world_vector"], trajectory["action"]["rotation_delta"], gripper_action[:, None], ), axis=-1, ) trajectory["language_instruction"] = trajectory["observation"]["natural_language_instruction"] return trajectory def kuka_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: # make gripper action absolute action, +1 = open, 0 = close gripper_action = trajectory["action"]["gripper_closedness_action"][:, 0] gripper_action = rel2abs_gripper_actions(gripper_action) trajectory["action"] = tf.concat( ( trajectory["action"]["world_vector"], trajectory["action"]["rotation_delta"], gripper_action[:, None], ), axis=-1, ) # decode compressed state eef_value = tf.io.decode_compressed( trajectory["observation"]["clip_function_input/base_pose_tool_reached"], compression_type="ZLIB", ) eef_value = tf.io.decode_raw(eef_value, tf.float32) trajectory["observation"]["clip_function_input/base_pose_tool_reached"] = tf.reshape(eef_value, (-1, 7)) gripper_value = tf.io.decode_compressed( trajectory["observation"]["gripper_closed"], compression_type="ZLIB" ) gripper_value = tf.io.decode_raw(gripper_value, tf.float32) trajectory["observation"]["gripper_closed"] = tf.reshape(gripper_value, (-1, 1)) trajectory["language_instruction"] = trajectory["observation"]["natural_language_instruction"] return trajectory def taco_play_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["observation"]["state_eef"] = trajectory["observation"]["robot_obs"][:, :6] trajectory["observation"]["state_gripper"] = trajectory["observation"]["robot_obs"][:, 7:8] trajectory["action"] = trajectory["action"]["rel_actions_world"] # invert gripper action + clip, +1 = open, 0 = close trajectory["action"] = tf.concat( ( trajectory["action"][:, :6], tf.clip_by_value(trajectory["action"][:, -1:], 0, 1), ), axis=-1, ) trajectory["language_instruction"] = trajectory["observation"]["natural_language_instruction"] return trajectory def jaco_play_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["observation"]["state_eef"] = trajectory["observation"]["end_effector_cartesian_pos"][:, :6] trajectory["observation"]["state_gripper"] = trajectory["observation"]["end_effector_cartesian_pos"][ :, -1: ] # make gripper action absolute action, +1 = open, 0 = close gripper_action = trajectory["action"]["gripper_closedness_action"][:, 0] gripper_action = rel2abs_gripper_actions(gripper_action) trajectory["action"] = tf.concat( ( trajectory["action"]["world_vector"], tf.zeros_like(trajectory["action"]["world_vector"]), gripper_action[:, None], ), axis=-1, ) trajectory["language_instruction"] = trajectory["observation"]["natural_language_instruction"] return trajectory def berkeley_cable_routing_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["action"] = tf.concat( ( trajectory["action"]["world_vector"], trajectory["action"]["rotation_delta"], tf.zeros_like(trajectory["action"]["world_vector"][:, :1]), ), axis=-1, ) trajectory["language_instruction"] = trajectory["observation"]["natural_language_instruction"] return trajectory def roboturk_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: # invert absolute gripper action, +1 = open, 0 = close gripper_action = invert_gripper_actions( tf.clip_by_value(trajectory["action"]["gripper_closedness_action"], 0, 1) ) trajectory["action"] = tf.concat( ( trajectory["action"]["world_vector"], trajectory["action"]["rotation_delta"], gripper_action, ), axis=-1, ) trajectory["language_instruction"] = trajectory["observation"]["natural_language_instruction"] trajectory["language_embedding"] = trajectory["observation"]["natural_language_embedding"] return trajectory def nyu_door_opening_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: # make gripper action absolute action, +1 = open, 0 = close gripper_action = trajectory["action"]["gripper_closedness_action"][:, 0] gripper_action = rel2abs_gripper_actions(gripper_action) trajectory["action"] = tf.concat( ( trajectory["action"]["world_vector"], trajectory["action"]["rotation_delta"], gripper_action[:, None], ), axis=-1, ) trajectory["language_instruction"] = trajectory["observation"]["natural_language_instruction"] return trajectory def viola_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: # make gripper action, +1 = open, 0 = close gripper_action = trajectory["action"]["gripper_closedness_action"][:, None] gripper_action = tf.clip_by_value(gripper_action, 0, 1) gripper_action = invert_gripper_actions(gripper_action) trajectory["action"] = tf.concat( ( trajectory["action"]["world_vector"], trajectory["action"]["rotation_delta"], gripper_action, ), axis=-1, ) trajectory["language_instruction"] = trajectory["observation"]["natural_language_instruction"] return trajectory def berkeley_autolab_ur5_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["observation"]["state"] = trajectory["observation"]["robot_state"][:, 6:14] # make gripper action absolute action, +1 = open, 0 = close gripper_action = trajectory["action"]["gripper_closedness_action"] gripper_action = rel2abs_gripper_actions(gripper_action) trajectory["action"] = tf.concat( ( trajectory["action"]["world_vector"], trajectory["action"]["rotation_delta"], gripper_action[:, None], ), axis=-1, ) trajectory["language_instruction"] = trajectory["observation"]["natural_language_instruction"] return trajectory def toto_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["action"] = tf.concat( ( trajectory["action"]["world_vector"], trajectory["action"]["rotation_delta"], tf.cast(trajectory["action"]["open_gripper"][:, None], tf.float32), ), axis=-1, ) trajectory["language_instruction"] = trajectory["observation"]["natural_language_instruction"] return trajectory def language_table_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: # default to "open" gripper trajectory["action"] = tf.concat( ( trajectory["action"], tf.zeros_like(trajectory["action"]), tf.zeros_like(trajectory["action"]), tf.ones_like(trajectory["action"][:, :1]), ), axis=-1, ) # decode language instruction instruction_bytes = trajectory["observation"]["instruction"] instruction_encoded = tf.strings.unicode_encode(instruction_bytes, output_encoding="UTF-8") # Remove trailing padding --> convert RaggedTensor to regular Tensor. trajectory["language_instruction"] = tf.strings.split(instruction_encoded, "\x00")[:, :1].to_tensor()[ :, 0 ] return trajectory def pusht_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["action"] = tf.concat( ( trajectory["action"]["world_vector"], trajectory["action"]["rotation_delta"], trajectory["action"]["gripper_closedness_action"][:, None], ), axis=-1, ) trajectory["language_instruction"] = trajectory["observation"]["natural_language_instruction"] return trajectory def stanford_kuka_multimodal_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["observation"]["depth_image"] = trajectory["observation"]["depth_image"][..., 0] trajectory["action"] = tf.concat( ( trajectory["action"][:, :3], tf.zeros_like(trajectory["action"][:, :3]), trajectory["action"][:, -1:], ), axis=-1, ) return trajectory def nyu_rot_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["observation"]["eef_state"] = trajectory["observation"]["state"][..., :6] trajectory["observation"]["gripper_state"] = trajectory["observation"]["state"][..., -1:] trajectory["action"] = trajectory["action"][..., :7] return trajectory def stanford_hydra_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: # invert gripper action, +1 = open, 0 = close trajectory["action"] = tf.concat( ( trajectory["action"][:, :6], invert_gripper_actions(trajectory["action"][:, -1:]), ), axis=-1, ) trajectory["observation"]["eef_state"] = tf.concat( ( trajectory["observation"]["state"][:, :3], trajectory["observation"]["state"][:, 7:10], ), axis=-1, ) trajectory["observation"]["gripper_state"] = trajectory["observation"]["state"][:, -3:-2] return trajectory def austin_buds_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: # invert gripper action + clip, +1 = open, 0 = close trajectory["action"] = tf.concat( ( trajectory["action"][:, :6], invert_gripper_actions(tf.clip_by_value(trajectory["action"][:, -1:], 0, 1)), ), axis=-1, ) trajectory["observation"]["state"] = trajectory["observation"]["state"][:, :8] return trajectory def nyu_franka_play_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["observation"]["depth"] = tf.cast(trajectory["observation"]["depth"][..., 0], tf.float32) trajectory["observation"]["depth_additional_view"] = tf.cast( trajectory["observation"]["depth_additional_view"][..., 0], tf.float32 ) trajectory["observation"]["eef_state"] = trajectory["observation"]["state"][:, -6:] # clip gripper action, +1 = open, 0 = close trajectory["action"] = tf.concat( ( trajectory["action"][:, -8:-2], tf.clip_by_value(trajectory["action"][:, -2:-1], 0, 1), ), axis=-1, ) return trajectory def maniskill_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["observation"]["gripper_state"] = trajectory["observation"]["state"][..., 7:8] return trajectory def furniture_bench_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: import tensorflow_graphics.geometry.transformation as tft trajectory["observation"]["state"] = tf.concat( ( trajectory["observation"]["state"][:, :7], trajectory["observation"]["state"][:, -1:], ), axis=-1, ) # invert gripper action + clip, +1 = open, 0 = close trajectory["action"] = tf.concat( ( trajectory["action"][:, :3], tft.euler.from_quaternion(trajectory["action"][:, 3:7]), invert_gripper_actions(tf.clip_by_value(trajectory["action"][:, -1:], 0, 1)), ), axis=-1, ) return trajectory def cmu_franka_exploration_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["action"] = trajectory["action"][..., :-1] return trajectory def ucsd_kitchen_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["observation"]["joint_state"] = trajectory["observation"]["state"][:, :7] trajectory["action"] = trajectory["action"][..., :-1] return trajectory def ucsd_pick_place_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["observation"]["eef_state"] = trajectory["observation"]["state"][:, :6] trajectory["observation"]["gripper_state"] = trajectory["observation"]["state"][:, -1:] trajectory["action"] = tf.concat( ( trajectory["action"][:, :3], tf.zeros_like(trajectory["action"][:, :3]), trajectory["action"][:, -1:], ), axis=-1, ) return trajectory def austin_sailor_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: # invert gripper action + clip, +1 = open, 0 = close trajectory["action"] = tf.concat( ( trajectory["action"][:, :6], invert_gripper_actions(tf.clip_by_value(trajectory["action"][:, -1:], 0, 1)), ), axis=-1, ) return trajectory def austin_sirius_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: # invert gripper action + clip, +1 = open, 0 = close trajectory["action"] = tf.concat( ( trajectory["action"][:, :6], invert_gripper_actions(tf.clip_by_value(trajectory["action"][:, -1:], 0, 1)), ), axis=-1, ) return trajectory def bc_z_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["action"] = tf.concat( ( trajectory["action"]["future/xyz_residual"][:, :3], trajectory["action"]["future/axis_angle_residual"][:, :3], invert_gripper_actions(tf.cast(trajectory["action"]["future/target_close"][:, :1], tf.float32)), ), axis=-1, ) trajectory["language_instruction"] = trajectory["observation"]["natural_language_instruction"] return trajectory def tokyo_pr2_opening_fridge_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["observation"]["eef_state"] = trajectory["observation"]["state"][:, :6] trajectory["observation"]["gripper_state"] = trajectory["observation"]["state"][:, -1:] trajectory["action"] = trajectory["action"][..., :-1] return trajectory def tokyo_pr2_tabletop_manipulation_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["observation"]["eef_state"] = trajectory["observation"]["state"][:, :6] trajectory["observation"]["gripper_state"] = trajectory["observation"]["state"][:, -1:] trajectory["action"] = trajectory["action"][..., :-1] return trajectory def utokyo_xarm_bimanual_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["action"] = trajectory["action"][..., -7:] return trajectory def robo_net_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["observation"]["eef_state"] = tf.concat( ( trajectory["observation"]["state"][:, :4], tf.zeros_like(trajectory["observation"]["state"][:, :2]), ), axis=-1, ) trajectory["observation"]["gripper_state"] = trajectory["observation"]["state"][:, -1:] trajectory["action"] = tf.concat( ( trajectory["action"][:, :4], tf.zeros_like(trajectory["action"][:, :2]), trajectory["action"][:, -1:], ), axis=-1, ) return trajectory def berkeley_mvp_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: """ trajectory["observation"]["state"] = tf.concat(( tf.cast(trajectory["observation"]["gripper"][:, None], tf.float32), trajectory["observation"]["pose"], trajectory["observation"]["joint_pos"],), axis=-1,) """ trajectory["observation"]["gripper"] = tf.cast(trajectory["observation"]["gripper"][:, None], tf.float32) return trajectory def berkeley_rpt_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["observation"]["gripper"] = tf.cast(trajectory["observation"]["gripper"][:, None], tf.float32) return trajectory def kaist_nonprehensible_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["observation"]["state"] = trajectory["observation"]["state"][:, -7:] trajectory["action"] = tf.concat( ( trajectory["action"][:, :6], tf.zeros_like(trajectory["action"][:, :1]), ), axis=-1, ) return trajectory def stanford_mask_vit_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["observation"]["eef_state"] = tf.concat( ( trajectory["observation"]["end_effector_pose"][:, :4], tf.zeros_like(trajectory["observation"]["end_effector_pose"][:, :2]), ), axis=-1, ) trajectory["observation"]["gripper_state"] = trajectory["observation"]["end_effector_pose"][:, -1:] trajectory["action"] = tf.concat( ( trajectory["action"][:, :4], tf.zeros_like(trajectory["action"][:, :2]), trajectory["action"][:, -1:], ), axis=-1, ) return trajectory def tokyo_lsmo_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["observation"]["eef_state"] = trajectory["observation"]["state"][:, :6] trajectory["observation"]["gripper_state"] = trajectory["observation"]["state"][:, -1:] return trajectory def dlr_sara_grid_clamp_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["observation"]["state"] = trajectory["observation"]["state"][:, :6] return trajectory def dlr_edan_shared_control_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: # invert gripper action, +1 = open, 0 = close trajectory["action"] = tf.concat( ( trajectory["action"][:, :6], invert_gripper_actions(trajectory["action"][:, -1:]), ), axis=-1, ) return trajectory def asu_table_top_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["observation"]["eef_state"] = trajectory["ground_truth_states"]["EE"] trajectory["observation"]["gripper_state"] = trajectory["observation"]["state"][:, -1:] return trajectory def robocook_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["observation"]["eef_state"] = trajectory["observation"]["state"][:, :6] trajectory["observation"]["gripper_state"] = trajectory["observation"]["state"][:, -1:] return trajectory def imperial_wristcam_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["action"] = trajectory["action"][..., :-1] return trajectory def iamlab_pick_insert_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: import tensorflow_graphics.geometry.transformation as tft trajectory["observation"]["joint_state"] = trajectory["observation"]["state"][:, :7] trajectory["observation"]["gripper_state"] = trajectory["observation"]["state"][:, 7:8] trajectory["action"] = tf.concat( ( trajectory["action"][:, :3], tft.euler.from_quaternion(trajectory["action"][:, 3:7]), trajectory["action"][:, 7:8], ), axis=-1, ) return trajectory def uiuc_d3field_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["action"] = tf.concat( ( trajectory["action"], tf.zeros_like(trajectory["action"]), tf.zeros_like(trajectory["action"][:, :1]), ), axis=-1, ) return trajectory def utaustin_mutex_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["observation"]["state"] = trajectory["observation"]["state"][:, :8] # invert gripper action + clip, +1 = open, 0 = close trajectory["action"] = tf.concat( ( trajectory["action"][:, :6], invert_gripper_actions(tf.clip_by_value(trajectory["action"][:, -1:], 0, 1)), ), axis=-1, ) return trajectory def berkeley_fanuc_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["observation"]["joint_state"] = trajectory["observation"]["state"][:, :6] trajectory["observation"]["gripper_state"] = trajectory["observation"]["state"][:, 6:7] # dataset does not store gripper actions, so use gripper state info, invert so +1 = open, 0 = close trajectory["action"] = tf.concat( ( trajectory["action"], invert_gripper_actions(trajectory["observation"]["gripper_state"]), ), axis=-1, ) return trajectory def cmu_playing_with_food_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: import tensorflow_graphics.geometry.transformation as tft trajectory["action"] = tf.concat( ( trajectory["action"][:, :3], tft.euler.from_quaternion(trajectory["action"][:, 3:7]), trajectory["action"][:, -1:], ), axis=-1, ) return trajectory def playfusion_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["action"] = tf.concat( ( trajectory["action"][:, :3], trajectory["action"][:, -4:], ), axis=-1, ) return trajectory def cmu_stretch_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["observation"]["eef_state"] = tf.concat( ( trajectory["observation"]["state"][:, :3], tf.zeros_like(trajectory["observation"]["state"][:, :3]), ), axis=-1, ) trajectory["observation"]["gripper_state"] = trajectory["observation"]["state"][:, -1:] trajectory["action"] = trajectory["action"][..., :-1] return trajectory def gnm_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: trajectory["observation"]["state"] = tf.concat( ( trajectory["observation"]["position"], tf.zeros_like(trajectory["observation"]["state"][:, :3]), trajectory["observation"]["yaw"], ), axis=-1, ) trajectory["action"] = tf.concat( ( trajectory["action"], tf.zeros_like(trajectory["action"]), tf.zeros_like(trajectory["action"]), tf.zeros_like(trajectory["action"][:, :1]), ), axis=-1, ) return trajectory def fmb_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: # every input feature is batched, ie has leading batch dimension trajectory["observation"]["proprio"] = tf.concat( ( trajectory["observation"]["eef_pose"], trajectory["observation"]["state_gripper_pose"][..., None], ), axis=-1, ) return trajectory def dobbe_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: # every input feature is batched, ie has leading batch dimension trajectory["observation"]["proprio"] = trajectory["observation"]["state"] return trajectory def robo_set_dataset_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: # gripper action is in -1...1 --> clip to 0...1, flip gripper_action = trajectory["action"][:, -1:] gripper_action = invert_gripper_actions(tf.clip_by_value(gripper_action, 0, 1)) trajectory["action"] = tf.concat( ( trajectory["action"][:, :7], gripper_action, ), axis=-1, ) return trajectory def identity_transform(trajectory: Dict[str, Any]) -> Dict[str, Any]: return trajectory # === Registry === OPENX_STANDARDIZATION_TRANSFORMS = { "bridge_openx": bridge_openx_dataset_transform, "bridge_orig": bridge_orig_dataset_transform, "bridge_dataset": bridge_orig_dataset_transform, "ppgm": ppgm_dataset_transform, "ppgm_static": ppgm_dataset_transform, "ppgm_wrist": ppgm_dataset_transform, "fractal20220817_data": rt1_dataset_transform, "kuka": kuka_dataset_transform, "taco_play": taco_play_dataset_transform, "jaco_play": jaco_play_dataset_transform, "berkeley_cable_routing": berkeley_cable_routing_dataset_transform, "roboturk": roboturk_dataset_transform, "nyu_door_opening_surprising_effectiveness": nyu_door_opening_dataset_transform, "viola": viola_dataset_transform, "berkeley_autolab_ur5": berkeley_autolab_ur5_dataset_transform, "toto": toto_dataset_transform, "language_table": language_table_dataset_transform, "columbia_cairlab_pusht_real": pusht_dataset_transform, "stanford_kuka_multimodal_dataset_converted_externally_to_rlds": stanford_kuka_multimodal_dataset_transform, "nyu_rot_dataset_converted_externally_to_rlds": nyu_rot_dataset_transform, "stanford_hydra_dataset_converted_externally_to_rlds": stanford_hydra_dataset_transform, "austin_buds_dataset_converted_externally_to_rlds": austin_buds_dataset_transform, "nyu_franka_play_dataset_converted_externally_to_rlds": nyu_franka_play_dataset_transform, "maniskill_dataset_converted_externally_to_rlds": maniskill_dataset_transform, "furniture_bench_dataset_converted_externally_to_rlds": furniture_bench_dataset_transform, "cmu_franka_exploration_dataset_converted_externally_to_rlds": cmu_franka_exploration_dataset_transform, "ucsd_kitchen_dataset_converted_externally_to_rlds": ucsd_kitchen_dataset_transform, "ucsd_pick_and_place_dataset_converted_externally_to_rlds": ucsd_pick_place_dataset_transform, "austin_sailor_dataset_converted_externally_to_rlds": austin_sailor_dataset_transform, "austin_sirius_dataset_converted_externally_to_rlds": austin_sirius_dataset_transform, "bc_z": bc_z_dataset_transform, "utokyo_pr2_opening_fridge_converted_externally_to_rlds": tokyo_pr2_opening_fridge_dataset_transform, "utokyo_pr2_tabletop_manipulation_converted_externally_to_rlds": tokyo_pr2_tabletop_manipulation_dataset_transform, "utokyo_xarm_pick_and_place_converted_externally_to_rlds": identity_transform, "utokyo_xarm_bimanual_converted_externally_to_rlds": utokyo_xarm_bimanual_dataset_transform, "robo_net": robo_net_dataset_transform, "berkeley_mvp_converted_externally_to_rlds": berkeley_mvp_dataset_transform, "berkeley_rpt_converted_externally_to_rlds": berkeley_rpt_dataset_transform, "kaist_nonprehensile_converted_externally_to_rlds": kaist_nonprehensible_dataset_transform, "stanford_mask_vit_converted_externally_to_rlds": stanford_mask_vit_dataset_transform, "tokyo_u_lsmo_converted_externally_to_rlds": tokyo_lsmo_dataset_transform, "dlr_sara_pour_converted_externally_to_rlds": identity_transform, "dlr_sara_grid_clamp_converted_externally_to_rlds": dlr_sara_grid_clamp_dataset_transform, "dlr_edan_shared_control_converted_externally_to_rlds": dlr_edan_shared_control_dataset_transform, "asu_table_top_converted_externally_to_rlds": asu_table_top_dataset_transform, "stanford_robocook_converted_externally_to_rlds": robocook_dataset_transform, "imperialcollege_sawyer_wrist_cam": imperial_wristcam_dataset_transform, "iamlab_cmu_pickup_insert_converted_externally_to_rlds": iamlab_pick_insert_dataset_transform, "uiuc_d3field": uiuc_d3field_dataset_transform, "utaustin_mutex": utaustin_mutex_dataset_transform, "berkeley_fanuc_manipulation": berkeley_fanuc_dataset_transform, "cmu_playing_with_food": cmu_playing_with_food_dataset_transform, "cmu_play_fusion": playfusion_dataset_transform, "cmu_stretch": cmu_stretch_dataset_transform, "berkeley_gnm_recon": gnm_dataset_transform, "berkeley_gnm_cory_hall": gnm_dataset_transform, "berkeley_gnm_sac_son": gnm_dataset_transform, "droid": droid_baseact_transform_fn(), "droid_100": droid_baseact_transform_fn(), # first 100 episodes of droid "fmb": fmb_transform, "dobbe": dobbe_dataset_transform, "robo_set": robo_set_dataset_transform, "usc_cloth_sim_converted_externally_to_rlds": identity_transform, "plex_robosuite": identity_transform, "conq_hose_manipulation": identity_transform, "io_ai_tech": identity_transform, "spoc": identity_transform, }
lerobot/lerobot/common/datasets/push_dataset_to_hub/openx/transforms.py/0
{ "file_path": "lerobot/lerobot/common/datasets/push_dataset_to_hub/openx/transforms.py", "repo_id": "lerobot", "token_count": 13988 }
164
#!/usr/bin/env python # Copyright 2024 Columbia Artificial Intelligence, Robotics Lab, # and 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. """Diffusion Policy as per "Diffusion Policy: Visuomotor Policy Learning via Action Diffusion" TODO(alexander-soare): - Remove reliance on diffusers for DDPMScheduler and LR scheduler. """ import math from collections import deque from typing import Callable import einops import numpy as np import torch import torch.nn.functional as F # noqa: N812 import torchvision from diffusers.schedulers.scheduling_ddim import DDIMScheduler from diffusers.schedulers.scheduling_ddpm import DDPMScheduler from huggingface_hub import PyTorchModelHubMixin from torch import Tensor, nn from lerobot.common.policies.diffusion.configuration_diffusion import DiffusionConfig from lerobot.common.policies.normalize import Normalize, Unnormalize from lerobot.common.policies.utils import ( get_device_from_parameters, get_dtype_from_parameters, populate_queues, ) class DiffusionPolicy( nn.Module, PyTorchModelHubMixin, library_name="lerobot", repo_url="https://github.com/huggingface/lerobot", tags=["robotics", "diffusion-policy"], ): """ Diffusion Policy as per "Diffusion Policy: Visuomotor Policy Learning via Action Diffusion" (paper: https://arxiv.org/abs/2303.04137, code: https://github.com/real-stanford/diffusion_policy). """ name = "diffusion" def __init__( self, config: DiffusionConfig | None = None, dataset_stats: dict[str, dict[str, Tensor]] | None = None, ): """ Args: config: Policy configuration class instance or None, in which case the default instantiation of the configuration class is used. dataset_stats: Dataset statistics to be used for normalization. If not passed here, it is expected that they will be passed with a call to `load_state_dict` before the policy is used. """ super().__init__() if config is None: config = DiffusionConfig() self.config = config self.normalize_inputs = Normalize( config.input_shapes, config.input_normalization_modes, dataset_stats ) self.normalize_targets = Normalize( config.output_shapes, config.output_normalization_modes, dataset_stats ) self.unnormalize_outputs = Unnormalize( config.output_shapes, config.output_normalization_modes, dataset_stats ) # queues are populated during rollout of the policy, they contain the n latest observations and actions self._queues = None self.diffusion = DiffusionModel(config) self.expected_image_keys = [k for k in config.input_shapes if k.startswith("observation.image")] self.use_env_state = "observation.environment_state" in config.input_shapes self.reset() def reset(self): """Clear observation and action queues. Should be called on `env.reset()`""" self._queues = { "observation.state": deque(maxlen=self.config.n_obs_steps), "action": deque(maxlen=self.config.n_action_steps), } if len(self.expected_image_keys) > 0: self._queues["observation.images"] = deque(maxlen=self.config.n_obs_steps) if self.use_env_state: self._queues["observation.environment_state"] = deque(maxlen=self.config.n_obs_steps) @torch.no_grad def select_action(self, batch: dict[str, Tensor]) -> Tensor: """Select a single action given environment observations. This method handles caching a history of observations and an action trajectory generated by the underlying diffusion model. Here's how it works: - `n_obs_steps` steps worth of observations are cached (for the first steps, the observation is copied `n_obs_steps` times to fill the cache). - The diffusion model generates `horizon` steps worth of actions. - `n_action_steps` worth of actions are actually kept for execution, starting from the current step. Schematically this looks like: ---------------------------------------------------------------------------------------------- (legend: o = n_obs_steps, h = horizon, a = n_action_steps) |timestep | n-o+1 | n-o+2 | ..... | n | ..... | n+a-1 | n+a | ..... | n-o+h | |observation is used | YES | YES | YES | YES | NO | NO | NO | NO | NO | |action is generated | YES | YES | YES | YES | YES | YES | YES | YES | YES | |action is used | NO | NO | NO | YES | YES | YES | NO | NO | NO | ---------------------------------------------------------------------------------------------- Note that this means we require: `n_action_steps <= horizon - n_obs_steps + 1`. Also, note that "horizon" may not the best name to describe what the variable actually means, because this period is actually measured from the first observation which (if `n_obs_steps` > 1) happened in the past. """ batch = self.normalize_inputs(batch) if len(self.expected_image_keys) > 0: batch = dict(batch) # shallow copy so that adding a key doesn't modify the original batch["observation.images"] = torch.stack([batch[k] for k in self.expected_image_keys], dim=-4) # Note: It's important that this happens after stacking the images into a single key. self._queues = populate_queues(self._queues, batch) if len(self._queues["action"]) == 0: # stack n latest observations from the queue batch = {k: torch.stack(list(self._queues[k]), dim=1) for k in batch if k in self._queues} actions = self.diffusion.generate_actions(batch) # TODO(rcadene): make above methods return output dictionary? actions = self.unnormalize_outputs({"action": actions})["action"] self._queues["action"].extend(actions.transpose(0, 1)) action = self._queues["action"].popleft() return action def forward(self, batch: dict[str, Tensor]) -> dict[str, Tensor]: """Run the batch through the model and compute the loss for training or validation.""" batch = self.normalize_inputs(batch) if len(self.expected_image_keys) > 0: batch = dict(batch) # shallow copy so that adding a key doesn't modify the original batch["observation.images"] = torch.stack([batch[k] for k in self.expected_image_keys], dim=-4) batch = self.normalize_targets(batch) loss = self.diffusion.compute_loss(batch) return {"loss": loss} def _make_noise_scheduler(name: str, **kwargs: dict) -> DDPMScheduler | DDIMScheduler: """ Factory for noise scheduler instances of the requested type. All kwargs are passed to the scheduler. """ if name == "DDPM": return DDPMScheduler(**kwargs) elif name == "DDIM": return DDIMScheduler(**kwargs) else: raise ValueError(f"Unsupported noise scheduler type {name}") class DiffusionModel(nn.Module): def __init__(self, config: DiffusionConfig): super().__init__() self.config = config # Build observation encoders (depending on which observations are provided). global_cond_dim = config.input_shapes["observation.state"][0] num_images = len([k for k in config.input_shapes if k.startswith("observation.image")]) self._use_images = False self._use_env_state = False if num_images > 0: self._use_images = True self.rgb_encoder = DiffusionRgbEncoder(config) global_cond_dim += self.rgb_encoder.feature_dim * num_images if "observation.environment_state" in config.input_shapes: self._use_env_state = True global_cond_dim += config.input_shapes["observation.environment_state"][0] self.unet = DiffusionConditionalUnet1d(config, global_cond_dim=global_cond_dim * config.n_obs_steps) self.noise_scheduler = _make_noise_scheduler( config.noise_scheduler_type, num_train_timesteps=config.num_train_timesteps, beta_start=config.beta_start, beta_end=config.beta_end, beta_schedule=config.beta_schedule, clip_sample=config.clip_sample, clip_sample_range=config.clip_sample_range, prediction_type=config.prediction_type, ) if config.num_inference_steps is None: self.num_inference_steps = self.noise_scheduler.config.num_train_timesteps else: self.num_inference_steps = config.num_inference_steps # ========= inference ============ def conditional_sample( self, batch_size: int, global_cond: Tensor | None = None, generator: torch.Generator | None = None ) -> Tensor: device = get_device_from_parameters(self) dtype = get_dtype_from_parameters(self) # Sample prior. sample = torch.randn( size=(batch_size, self.config.horizon, self.config.output_shapes["action"][0]), dtype=dtype, device=device, generator=generator, ) self.noise_scheduler.set_timesteps(self.num_inference_steps) for t in self.noise_scheduler.timesteps: # Predict model output. model_output = self.unet( sample, torch.full(sample.shape[:1], t, dtype=torch.long, device=sample.device), global_cond=global_cond, ) # Compute previous image: x_t -> x_t-1 sample = self.noise_scheduler.step(model_output, t, sample, generator=generator).prev_sample return sample def _prepare_global_conditioning(self, batch: dict[str, Tensor]) -> Tensor: """Encode image features and concatenate them all together along with the state vector.""" batch_size, n_obs_steps = batch["observation.state"].shape[:2] global_cond_feats = [batch["observation.state"]] # Extract image feature (first combine batch, sequence, and camera index dims). if self._use_images: img_features = self.rgb_encoder( einops.rearrange(batch["observation.images"], "b s n ... -> (b s n) ...") ) # Separate batch dim and sequence dim back out. The camera index dim gets absorbed into the # feature dim (effectively concatenating the camera features). img_features = einops.rearrange( img_features, "(b s n) ... -> b s (n ...)", b=batch_size, s=n_obs_steps ) global_cond_feats.append(img_features) if self._use_env_state: global_cond_feats.append(batch["observation.environment_state"]) # Concatenate features then flatten to (B, global_cond_dim). return torch.cat(global_cond_feats, dim=-1).flatten(start_dim=1) def generate_actions(self, batch: dict[str, Tensor]) -> Tensor: """ This function expects `batch` to have: { "observation.state": (B, n_obs_steps, state_dim) "observation.images": (B, n_obs_steps, num_cameras, C, H, W) AND/OR "observation.environment_state": (B, environment_dim) } """ batch_size, n_obs_steps = batch["observation.state"].shape[:2] assert n_obs_steps == self.config.n_obs_steps # Encode image features and concatenate them all together along with the state vector. global_cond = self._prepare_global_conditioning(batch) # (B, global_cond_dim) # run sampling actions = self.conditional_sample(batch_size, global_cond=global_cond) # Extract `n_action_steps` steps worth of actions (from the current observation). start = n_obs_steps - 1 end = start + self.config.n_action_steps actions = actions[:, start:end] return actions def compute_loss(self, batch: dict[str, Tensor]) -> Tensor: """ This function expects `batch` to have (at least): { "observation.state": (B, n_obs_steps, state_dim) "observation.images": (B, n_obs_steps, num_cameras, C, H, W) AND/OR "observation.environment_state": (B, environment_dim) "action": (B, horizon, action_dim) "action_is_pad": (B, horizon) } """ # Input validation. assert set(batch).issuperset({"observation.state", "action", "action_is_pad"}) assert "observation.images" in batch or "observation.environment_state" in batch n_obs_steps = batch["observation.state"].shape[1] horizon = batch["action"].shape[1] assert horizon == self.config.horizon assert n_obs_steps == self.config.n_obs_steps # Encode image features and concatenate them all together along with the state vector. global_cond = self._prepare_global_conditioning(batch) # (B, global_cond_dim) # Forward diffusion. trajectory = batch["action"] # Sample noise to add to the trajectory. eps = torch.randn(trajectory.shape, device=trajectory.device) # Sample a random noising timestep for each item in the batch. timesteps = torch.randint( low=0, high=self.noise_scheduler.config.num_train_timesteps, size=(trajectory.shape[0],), device=trajectory.device, ).long() # Add noise to the clean trajectories according to the noise magnitude at each timestep. noisy_trajectory = self.noise_scheduler.add_noise(trajectory, eps, timesteps) # Run the denoising network (that might denoise the trajectory, or attempt to predict the noise). pred = self.unet(noisy_trajectory, timesteps, global_cond=global_cond) # Compute the loss. # The target is either the original trajectory, or the noise. if self.config.prediction_type == "epsilon": target = eps elif self.config.prediction_type == "sample": target = batch["action"] else: raise ValueError(f"Unsupported prediction type {self.config.prediction_type}") loss = F.mse_loss(pred, target, reduction="none") # Mask loss wherever the action is padded with copies (edges of the dataset trajectory). if self.config.do_mask_loss_for_padding: if "action_is_pad" not in batch: raise ValueError( "You need to provide 'action_is_pad' in the batch when " f"{self.config.do_mask_loss_for_padding=}." ) in_episode_bound = ~batch["action_is_pad"] loss = loss * in_episode_bound.unsqueeze(-1) return loss.mean() class SpatialSoftmax(nn.Module): """ Spatial Soft Argmax operation described in "Deep Spatial Autoencoders for Visuomotor Learning" by Finn et al. (https://arxiv.org/pdf/1509.06113). A minimal port of the robomimic implementation. At a high level, this takes 2D feature maps (from a convnet/ViT) and returns the "center of mass" of activations of each channel, i.e., keypoints in the image space for the policy to focus on. Example: take feature maps of size (512x10x12). We generate a grid of normalized coordinates (10x12x2): ----------------------------------------------------- | (-1., -1.) | (-0.82, -1.) | ... | (1., -1.) | | (-1., -0.78) | (-0.82, -0.78) | ... | (1., -0.78) | | ... | ... | ... | ... | | (-1., 1.) | (-0.82, 1.) | ... | (1., 1.) | ----------------------------------------------------- This is achieved by applying channel-wise softmax over the activations (512x120) and computing the dot product with the coordinates (120x2) to get expected points of maximal activation (512x2). The example above results in 512 keypoints (corresponding to the 512 input channels). We can optionally provide num_kp != None to control the number of keypoints. This is achieved by a first applying a learnable linear mapping (in_channels, H, W) -> (num_kp, H, W). """ def __init__(self, input_shape, num_kp=None): """ Args: input_shape (list): (C, H, W) input feature map shape. num_kp (int): number of keypoints in output. If None, output will have the same number of channels as input. """ super().__init__() assert len(input_shape) == 3 self._in_c, self._in_h, self._in_w = input_shape if num_kp is not None: self.nets = torch.nn.Conv2d(self._in_c, num_kp, kernel_size=1) self._out_c = num_kp else: self.nets = None self._out_c = self._in_c # we could use torch.linspace directly but that seems to behave slightly differently than numpy # and causes a small degradation in pc_success of pre-trained models. pos_x, pos_y = np.meshgrid(np.linspace(-1.0, 1.0, self._in_w), np.linspace(-1.0, 1.0, self._in_h)) pos_x = torch.from_numpy(pos_x.reshape(self._in_h * self._in_w, 1)).float() pos_y = torch.from_numpy(pos_y.reshape(self._in_h * self._in_w, 1)).float() # register as buffer so it's moved to the correct device. self.register_buffer("pos_grid", torch.cat([pos_x, pos_y], dim=1)) def forward(self, features: Tensor) -> Tensor: """ Args: features: (B, C, H, W) input feature maps. Returns: (B, K, 2) image-space coordinates of keypoints. """ if self.nets is not None: features = self.nets(features) # [B, K, H, W] -> [B * K, H * W] where K is number of keypoints features = features.reshape(-1, self._in_h * self._in_w) # 2d softmax normalization attention = F.softmax(features, dim=-1) # [B * K, H * W] x [H * W, 2] -> [B * K, 2] for spatial coordinate mean in x and y dimensions expected_xy = attention @ self.pos_grid # reshape to [B, K, 2] feature_keypoints = expected_xy.view(-1, self._out_c, 2) return feature_keypoints class DiffusionRgbEncoder(nn.Module): """Encoder an RGB image into a 1D feature vector. Includes the ability to normalize and crop the image first. """ def __init__(self, config: DiffusionConfig): super().__init__() # Set up optional preprocessing. if config.crop_shape is not None: self.do_crop = True # Always use center crop for eval self.center_crop = torchvision.transforms.CenterCrop(config.crop_shape) if config.crop_is_random: self.maybe_random_crop = torchvision.transforms.RandomCrop(config.crop_shape) else: self.maybe_random_crop = self.center_crop else: self.do_crop = False # Set up backbone. backbone_model = getattr(torchvision.models, config.vision_backbone)( weights=config.pretrained_backbone_weights ) # Note: This assumes that the layer4 feature map is children()[-3] # TODO(alexander-soare): Use a safer alternative. self.backbone = nn.Sequential(*(list(backbone_model.children())[:-2])) if config.use_group_norm: if config.pretrained_backbone_weights: raise ValueError( "You can't replace BatchNorm in a pretrained model without ruining the weights!" ) self.backbone = _replace_submodules( root_module=self.backbone, predicate=lambda x: isinstance(x, nn.BatchNorm2d), func=lambda x: nn.GroupNorm(num_groups=x.num_features // 16, num_channels=x.num_features), ) # Set up pooling and final layers. # Use a dry run to get the feature map shape. # The dummy input should take the number of image channels from `config.input_shapes` and it should # use the height and width from `config.crop_shape` if it is provided, otherwise it should use the # height and width from `config.input_shapes`. image_keys = [k for k in config.input_shapes if k.startswith("observation.image")] # Note: we have a check in the config class to make sure all images have the same shape. image_key = image_keys[0] dummy_input_h_w = ( config.crop_shape if config.crop_shape is not None else config.input_shapes[image_key][1:] ) dummy_input = torch.zeros(size=(1, config.input_shapes[image_key][0], *dummy_input_h_w)) with torch.inference_mode(): dummy_feature_map = self.backbone(dummy_input) feature_map_shape = tuple(dummy_feature_map.shape[1:]) self.pool = SpatialSoftmax(feature_map_shape, num_kp=config.spatial_softmax_num_keypoints) self.feature_dim = config.spatial_softmax_num_keypoints * 2 self.out = nn.Linear(config.spatial_softmax_num_keypoints * 2, self.feature_dim) self.relu = nn.ReLU() def forward(self, x: Tensor) -> Tensor: """ Args: x: (B, C, H, W) image tensor with pixel values in [0, 1]. Returns: (B, D) image feature. """ # Preprocess: maybe crop (if it was set up in the __init__). if self.do_crop: if self.training: # noqa: SIM108 x = self.maybe_random_crop(x) else: # Always use center crop for eval. x = self.center_crop(x) # Extract backbone feature. x = torch.flatten(self.pool(self.backbone(x)), start_dim=1) # Final linear layer with non-linearity. x = self.relu(self.out(x)) return x def _replace_submodules( root_module: nn.Module, predicate: Callable[[nn.Module], bool], func: Callable[[nn.Module], nn.Module] ) -> nn.Module: """ Args: root_module: The module for which the submodules need to be replaced predicate: Takes a module as an argument and must return True if the that module is to be replaced. func: Takes a module as an argument and returns a new module to replace it with. Returns: The root module with its submodules replaced. """ if predicate(root_module): return func(root_module) replace_list = [k.split(".") for k, m in root_module.named_modules(remove_duplicate=True) if predicate(m)] for *parents, k in replace_list: parent_module = root_module if len(parents) > 0: parent_module = root_module.get_submodule(".".join(parents)) if isinstance(parent_module, nn.Sequential): src_module = parent_module[int(k)] else: src_module = getattr(parent_module, k) tgt_module = func(src_module) if isinstance(parent_module, nn.Sequential): parent_module[int(k)] = tgt_module else: setattr(parent_module, k, tgt_module) # verify that all BN are replaced assert not any(predicate(m) for _, m in root_module.named_modules(remove_duplicate=True)) return root_module class DiffusionSinusoidalPosEmb(nn.Module): """1D sinusoidal positional embeddings as in Attention is All You Need.""" def __init__(self, dim: int): super().__init__() self.dim = dim def forward(self, x: Tensor) -> Tensor: device = x.device half_dim = self.dim // 2 emb = math.log(10000) / (half_dim - 1) emb = torch.exp(torch.arange(half_dim, device=device) * -emb) emb = x.unsqueeze(-1) * emb.unsqueeze(0) emb = torch.cat((emb.sin(), emb.cos()), dim=-1) return emb class DiffusionConv1dBlock(nn.Module): """Conv1d --> GroupNorm --> Mish""" def __init__(self, inp_channels, out_channels, kernel_size, n_groups=8): super().__init__() self.block = nn.Sequential( nn.Conv1d(inp_channels, out_channels, kernel_size, padding=kernel_size // 2), nn.GroupNorm(n_groups, out_channels), nn.Mish(), ) def forward(self, x): return self.block(x) class DiffusionConditionalUnet1d(nn.Module): """A 1D convolutional UNet with FiLM modulation for conditioning. Note: this removes local conditioning as compared to the original diffusion policy code. """ def __init__(self, config: DiffusionConfig, global_cond_dim: int): super().__init__() self.config = config # Encoder for the diffusion timestep. self.diffusion_step_encoder = nn.Sequential( DiffusionSinusoidalPosEmb(config.diffusion_step_embed_dim), nn.Linear(config.diffusion_step_embed_dim, config.diffusion_step_embed_dim * 4), nn.Mish(), nn.Linear(config.diffusion_step_embed_dim * 4, config.diffusion_step_embed_dim), ) # The FiLM conditioning dimension. cond_dim = config.diffusion_step_embed_dim + global_cond_dim # In channels / out channels for each downsampling block in the Unet's encoder. For the decoder, we # just reverse these. in_out = [(config.output_shapes["action"][0], config.down_dims[0])] + list( zip(config.down_dims[:-1], config.down_dims[1:], strict=True) ) # Unet encoder. common_res_block_kwargs = { "cond_dim": cond_dim, "kernel_size": config.kernel_size, "n_groups": config.n_groups, "use_film_scale_modulation": config.use_film_scale_modulation, } self.down_modules = nn.ModuleList([]) for ind, (dim_in, dim_out) in enumerate(in_out): is_last = ind >= (len(in_out) - 1) self.down_modules.append( nn.ModuleList( [ DiffusionConditionalResidualBlock1d(dim_in, dim_out, **common_res_block_kwargs), DiffusionConditionalResidualBlock1d(dim_out, dim_out, **common_res_block_kwargs), # Downsample as long as it is not the last block. nn.Conv1d(dim_out, dim_out, 3, 2, 1) if not is_last else nn.Identity(), ] ) ) # Processing in the middle of the auto-encoder. self.mid_modules = nn.ModuleList( [ DiffusionConditionalResidualBlock1d( config.down_dims[-1], config.down_dims[-1], **common_res_block_kwargs ), DiffusionConditionalResidualBlock1d( config.down_dims[-1], config.down_dims[-1], **common_res_block_kwargs ), ] ) # Unet decoder. self.up_modules = nn.ModuleList([]) for ind, (dim_out, dim_in) in enumerate(reversed(in_out[1:])): is_last = ind >= (len(in_out) - 1) self.up_modules.append( nn.ModuleList( [ # dim_in * 2, because it takes the encoder's skip connection as well DiffusionConditionalResidualBlock1d(dim_in * 2, dim_out, **common_res_block_kwargs), DiffusionConditionalResidualBlock1d(dim_out, dim_out, **common_res_block_kwargs), # Upsample as long as it is not the last block. nn.ConvTranspose1d(dim_out, dim_out, 4, 2, 1) if not is_last else nn.Identity(), ] ) ) self.final_conv = nn.Sequential( DiffusionConv1dBlock(config.down_dims[0], config.down_dims[0], kernel_size=config.kernel_size), nn.Conv1d(config.down_dims[0], config.output_shapes["action"][0], 1), ) def forward(self, x: Tensor, timestep: Tensor | int, global_cond=None) -> Tensor: """ Args: x: (B, T, input_dim) tensor for input to the Unet. timestep: (B,) tensor of (timestep_we_are_denoising_from - 1). global_cond: (B, global_cond_dim) output: (B, T, input_dim) Returns: (B, T, input_dim) diffusion model prediction. """ # For 1D convolutions we'll need feature dimension first. x = einops.rearrange(x, "b t d -> b d t") timesteps_embed = self.diffusion_step_encoder(timestep) # If there is a global conditioning feature, concatenate it to the timestep embedding. if global_cond is not None: global_feature = torch.cat([timesteps_embed, global_cond], axis=-1) else: global_feature = timesteps_embed # Run encoder, keeping track of skip features to pass to the decoder. encoder_skip_features: list[Tensor] = [] for resnet, resnet2, downsample in self.down_modules: x = resnet(x, global_feature) x = resnet2(x, global_feature) encoder_skip_features.append(x) x = downsample(x) for mid_module in self.mid_modules: x = mid_module(x, global_feature) # Run decoder, using the skip features from the encoder. for resnet, resnet2, upsample in self.up_modules: x = torch.cat((x, encoder_skip_features.pop()), dim=1) x = resnet(x, global_feature) x = resnet2(x, global_feature) x = upsample(x) x = self.final_conv(x) x = einops.rearrange(x, "b d t -> b t d") return x class DiffusionConditionalResidualBlock1d(nn.Module): """ResNet style 1D convolutional block with FiLM modulation for conditioning.""" def __init__( self, in_channels: int, out_channels: int, cond_dim: int, kernel_size: int = 3, n_groups: int = 8, # Set to True to do scale modulation with FiLM as well as bias modulation (defaults to False meaning # FiLM just modulates bias). use_film_scale_modulation: bool = False, ): super().__init__() self.use_film_scale_modulation = use_film_scale_modulation self.out_channels = out_channels self.conv1 = DiffusionConv1dBlock(in_channels, out_channels, kernel_size, n_groups=n_groups) # FiLM modulation (https://arxiv.org/abs/1709.07871) outputs per-channel bias and (maybe) scale. cond_channels = out_channels * 2 if use_film_scale_modulation else out_channels self.cond_encoder = nn.Sequential(nn.Mish(), nn.Linear(cond_dim, cond_channels)) self.conv2 = DiffusionConv1dBlock(out_channels, out_channels, kernel_size, n_groups=n_groups) # A final convolution for dimension matching the residual (if needed). self.residual_conv = ( nn.Conv1d(in_channels, out_channels, 1) if in_channels != out_channels else nn.Identity() ) def forward(self, x: Tensor, cond: Tensor) -> Tensor: """ Args: x: (B, in_channels, T) cond: (B, cond_dim) Returns: (B, out_channels, T) """ out = self.conv1(x) # Get condition embedding. Unsqueeze for broadcasting to `out`, resulting in (B, out_channels, 1). cond_embed = self.cond_encoder(cond).unsqueeze(-1) if self.use_film_scale_modulation: # Treat the embedding as a list of scales and biases. scale = cond_embed[:, : self.out_channels] bias = cond_embed[:, self.out_channels :] out = scale * out + bias else: # Treat the embedding as biases. out = out + cond_embed out = self.conv2(out) out = out + self.residual_conv(x) return out
lerobot/lerobot/common/policies/diffusion/modeling_diffusion.py/0
{ "file_path": "lerobot/lerobot/common/policies/diffusion/modeling_diffusion.py", "repo_id": "lerobot", "token_count": 14052 }
165
from typing import Protocol class Robot(Protocol): def init_teleop(self): ... def run_calibration(self): ... def teleop_step(self, record_data=False): ... def capture_observation(self): ... def send_action(self, action): ...
lerobot/lerobot/common/robot_devices/robots/utils.py/0
{ "file_path": "lerobot/lerobot/common/robot_devices/robots/utils.py", "repo_id": "lerobot", "token_count": 87 }
166
# @package _global_ # Defaults for training for the PushT dataset as per https://github.com/real-stanford/diffusion_policy. # Note: We do not track EMA model weights as we discovered it does not improve the results. See # https://github.com/huggingface/lerobot/pull/134 for more details. seed: 100000 dataset_repo_id: lerobot/pusht override_dataset_stats: # TODO(rcadene, alexander-soare): should we remove image stats as well? do we use a pretrained vision model? observation.image: mean: [[[0.5]], [[0.5]], [[0.5]]] # (c,1,1) std: [[[0.5]], [[0.5]], [[0.5]]] # (c,1,1) # TODO(rcadene, alexander-soare): we override state and action stats to use the same as the pretrained model # from the original codebase, but we should remove these and train our own pretrained model observation.state: min: [13.456424, 32.938293] max: [496.14618, 510.9579] action: min: [12.0, 25.0] max: [511.0, 511.0] training: offline_steps: 200000 online_steps: 0 eval_freq: 25000 save_freq: 25000 save_checkpoint: true batch_size: 64 grad_clip_norm: 10 lr: 1.0e-4 lr_scheduler: cosine lr_warmup_steps: 500 adam_betas: [0.95, 0.999] adam_eps: 1.0e-8 adam_weight_decay: 1.0e-6 online_steps_between_rollouts: 1 delta_timestamps: observation.image: "[i / ${fps} for i in range(1 - ${policy.n_obs_steps}, 1)]" observation.state: "[i / ${fps} for i in range(1 - ${policy.n_obs_steps}, 1)]" action: "[i / ${fps} for i in range(1 - ${policy.n_obs_steps}, 1 - ${policy.n_obs_steps} + ${policy.horizon})]" # The original implementation doesn't sample frames for the last 7 steps, # which avoids excessive padding and leads to improved training results. drop_n_last_frames: 7 # ${policy.horizon} - ${policy.n_action_steps} - ${policy.n_obs_steps} + 1 eval: n_episodes: 50 batch_size: 50 policy: name: diffusion # Input / output structure. n_obs_steps: 2 horizon: 16 n_action_steps: 8 input_shapes: # TODO(rcadene, alexander-soare): add variables for height and width from the dataset/env? observation.image: [3, 96, 96] observation.state: ["${env.state_dim}"] output_shapes: action: ["${env.action_dim}"] # Normalization / Unnormalization input_normalization_modes: observation.image: mean_std observation.state: min_max output_normalization_modes: action: min_max # Architecture / modeling. # Vision backbone. vision_backbone: resnet18 crop_shape: [84, 84] crop_is_random: True pretrained_backbone_weights: null use_group_norm: True spatial_softmax_num_keypoints: 32 # Unet. down_dims: [512, 1024, 2048] kernel_size: 5 n_groups: 8 diffusion_step_embed_dim: 128 use_film_scale_modulation: True # Noise scheduler. noise_scheduler_type: DDPM num_train_timesteps: 100 beta_schedule: squaredcos_cap_v2 beta_start: 0.0001 beta_end: 0.02 prediction_type: epsilon # epsilon / sample clip_sample: True clip_sample_range: 1.0 # Inference num_inference_steps: null # if not provided, defaults to `num_train_timesteps` # Loss computation do_mask_loss_for_padding: false
lerobot/lerobot/configs/policy/diffusion.yaml/0
{ "file_path": "lerobot/lerobot/configs/policy/diffusion.yaml", "repo_id": "lerobot", "token_count": 1193 }
167
version https://git-lfs.github.com/spec/v1 oid sha256:1bde721d645959783d50753d277f91b435a06b5494ab16d1a21af159cce18421 size 247
lerobot/tests/data/lerobot/aloha_static_fork_pick_up/train/state.json/0
{ "file_path": "lerobot/tests/data/lerobot/aloha_static_fork_pick_up/train/state.json", "repo_id": "lerobot", "token_count": 62 }
168
version https://git-lfs.github.com/spec/v1 oid sha256:5624d9494a71d7c44b91d512cfe3e0db0eca97fae168be0d2fd7ee98af17d4e7 size 240928
lerobot/tests/data/lerobot/aloha_static_thread_velcro/train/data-00000-of-00001.arrow/0
{ "file_path": "lerobot/tests/data/lerobot/aloha_static_thread_velcro/train/data-00000-of-00001.arrow", "repo_id": "lerobot", "token_count": 69 }
169
version https://git-lfs.github.com/spec/v1 oid sha256:1af8d36fca4fc62d47c2cfe8829e6d341e08c7667ca9bed1da63bf66c4f0f81d size 247
lerobot/tests/data/lerobot/aloha_static_vinh_cup_left/train/state.json/0
{ "file_path": "lerobot/tests/data/lerobot/aloha_static_vinh_cup_left/train/state.json", "repo_id": "lerobot", "token_count": 68 }
170
version https://git-lfs.github.com/spec/v1 oid sha256:1e737caa14a3aa1d81986faae579f81fe6b39ebc91e1ad1256c17c7e1b75e9da size 188
lerobot/tests/data/lerobot/pusht/meta_data/info.json/0
{ "file_path": "lerobot/tests/data/lerobot/pusht/meta_data/info.json", "repo_id": "lerobot", "token_count": 68 }
171
version https://git-lfs.github.com/spec/v1 oid sha256:686d9d9bad8815d67597b997058d9853a04e5bdbe4eed038f4da9806f867af3d size 1098
lerobot/tests/data/lerobot/pusht_keypoints/train/dataset_info.json/0
{ "file_path": "lerobot/tests/data/lerobot/pusht_keypoints/train/dataset_info.json", "repo_id": "lerobot", "token_count": 66 }
172
version https://git-lfs.github.com/spec/v1 oid sha256:53172b773d4a78bb3140f10280105c2c4ebcb467f3097579988d42cb87790ab9 size 3687117
lerobot/tests/data/save_dataset_to_safetensors/lerobot/aloha_sim_insertion_human/frame_251.safetensors/0
{ "file_path": "lerobot/tests/data/save_dataset_to_safetensors/lerobot/aloha_sim_insertion_human/frame_251.safetensors", "repo_id": "lerobot", "token_count": 63 }
173
version https://git-lfs.github.com/spec/v1 oid sha256:0dc691503e7d90b2086bb408e89a65f772ce5ee6e3562ef8c127bcb09bd90851 size 40551392
lerobot/tests/data/save_image_transforms_to_safetensors/single_transforms.safetensors/0
{ "file_path": "lerobot/tests/data/save_image_transforms_to_safetensors/single_transforms.safetensors", "repo_id": "lerobot", "token_count": 67 }
174
version https://git-lfs.github.com/spec/v1 oid sha256:bea60cce42d324f539dd3bca1e66b5ba6391838fdcadb00efc25f3240edb529a size 33600
lerobot/tests/data/save_policy_to_safetensors/dora_aloha_real_act_real_no_state/param_stats.safetensors/0
{ "file_path": "lerobot/tests/data/save_policy_to_safetensors/dora_aloha_real_act_real_no_state/param_stats.safetensors", "repo_id": "lerobot", "token_count": 67 }
175
#!/usr/bin/env python # Copyright 2024 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import importlib import gymnasium as gym import pytest import lerobot from lerobot.common.policies.act.modeling_act import ACTPolicy from lerobot.common.policies.diffusion.modeling_diffusion import DiffusionPolicy from lerobot.common.policies.tdmpc.modeling_tdmpc import TDMPCPolicy from lerobot.common.policies.vqbet.modeling_vqbet import VQBeTPolicy from tests.utils import require_env @pytest.mark.parametrize("env_name, task_name", lerobot.env_task_pairs) @require_env def test_available_env_task(env_name: str, task_name: list): """ This test verifies that all environments listed in `lerobot/__init__.py` can be successfully imported — if they're installed — and that their `available_tasks_per_env` are valid. """ package_name = f"gym_{env_name}" importlib.import_module(package_name) gym_handle = f"{package_name}/{task_name}" assert gym_handle in gym.envs.registry, gym_handle def test_available_policies(): """ This test verifies that the class attribute `name` for all policies is consistent with those listed in `lerobot/__init__.py`. """ policy_classes = [ ACTPolicy, DiffusionPolicy, TDMPCPolicy, VQBeTPolicy, ] policies = [pol_cls.name for pol_cls in policy_classes] assert set(policies) == set(lerobot.available_policies), policies def test_print(): print(lerobot.available_envs) print(lerobot.available_tasks_per_env) print(lerobot.available_datasets) print(lerobot.available_datasets_per_env) print(lerobot.available_real_world_datasets) print(lerobot.available_policies) print(lerobot.available_policies_per_env)
lerobot/tests/test_available.py/0
{ "file_path": "lerobot/tests/test_available.py", "repo_id": "lerobot", "token_count": 810 }
176
#!/usr/bin/env python # Copyright 2024 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import platform from functools import wraps import pytest import torch from lerobot.common.utils.import_utils import is_package_available # Pass this as the first argument to init_hydra_config. DEFAULT_CONFIG_PATH = "lerobot/configs/default.yaml" KOCH_ROBOT_CONFIG_PATH = "lerobot/configs/robot/koch.yaml" DEVICE = "cuda" if torch.cuda.is_available() else "cpu" def require_x86_64_kernel(func): """ Decorator that skips the test if plateform device is not an x86_64 cpu. """ from functools import wraps @wraps(func) def wrapper(*args, **kwargs): if platform.machine() != "x86_64": pytest.skip("requires x86_64 plateform") return func(*args, **kwargs) return wrapper def require_cpu(func): """ Decorator that skips the test if device is not cpu. """ from functools import wraps @wraps(func) def wrapper(*args, **kwargs): if DEVICE != "cpu": pytest.skip("requires cpu") return func(*args, **kwargs) return wrapper def require_cuda(func): """ Decorator that skips the test if cuda is not available. """ from functools import wraps @wraps(func) def wrapper(*args, **kwargs): if not torch.cuda.is_available(): pytest.skip("requires cuda") return func(*args, **kwargs) return wrapper def require_env(func): """ Decorator that skips the test if the required environment package is not installed. As it need 'env_name' in args, it also checks whether it is provided as an argument. If 'env_name' is None, this check is skipped. """ @wraps(func) def wrapper(*args, **kwargs): # Determine if 'env_name' is provided and extract its value arg_names = func.__code__.co_varnames[: func.__code__.co_argcount] if "env_name" in arg_names: # Get the index of 'env_name' and retrieve the value from args index = arg_names.index("env_name") env_name = args[index] if len(args) > index else kwargs.get("env_name") else: raise ValueError("Function does not have 'env_name' as an argument.") # Perform the package check package_name = f"gym_{env_name}" if env_name is not None and not is_package_available(package_name): pytest.skip(f"gym-{env_name} not installed") return func(*args, **kwargs) return wrapper def require_package_arg(func): """ Decorator that skips the test if the required package is not installed. This is similar to `require_env` but more general in that it can check any package (not just environments). As it need 'required_packages' in args, it also checks whether it is provided as an argument. If 'required_packages' is None, this check is skipped. """ @wraps(func) def wrapper(*args, **kwargs): # Determine if 'required_packages' is provided and extract its value arg_names = func.__code__.co_varnames[: func.__code__.co_argcount] if "required_packages" in arg_names: # Get the index of 'required_packages' and retrieve the value from args index = arg_names.index("required_packages") required_packages = args[index] if len(args) > index else kwargs.get("required_packages") else: raise ValueError("Function does not have 'required_packages' as an argument.") if required_packages is None: return func(*args, **kwargs) # Perform the package check for package in required_packages: if not is_package_available(package): pytest.skip(f"{package} not installed") return func(*args, **kwargs) return wrapper def require_package(package_name): """ Decorator that skips the test if the specified package is not installed. """ def decorator(func): @wraps(func) def wrapper(*args, **kwargs): if not is_package_available(package_name): pytest.skip(f"{package_name} not installed") return func(*args, **kwargs) return wrapper return decorator def require_koch(func): """ Decorator that skips the test if an alexander koch robot is not available """ @wraps(func) def wrapper(*args, **kwargs): # Access the pytest request context to get the is_koch_available fixture request = kwargs.get("request") if request is None: raise ValueError("The 'request' fixture must be passed to the test function as a parameter.") # The function `is_koch_available` is defined in `tests/conftest.py` if not request.getfixturevalue("is_koch_available"): pytest.skip("An alexander koch robot is not available.") return func(*args, **kwargs) return wrapper
lerobot/tests/utils.py/0
{ "file_path": "lerobot/tests/utils.py", "repo_id": "lerobot", "token_count": 2057 }
177
import gradio as gr import torch from transformers import AutoFeatureExtractor, AutoTokenizer, set_seed from parler_tts import ParlerTTSForConditionalGeneration device = "cuda:0" if torch.cuda.is_available() else "cpu" repo_id = "parler-tts/parler_tts_mini_v0.1" model = ParlerTTSForConditionalGeneration.from_pretrained(repo_id).to(device) tokenizer = AutoTokenizer.from_pretrained(repo_id) feature_extractor = AutoFeatureExtractor.from_pretrained(repo_id) SAMPLE_RATE = feature_extractor.sampling_rate SEED = 41 default_text = "Please surprise me and speak in whatever voice you enjoy." title = "# Parler-TTS </div>" examples = [ [ "'This is the best time of my life, Bartley,' she said happily.", "A female speaker with a slightly low-pitched, quite monotone voice delivers her words at a slightly faster-than-average pace in a confined space with very clear audio.", ], [ "Montrose also, after having experienced still more variety of good and bad fortune, threw down his arms, and retired out of the kingdom. ", "A male speaker with a slightly high-pitched voice delivering his words at a slightly slow pace in a small, confined space with a touch of background noise and a quite monotone tone.", ], [ "montrose also after having experienced still more variety of good and bad fortune threw down his arms and retired out of the kingdom", "A male speaker with a low-pitched voice delivering his words at a fast pace in a small, confined space with a lot of background noise and an animated tone.", ], ] def gen_tts(text, description): inputs = tokenizer(description, return_tensors="pt").to(device) prompt = tokenizer(text, return_tensors="pt").to(device) set_seed(SEED) generation = model.generate( input_ids=inputs.input_ids, prompt_input_ids=prompt.input_ids, do_sample=True, temperature=1.0 ) audio_arr = generation.cpu().numpy().squeeze() return (SAMPLE_RATE, audio_arr) css = """ #share-btn-container { display: flex; padding-left: 0.5rem !important; padding-right: 0.5rem !important; background-color: #000000; justify-content: center; align-items: center; border-radius: 9999px !important; width: 13rem; margin-top: 10px; margin-left: auto; flex: unset !important; } #share-btn { all: initial; color: #ffffff; font-weight: 600; cursor: pointer; font-family: 'IBM Plex Sans', sans-serif; margin-left: 0.5rem !important; padding-top: 0.25rem !important; padding-bottom: 0.25rem !important; right:0; } #share-btn * { all: unset !important; } #share-btn-container div:nth-child(-n+2){ width: auto !important; min-height: 0px !important; } #share-btn-container .wrap { display: none !important; } """ with gr.Blocks(css=css) as block: gr.Markdown(title) with gr.Row(): with gr.Column(): input_text = gr.Textbox(label="Input Text", lines=2, value=default_text, elem_id="input_text") description = gr.Textbox(label="Description", lines=2, value="", elem_id="input_description") run_button = gr.Button("Generate Audio", variant="primary") with gr.Column(): audio_out = gr.Audio(label="Parler-TTS generation", type="numpy", elem_id="audio_out") inputs = [input_text, description] outputs = [audio_out] gr.Examples(examples=examples, fn=gen_tts, inputs=inputs, outputs=outputs, cache_examples=True) run_button.click(fn=gen_tts, inputs=inputs, outputs=outputs, queue=True) block.queue() block.launch(share=True)
parler-tts/helpers/gradio_demo/app.py/0
{ "file_path": "parler-tts/helpers/gradio_demo/app.py", "repo_id": "parler-tts", "token_count": 1577 }
178
# coding=utf-8 # Copyright 2024 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ PyTorch ParlerTTS model.""" import copy import inspect import math import random from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import CrossEntropyLoss from transformers import AutoConfig, AutoModel, AutoModelForTextEncoding from transformers.activations import ACT2FN from transformers.cache_utils import ( Cache, DynamicCache, EncoderDecoderCache, SlidingWindowCache, StaticCache, ) from transformers.generation.configuration_utils import GenerationConfig from transformers.generation.logits_process import LogitsProcessorList from transformers.generation.stopping_criteria import StoppingCriteriaList from transformers.modeling_attn_mask_utils import ( AttentionMaskConverter, _prepare_4d_attention_mask, _prepare_4d_attention_mask_for_sdpa, ) from transformers.modeling_outputs import ( BaseModelOutput, BaseModelOutputWithPastAndCrossAttentions, CausalLMOutputWithCrossAttentions, ModelOutput, Seq2SeqLMOutput, ) from transformers.modeling_utils import PreTrainedModel from transformers.utils import ( add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings, ) from transformers.utils.import_utils import is_flash_attn_2_available, is_flash_attn_greater_or_equal_2_10 from .configuration_parler_tts import ParlerTTSConfig, ParlerTTSDecoderConfig from .dac_wrapper import DACConfig, DACModel AutoConfig.register("dac", DACConfig) AutoModel.register(DACConfig, DACModel) if TYPE_CHECKING: from transformers.generation.streamers import BaseStreamer logger = logging.get_logger(__name__) if is_flash_attn_2_available(): from flash_attn import flash_attn_func, flash_attn_varlen_func from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa else: logger.warn("Flash attention 2 is not installed") _CONFIG_FOR_DOC = "ParlerTTSConfig" _CHECKPOINT_FOR_DOC = "facebook/parler_tts-small" MUSICGEN_PRETRAINED_MODEL_ARCHIVE_LIST = [ "facebook/parler_tts-small", # See all ParlerTTS models at https://huggingface.co/models?filter=parler_tts ] NEED_SETUP_CACHE_CLASSES_MAPPING = {"static": StaticCache, "sliding_window": SlidingWindowCache} def apply_delay_pattern_mask(input_ids, decoder_pad_token_mask): """Apply a delay pattern mask to the decoder input ids, only preserving predictions where the mask is set to -1, and otherwise setting to the value detailed in the mask.""" seq_len = input_ids.shape[-1] decoder_pad_token_mask = decoder_pad_token_mask[..., :seq_len] input_ids = torch.where(decoder_pad_token_mask == -1, input_ids, decoder_pad_token_mask) return input_ids def build_delay_pattern_mask( input_ids: torch.LongTensor, bos_token_id: int, pad_token_id: int, max_length: int, num_codebooks: int ): """Build a delayed pattern mask to the input_ids. Each codebook is offset by the previous codebook by one, giving a delayed pattern mask at the start of sequence and end of sequence. Take the example where there are 4 codebooks and a max sequence length of 8, we have the delayed pattern mask of shape `(codebooks, seq_len)`: - [B, -1, -1, -1, -1, P, P, P] - [B, B, -1, -1, -1, -1, P, P] - [B, B, B, -1, -1, -1, -1, P] - [B, B, B, B, -1, -1, -1, -1] where P is the special padding token id and -1 indicates that the token is valid for prediction. If we include a prompt (decoder input ids), the -1 positions indicate where new tokens should be predicted. Otherwise, the mask is set to the value in the prompt: - [B, a, b, -1, -1, P, P, P] - [B, B, c, d, -1, -1, P, P] - [B, B, B, e, f, -1, -1, P] - [B, B, B, B, g, h, -1, -1] where a-h indicate the input prompt (decoder input ids) that are offset by 1. Now, we only override the -1 tokens in our prediction. """ # (bsz * num_codebooks, seq_len) -> (bsz, num_codebooks, seq_len) input_ids = input_ids.reshape(-1, num_codebooks, input_ids.shape[-1]) bsz, num_codebooks, seq_len = input_ids.shape input_ids_shifted = torch.ones((bsz, num_codebooks, max_length), dtype=torch.long, device=input_ids.device) * -1 # we only apply the mask if we have a large enough seq len - otherwise we return as is if max_length < 2 * num_codebooks - 1: return input_ids.reshape(bsz * num_codebooks, -1), input_ids_shifted.reshape(bsz * num_codebooks, -1) # fill the shifted ids with the prompt entries, offset by the codebook idx for codebook in range(num_codebooks): # mono channel - loop over the codebooks one-by-one input_ids_shifted[:, codebook, codebook : seq_len + codebook] = input_ids[:, codebook] # construct a pattern mask that indicates the positions of padding tokens for each codebook # first fill the upper triangular part (the EOS padding) eos_delay_pattern = torch.triu( torch.ones((num_codebooks, max_length), dtype=torch.bool), diagonal=max_length - num_codebooks + 1 ) # then fill the lower triangular part (the BOS padding) bos_delay_pattern = torch.tril(torch.ones((num_codebooks, max_length), dtype=torch.bool)) bos_mask = ~(bos_delay_pattern).to(input_ids.device) eos_mask = ~(eos_delay_pattern).to(input_ids.device) mask = ~(bos_delay_pattern + eos_delay_pattern).to(input_ids.device) input_ids = mask * input_ids_shifted + ~bos_mask * bos_token_id + ~eos_mask * pad_token_id # find the first position to start generating - this is the first place we have the -1 token # and will always be in the first codebook (since it has no codebook offset) first_codebook_ids = input_ids[:, 0, :] start_ids = (first_codebook_ids == -1).nonzero()[:, 1] if len(start_ids) > 0: first_start_id = min(start_ids) else: # we have no tokens that need to be filled - return entire matrix of input ids first_start_id = seq_len # (bsz * num_codebooks, seq_len) -> (bsz, num_codebooks, seq_len) pattern_mask = input_ids.reshape(bsz * num_codebooks, -1) input_ids = input_ids[..., :first_start_id].reshape(bsz * num_codebooks, -1) return input_ids, pattern_mask # Copied from transformers.models.llama.modeling_llama.repeat_kv def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) """ batch, num_key_value_heads, slen, head_dim = hidden_states.shape if n_rep == 1: return hidden_states hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) @dataclass class ParlerTTSUnconditionalInput(ModelOutput): """ Args: encoder_outputs (`Tuple[torch.FloatTensor]` of length 1, with tensor shape `(batch_size, sequence_length, hidden_size)`): Sequence of hidden-states at the output of the last layer of the text encoder model. attention_mask (`torch.LongTensor`) of shape `(batch_size, sequence_length)`, *optional*): Encoder attention mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: 1 for tokens that are **not masked**, 0 for tokens that are **masked**. """ encoder_outputs: Tuple[torch.FloatTensor] = None attention_mask: torch.LongTensor = None # Copied from transformers.models.encoder_decoder.modeling_encoder_decoder.shift_tokens_right def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int): """ Shift input ids one token to the right. """ shifted_input_ids = input_ids.new_zeros(input_ids.shape) shifted_input_ids[:, 1:] = input_ids[:, :-1].clone() if decoder_start_token_id is None: raise ValueError("Make sure to set the decoder_start_token_id attribute of the model's configuration.") shifted_input_ids[:, 0] = decoder_start_token_id if pad_token_id is None: raise ValueError("Make sure to set the pad_token_id attribute of the model's configuration.") # replace possible -100 values in labels by `pad_token_id` shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id) return shifted_input_ids # Copied from transformers.models.musicgen.modeling_musicgen.MusicgenSinusoidalPositionalEmbedding with Musicgen->ParlerTTS class ParlerTTSSinusoidalPositionalEmbedding(nn.Module): """This module produces sinusoidal positional embeddings of any length.""" def __init__(self, num_positions: int, embedding_dim: int): super().__init__() self.embedding_dim = embedding_dim self.make_weights(num_positions, embedding_dim) def make_weights(self, num_embeddings: int, embedding_dim: int): emb_weights = self.get_embedding(num_embeddings, embedding_dim) if hasattr(self, "weights"): # in forward put the weights on the correct dtype and device of the param emb_weights = emb_weights.to(dtype=self.weights.dtype, device=self.weights.device) self.weights = nn.Parameter(emb_weights) self.weights.requires_grad = False self.weights.detach_() @staticmethod def get_embedding(num_embeddings: int, embedding_dim: int): """ Build sinusoidal embeddings. This matches the implementation in tensor2tensor, but differs slightly from the description in Section 3.5 of "Attention Is All You Need". """ half_dim = embedding_dim // 2 emb = math.log(10000) / (half_dim - 1) emb = torch.exp(torch.arange(half_dim, dtype=torch.int64).float() * -emb) emb = torch.arange(num_embeddings, dtype=torch.int64).float().unsqueeze(1) * emb.unsqueeze(0) emb = torch.cat([torch.cos(emb), torch.sin(emb)], dim=1).view(num_embeddings, -1) if embedding_dim % 2 == 1: # zero pad emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1) return emb.to(torch.get_default_dtype()) @torch.no_grad() def forward(self, input_ids: torch.Tensor, past_key_values_length: int = 0): bsz, seq_len, _ = input_ids.size() # Create the position ids from the input token ids. position_ids = torch.arange(seq_len, device=input_ids.device) + past_key_values_length # expand embeddings if needed if seq_len > self.weights.size(0): self.make_weights(seq_len + self.offset, self.embedding_dim) return self.weights.index_select(0, position_ids.view(-1)).detach() # Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->ParlerTTS class ParlerTTSRotaryEmbedding(nn.Module): def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0): super().__init__() self.scaling_factor = scaling_factor self.dim = dim self.max_position_embeddings = max_position_embeddings self.base = base inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2, dtype=torch.int64).float().to(device) / self.dim)) self.register_buffer("inv_freq", inv_freq, persistent=False) # For BC we register cos and sin cached self.max_seq_len_cached = max_position_embeddings t = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.int64).type_as(self.inv_freq) t = t / self.scaling_factor freqs = torch.outer(t, self.inv_freq) # Different from paper, but it uses a different permutation in order to obtain the same calculation emb = torch.cat((freqs, freqs), dim=-1) self.register_buffer("_cos_cached", emb.cos().to(torch.get_default_dtype()), persistent=False) self.register_buffer("_sin_cached", emb.sin().to(torch.get_default_dtype()), persistent=False) # Ignore copy @torch.no_grad() def forward(self, device_type, position_ids): # x: [bs, num_attention_heads, seq_len, head_size] inv_freq_expanded = self.inv_freq[None, :, None].expand(position_ids.shape[0], -1, 1) position_ids_expanded = position_ids[:, None, :] # Force float32 since bfloat16 loses precision on long contexts # See https://github.com/huggingface/transformers/pull/29285 device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu" with torch.autocast(device_type=device_type, enabled=False): freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2) emb = torch.cat((freqs, freqs), dim=-1) cos = emb.cos() sin = emb.sin() return cos, sin def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1) def apply_rotary_pos_emb(x, cos, sin, unsqueeze_dim=1): """Applies Rotary Position Embedding to the query and key tensors. Args: x (`torch.Tensor`): The tensor over which to apply the rope embeddings cos (`torch.Tensor`): The cosine part of the rotary embedding. sin (`torch.Tensor`): The sine part of the rotary embedding. unsqueeze_dim (`int`, *optional*, defaults to 1): The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. Returns: `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. """ cos = cos.unsqueeze(unsqueeze_dim) sin = sin.unsqueeze(unsqueeze_dim) x_embed = (x * cos) + (rotate_half(x) * sin) return x_embed class ParlerTTSAttention(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper. Modified to use GQA and MQA.""" def __init__( self, embed_dim: int, num_heads: int, num_key_value_heads: int, dropout: float = 0.0, is_decoder: bool = False, bias: bool = True, is_causal: bool = False, rope_embeddings: bool = False, layer_idx: Optional[int] = None, config: Optional[ParlerTTSDecoderConfig] = None, ): super().__init__() self.embed_dim = embed_dim self.num_heads = num_heads self.dropout = dropout self.head_dim = embed_dim // num_heads self.num_key_value_heads = num_key_value_heads self.num_key_value_groups = self.num_heads // self.num_key_value_heads self.config = config if (self.head_dim * num_heads) != self.embed_dim: raise ValueError( f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}" f" and `num_heads`: {num_heads})." ) self.scaling = self.head_dim**-0.5 self.is_decoder = is_decoder self.is_causal = is_causal if layer_idx is None and is_decoder: logger.warning_once( f"Instantiating a decoder {self.__class__.__name__} without passing `layer_idx` is not recommended and " "will to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` " "when creating this class." ) self.layer_idx = layer_idx self.k_proj = nn.Linear(embed_dim, self.num_key_value_heads * self.head_dim, bias=bias) self.v_proj = nn.Linear(embed_dim, self.num_key_value_heads * self.head_dim, bias=bias) self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias) self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias) self.rope_embeddings = rope_embeddings def _shape_query(self, tensor: torch.Tensor, seq_len: int, bsz: int): return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous() def _shape_key_value(self, tensor: torch.Tensor, seq_len: int, bsz: int): return tensor.view(bsz, seq_len, self.num_key_value_heads, self.head_dim).transpose(1, 2).contiguous() def forward( self, hidden_states: torch.Tensor, key_value_states: Optional[torch.Tensor] = None, past_key_value: Optional[EncoderDecoderCache] = None, attention_mask: Optional[torch.Tensor] = None, cos: Optional[torch.LongTensor] = None, sin: Optional[torch.LongTensor] = None, layer_head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False, cache_position: Optional[torch.LongTensor] = None, ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: """Input shape: Batch x Time x Channel""" # if key_value_states are provided this layer is used as a cross-attention layer # for the decoder is_cross_attention = key_value_states is not None bsz, tgt_len = hidden_states.shape[:2] # get query proj query_states = self.q_proj(hidden_states) * self.scaling query_states = self._shape_query(query_states, tgt_len, bsz) if self.rope_embeddings: query_states = apply_rotary_pos_emb(query_states, cos, sin) if past_key_value is not None: is_updated = past_key_value.is_updated.get(self.layer_idx) if is_cross_attention: # after the first generated id, we can subsequently re-use all key/value_states from cache past_key_value.is_updated[self.layer_idx] = True past_key_value = past_key_value.cross_attention_cache else: past_key_value = past_key_value.self_attention_cache # use key_value_states if cross attention current_states = key_value_states if key_value_states is not None else hidden_states if is_cross_attention and past_key_value and is_updated: # reuse k,v, cross_attentions key_states = past_key_value.key_cache[self.layer_idx] value_states = past_key_value.value_cache[self.layer_idx] else: key_states = self._shape_key_value(self.k_proj(current_states), -1, bsz) value_states = self._shape_key_value(self.v_proj(current_states), -1, bsz) if not is_cross_attention: # cached key states already have rope applied - only apply to new state key_states = apply_rotary_pos_emb(key_states, cos, sin) if self.rope_embeddings else key_states if past_key_value is not None: # save all key/value_states to cache to be re-used for fast auto-regressive generation cache_position = cache_position if not is_cross_attention else None key_states, value_states = past_key_value.update( key_states, value_states, self.layer_idx, {"cache_position": cache_position} ) key_states = repeat_kv(key_states, self.num_key_value_groups) value_states = repeat_kv(value_states, self.num_key_value_groups) attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) if attention_mask is not None: # no matter the length, we just slice it causal_mask = attention_mask[:, :, :, : key_states.shape[-2]] attn_weights = attn_weights + causal_mask attn_weights = nn.functional.softmax(attn_weights, dim=-1) if layer_head_mask is not None: if layer_head_mask.size() != (self.num_heads,): raise ValueError( f"Head mask for a single layer should be of size {(self.num_heads,)}, but is" f" {layer_head_mask.size()}" ) attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training) attn_output = torch.matmul(attn_probs, value_states) if attn_output.size() != (bsz, self.num_heads, tgt_len, self.head_dim): raise ValueError( f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is" f" {attn_output.size()}" ) attn_output = attn_output.transpose(1, 2) # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be # partitioned across GPUs when using tensor-parallelism. attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim) attn_output = self.out_proj(attn_output) return attn_output, attn_weights, past_key_value def _get_unpad_data(attention_mask): seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32) indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten() max_seqlen_in_batch = seqlens_in_batch.max().item() cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0)) return ( indices, cu_seqlens, max_seqlen_in_batch, ) # Copied from transformers.models.musicgen.modeling_musicgen.MusicgenFlashAttention2 with Musicgen->ParlerTTS class ParlerTTSFlashAttention2(ParlerTTSAttention): """ ParlerTTS flash attention module. This module inherits from `ParlerTTSAttention` as the weights of the module stays untouched. The only required change would be on the forward pass where it needs to correctly call the public API of flash attention and deal with padding tokens in case the input contains any of them. """ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1. # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0. # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left). self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10() def forward( self, hidden_states: torch.Tensor, key_value_states: Optional[torch.Tensor] = None, past_key_value: Optional[EncoderDecoderCache] = None, attention_mask: Optional[torch.Tensor] = None, cos: Optional[torch.LongTensor] = None, sin: Optional[torch.LongTensor] = None, layer_head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False, cache_position: Optional[torch.LongTensor] = None, ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: # ParlerTTSFlashAttention2 attention does not support output_attentions if isinstance(past_key_value, StaticCache): raise ValueError( "The `static` cache implementation is not compatible with `attn_implementation='flash_attention_2'`. " "Use `attn_implementation='sdpa'` in the meantime, and open an issue at https://github.com/huggingface/transformers" ) # if key_value_states are provided this layer is used as a cross-attention layer # for the decoder is_cross_attention = key_value_states is not None bsz, tgt_len = hidden_states.shape[:2] # get query proj query_states = self.q_proj(hidden_states).view(bsz, tgt_len, self.num_heads, self.head_dim) if self.rope_embeddings: query_states = apply_rotary_pos_emb(query_states, cos, sin, unsqueeze_dim=2) if past_key_value is not None: is_updated = past_key_value.is_updated.get(self.layer_idx) if is_cross_attention: # after the first generated id, we can subsequently re-use all key/value_states from cache past_key_value.is_updated[self.layer_idx] = True past_key_value = past_key_value.cross_attention_cache else: past_key_value = past_key_value.self_attention_cache # use key_value_states if cross attention current_states = key_value_states if key_value_states is not None else hidden_states if is_cross_attention and past_key_value and is_updated: # reuse k,v, cross_attentions key_states = past_key_value.key_cache[self.layer_idx] value_states = past_key_value.value_cache[self.layer_idx] else: key_states = self._shape_key_value(self.k_proj(current_states), -1, bsz) value_states = self._shape_key_value(self.v_proj(current_states), -1, bsz) if not is_cross_attention and self.rope_embeddings: # cached key states already have rope applied - only apply to new state key_states = apply_rotary_pos_emb(key_states, cos, sin) if past_key_value is not None: # save all key/value_states to cache to be re-used for fast auto-regressive generation cache_position = cache_position if not is_cross_attention else None key_states, value_states = past_key_value.update( key_states, value_states, self.layer_idx, {"cache_position": cache_position} ) # # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim] # # We would need to refactor the KV cache to be able to avoid many of these transpose/reshape/view. key_states = key_states.transpose(1, 2) value_states = value_states.transpose(1, 2) # In PEFT, usually we cast the layer norms in float32 for training stability reasons # therefore the input hidden states gets silently casted in float32. Hence, we need # cast them back in the correct dtype just to be sure everything works as expected. # This might slowdown training & inference so it is recommended to not cast the LayerNorms # in fp32. (LlamaRMSNorm handles it correctly) if query_states.dtype == torch.float32 or value_states.dtype == torch.float32: if torch.is_autocast_enabled(): target_dtype = torch.get_autocast_gpu_dtype() # Handle the case where the model is quantized elif hasattr(self.config, "_pre_quantization_dtype"): target_dtype = self.config._pre_quantization_dtype else: target_dtype = self.q_proj.weight.dtype logger.warning_once( f"The input hidden states seems to be silently casted in float32, this might be related to" f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in" f" {target_dtype}." ) query_states = query_states.to(target_dtype) key_states = key_states.to(target_dtype) value_states = value_states.to(target_dtype) attn_output = self._flash_attention_forward( query_states, key_states, value_states, attention_mask, tgt_len, dropout=self.dropout ) attn_output = attn_output.reshape(bsz, tgt_len, -1) attn_output = self.out_proj(attn_output) if not output_attentions: attn_weights = None return attn_output, attn_weights, past_key_value # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._flash_attention_forward def _flash_attention_forward( self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None ): """ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token first unpad the input, then computes the attention scores and pad the final attention scores. Args: query_states (`torch.Tensor`): Input query states to be passed to Flash Attention API key_states (`torch.Tensor`): Input key states to be passed to Flash Attention API value_states (`torch.Tensor`): Input value states to be passed to Flash Attention API attention_mask (`torch.Tensor`): The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the position of padding tokens and 1 for the position of non-padding tokens. dropout (`float`): Attention dropout softmax_scale (`float`, *optional*): The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim) """ if not self._flash_attn_uses_top_left_mask: causal = self.is_causal else: # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__. causal = self.is_causal and query_length != 1 # Contains at least one padding token in the sequence if attention_mask is not None: batch_size = query_states.shape[0] query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input( query_states, key_states, value_states, attention_mask, query_length ) cu_seqlens_q, cu_seqlens_k = cu_seq_lens max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens attn_output_unpad = flash_attn_varlen_func( query_states, key_states, value_states, cu_seqlens_q=cu_seqlens_q, cu_seqlens_k=cu_seqlens_k, max_seqlen_q=max_seqlen_in_batch_q, max_seqlen_k=max_seqlen_in_batch_k, dropout_p=dropout, softmax_scale=softmax_scale, causal=causal, ) attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length) else: attn_output = flash_attn_func( query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal ) return attn_output # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._upad_input def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length): indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask) batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape key_layer = index_first_axis( key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k ) value_layer = index_first_axis( value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k ) if query_length == kv_seq_len: query_layer = index_first_axis( query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k ) cu_seqlens_q = cu_seqlens_k max_seqlen_in_batch_q = max_seqlen_in_batch_k indices_q = indices_k elif query_length == 1: max_seqlen_in_batch_q = 1 cu_seqlens_q = torch.arange( batch_size + 1, dtype=torch.int32, device=query_layer.device ) # There is a memcpy here, that is very bad. indices_q = cu_seqlens_q[:-1] query_layer = query_layer.squeeze(1) else: # The -q_len: slice assumes left padding. attention_mask = attention_mask[:, -query_length:] query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask) return ( query_layer, key_layer, value_layer, indices_q, (cu_seqlens_q, cu_seqlens_k), (max_seqlen_in_batch_q, max_seqlen_in_batch_k), ) # Copied from transformers.models.bart.modeling_bart.BartSdpaAttention with Bart->Musicgen class ParlerTTSSdpaAttention(ParlerTTSAttention): def forward( self, hidden_states: torch.Tensor, key_value_states: Optional[torch.Tensor] = None, past_key_value: Optional[EncoderDecoderCache] = None, attention_mask: Optional[torch.Tensor] = None, cos: Optional[torch.LongTensor] = None, sin: Optional[torch.LongTensor] = None, layer_head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False, cache_position: Optional[torch.LongTensor] = None, ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: """Input shape: Batch x Time x Channel""" if output_attentions or layer_head_mask is not None: # TODO: Improve this warning with e.g. `model.config._attn_implementation = "manual"` once this is implemented. logger.warning_once( "ParlerTTSModel is using ParlerTTSSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True` or `layer_head_mask` not None. Falling back to the manual attention" ' implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.' ) return super().forward( hidden_states, key_value_states=key_value_states, past_key_value=past_key_value, attention_mask=attention_mask, layer_head_mask=layer_head_mask, output_attentions=output_attentions, cache_position=cache_position, ) # if key_value_states are provided this layer is used as a cross-attention layer # for the decoder is_cross_attention = key_value_states is not None bsz, tgt_len = hidden_states.shape[:2] # get query proj query_states = self.q_proj(hidden_states) query_states = self._shape_query(query_states, tgt_len, bsz) if self.rope_embeddings: query_states = apply_rotary_pos_emb(query_states, cos, sin) if past_key_value is not None: is_updated = past_key_value.is_updated.get(self.layer_idx) if is_cross_attention: # after the first generated id, we can subsequently re-use all key/value_states from cache past_key_value.is_updated[self.layer_idx] = True past_key_value = past_key_value.cross_attention_cache else: past_key_value = past_key_value.self_attention_cache # use key_value_states if cross attention current_states = key_value_states if key_value_states is not None else hidden_states if is_cross_attention and past_key_value and is_updated: # reuse k,v, cross_attentions key_states = past_key_value.key_cache[self.layer_idx] value_states = past_key_value.value_cache[self.layer_idx] else: key_states = self._shape_key_value(self.k_proj(current_states), -1, bsz) value_states = self._shape_key_value(self.v_proj(current_states), -1, bsz) if not is_cross_attention and self.rope_embeddings: # cached key states already have rope applied - only apply to new state key_states = apply_rotary_pos_emb(key_states, cos, sin) if past_key_value is not None: # save all key/value_states to cache to be re-used for fast auto-regressive generation cache_position = cache_position if not is_cross_attention else None key_states, value_states = past_key_value.update( key_states, value_states, self.layer_idx, {"cache_position": cache_position} ) causal_mask = attention_mask if attention_mask is not None: # no matter the length, we just slice it causal_mask = attention_mask[:, :, :, : key_states.shape[-2]] # repeat k/v heads if n_kv_heads < n_heads key_states = repeat_kv(key_states, self.num_key_value_groups) value_states = repeat_kv(value_states, self.num_key_value_groups) # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling. # The tgt_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case tgt_len == 1. is_causal = True if self.is_causal and causal_mask is None and tgt_len > 1 else False # NOTE: SDPA with memory-efficient backend is currently (torch==2.1.2) bugged when using non-contiguous inputs and a custom attn_mask, # but we are fine here as `_shape` do call `.contiguous()`. Reference: https://github.com/pytorch/pytorch/issues/112577 attn_output = torch.nn.functional.scaled_dot_product_attention( query_states, key_states, value_states, attn_mask=causal_mask, dropout_p=self.dropout if self.training else 0.0, # The tgt_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case tgt_len == 1. is_causal=is_causal, ) if attn_output.size() != (bsz, self.num_heads, tgt_len, self.head_dim): raise ValueError( f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is" f" {attn_output.size()}" ) attn_output = attn_output.transpose(1, 2) # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be # partitioned across GPUs when using tensor-parallelism. attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim) attn_output = self.out_proj(attn_output) return attn_output, None, past_key_value PARLERTTS_ATTENTION_CLASSES = { "eager": ParlerTTSAttention, "sdpa": ParlerTTSSdpaAttention, "flash_attention_2": ParlerTTSFlashAttention2, } class ParlerTTSDecoderLayer(nn.Module): def __init__(self, config: ParlerTTSDecoderConfig, layer_idx: int = None): super().__init__() self.embed_dim = config.hidden_size self.self_attn = PARLERTTS_ATTENTION_CLASSES[config._attn_implementation]( embed_dim=self.embed_dim, num_heads=config.num_attention_heads, num_key_value_heads=config.num_key_value_heads, dropout=config.attention_dropout, is_decoder=True, is_causal=True, bias=False, rope_embeddings=config.rope_embeddings, layer_idx=layer_idx, config=config, ) self.dropout = config.dropout self.activation_fn = ACT2FN[config.activation_function] self.activation_dropout = config.activation_dropout self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim) cross_attn_implementation = config._attn_implementation if config.cross_attention_implementation_strategy == "always_eager": cross_attn_implementation = "eager" elif config.cross_attention_implementation_strategy == "always_sdpa": cross_attn_implementation = "sdpa" self.encoder_attn = PARLERTTS_ATTENTION_CLASSES[cross_attn_implementation]( self.embed_dim, config.num_attention_heads, num_key_value_heads=config.num_cross_attention_key_value_heads, dropout=config.attention_dropout, is_decoder=True, bias=False, rope_embeddings=config.rope_embeddings, layer_idx=layer_idx, config=config, ) self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim) self.fc1 = nn.Linear(self.embed_dim, config.ffn_dim, bias=False) self.fc2 = nn.Linear(config.ffn_dim, self.embed_dim, bias=False) self.final_layer_norm = nn.LayerNorm(self.embed_dim) def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, cos: Optional[torch.LongTensor] = None, sin: Optional[torch.LongTensor] = None, encoder_hidden_states: Optional[torch.Tensor] = None, encoder_attention_mask: Optional[torch.Tensor] = None, layer_head_mask: Optional[torch.Tensor] = None, cross_attn_layer_head_mask: Optional[torch.Tensor] = None, past_key_value: Optional[EncoderDecoderCache] = None, output_attentions: Optional[bool] = False, use_cache: Optional[bool] = True, cache_position: Optional[torch.LongTensor] = None, ) -> torch.Tensor: """ Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`): attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.n_positions - 1]`. encoder_hidden_states (`torch.FloatTensor`): cross attention input to the layer of shape `(batch, seq_len, embed_dim)` encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size `(encoder_attention_heads,)`. cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of size `(decoder_attention_heads,)`. past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. """ residual = hidden_states hidden_states = self.self_attn_layer_norm(hidden_states) # Self Attention hidden_states, self_attn_weights, present_key_value = self.self_attn( hidden_states=hidden_states, past_key_value=past_key_value, attention_mask=attention_mask, cos=cos, sin=sin, layer_head_mask=layer_head_mask, output_attentions=output_attentions, cache_position=cache_position, ) hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) hidden_states = residual + hidden_states # Cross-Attention Block cross_attn_weights = None if encoder_hidden_states is not None: residual = hidden_states hidden_states = self.encoder_attn_layer_norm(hidden_states) hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn( hidden_states=hidden_states, key_value_states=encoder_hidden_states, attention_mask=encoder_attention_mask, cos=cos, sin=sin, layer_head_mask=cross_attn_layer_head_mask, past_key_value=past_key_value, output_attentions=output_attentions, ) hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) hidden_states = residual + hidden_states # add cross-attn to positions 1 of present_key_value tuple present_key_value = (present_key_value, cross_attn_present_key_value) # Fully Connected residual = hidden_states hidden_states = self.final_layer_norm(hidden_states) hidden_states = self.activation_fn(self.fc1(hidden_states)) hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training) hidden_states = self.fc2(hidden_states) hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) hidden_states = residual + hidden_states outputs = (hidden_states,) if output_attentions: outputs += (self_attn_weights, cross_attn_weights) if use_cache: outputs += (present_key_value,) return outputs # Copied from transformers.models.musicgen.modeling_musicgen.MusicgenPreTrainedModel with Musicgen->ParlerTTS class ParlerTTSPreTrainedModel(PreTrainedModel): """ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models. """ config_class = ParlerTTSDecoderConfig base_model_prefix = "model" supports_gradient_checkpointing = True _supports_flash_attn_2 = True _supports_sdpa = True _no_split_modules = ["ParlerTTSDecoderLayer", "ParlerTTSAttention"] _supports_cache_class = True _supports_static_cache = True def _init_weights(self, module): std = self.config.initializer_factor if isinstance(module, (nn.Linear, nn.Conv1d)): module.weight.data.normal_(mean=0.0, std=std) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=std) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_() MUSICGEN_START_DOCSTRING = r""" The ParlerTTS model was proposed in [Simple and Controllable Music Generation](https://arxiv.org/abs/2306.05284) by Jade Copet, Felix Kreuk, Itai Gat, Tal Remez, David Kant, Gabriel Synnaeve, Yossi Adi, Alexandre Défossez. It is an encoder decoder transformer trained on the task of conditional music generation This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.) This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`ParlerTTSConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ MUSICGEN_INPUTS_DOCSTRING = r""" Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) decoder_input_ids (`torch.LongTensor` of shape `(batch_size * num_codebooks, target_sequence_length)`, *optional*): Indices of decoder input sequence tokens in the vocabulary, corresponding to the sequence of audio codes. Indices can be obtained by encoding an audio prompt with an audio encoder model to predict audio codes, such as with the [`EncodecModel`]. See [`EncodecModel.encode`] for details. [What are decoder input IDs?](../glossary#decoder-input-ids) <Tip warning={true}> The `decoder_input_ids` will automatically be converted from shape `(batch_size * num_codebooks, target_sequence_length)` to `(batch_size, num_codebooks, target_sequence_length)` in the forward pass. If you obtain audio codes from an audio encoding model, such as [`EncodecModel`], ensure that the number of frames is equal to 1, and that you reshape the audio codes from `(frames, batch_size, num_codebooks, target_sequence_length)` to `(batch_size * num_codebooks, target_sequence_length)` prior to passing them as `decoder_input_ids`. </Tip> decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*): Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also be used by default. head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*): Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`: - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. decoder_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*): Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`: - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*): Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in `[0, 1]`: - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*): Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`) `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder. TODO: it's passed through enc_to_dec_proj and optionnally we concat the prompt hidden states in certain cases. past_key_values (`EncoderDecoderCache` or `tuple(tuple(torch.FloatTensor))`, *optional*): Pre-computed hidden-states that can be used to speed up auto-regressive (sequential) decoding. There are four sets of pre-computed hidden-states: key and values states in the self-attention blocks (2) and in the cross-attention blocks (2). The `past_key_values` are returned when `use_cache=True` is passed or when `config.use_cache=True` Two formats are allowed: - An [`~cache_utils.EncoderDecoderCache`] instance; - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `decoder_input_ids` of shape `(batch_size, sequence_length)`. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be input (see `past_key_values`). This is useful if you want more control over how to convert `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix. If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value of `inputs_embeds`. prompt_input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input prompt sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) prompt_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding prompt token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) prompt_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `prompt_input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `prompt_input_ids` indices into associated vectors than the model's internal embedding lookup matrix. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*): Indices depicting the position of the input sequence tokens in the sequence. It is used to update the cache in the correct position and to infer the complete sequence length. """ MUSICGEN_DECODER_INPUTS_DOCSTRING = r""" Args: input_ids (`torch.LongTensor` of shape `(batch_size * num_codebooks, sequence_length)`): Indices of input sequence tokens in the vocabulary, corresponding to the sequence of audio codes. Indices can be obtained by encoding an audio prompt with an audio encoder model to predict audio codes, such as with the [`EncodecModel`]. See [`EncodecModel.encode`] for details. [What are input IDs?](../glossary#input-ids) <Tip warning={true}> The `input_ids` will automatically be converted from shape `(batch_size * num_codebooks, target_sequence_length)` to `(batch_size, num_codebooks, target_sequence_length)` in the forward pass. If you obtain audio codes from an audio encoding model, such as [`EncodecModel`], ensure that the number of frames is equal to 1, and that you reshape the audio codes from `(frames, batch_size, num_codebooks, target_sequence_length)` to `(batch_size * num_codebooks, target_sequence_length)` prior to passing them as `input_ids`. </Tip> attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*): Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder. encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*): Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) prompt_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*): Sequence of prompt hidden-states at the output of the initial embedding layer. Concatenated to the input embeds. prompt_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*): Mask to avoid performing cross-attention on padding tokens indices of prompt input_ids. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*): Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`: - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*): Mask to nullify selected heads of the cross-attention modules in the decoder to avoid performing cross-attention on hidden heads. Mask values selected in `[0, 1]`: - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `decoder_input_ids` of shape `(batch_size, sequence_length)`. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ class ParlerTTSDecoder(ParlerTTSPreTrainedModel): """ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`ParlerTTSDecoderLayer`] """ def __init__(self, config: ParlerTTSDecoderConfig): super().__init__(config) self.dropout = config.dropout self.layerdrop = config.layerdrop self.max_target_positions = config.max_position_embeddings self.d_model = config.hidden_size self.num_codebooks = config.num_codebooks self.embed_scale = math.sqrt(config.hidden_size) if config.scale_embedding else 1.0 # TODO(YL): actually doesn't need the +1 if initialized correctly. Too late to change now. embed_dim = config.vocab_size + 1 # + 1 for pad token id self.embed_tokens = nn.ModuleList( [nn.Embedding(embed_dim, config.hidden_size) for _ in range(config.num_codebooks)] ) self.rope_embeddings = config.rope_embeddings if not config.rope_embeddings: self.embed_positions = ParlerTTSSinusoidalPositionalEmbedding( config.max_position_embeddings, config.hidden_size, ) else: self.rotary_emb = ParlerTTSRotaryEmbedding( config.hidden_size // config.num_attention_heads, max_position_embeddings=config.max_position_embeddings, base=config.rope_theta, ) self.layers = nn.ModuleList( [ParlerTTSDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] ) self.layer_norm = nn.LayerNorm(config.hidden_size) self.attn_implementation = config._attn_implementation encoder_attn_implementation = config._attn_implementation if config.cross_attention_implementation_strategy is not None: encoder_attn_implementation = ( "sdpa" if config.cross_attention_implementation_strategy == "always_sdpa" else "eager" ) self.encoder_attn_implementation = encoder_attn_implementation self.gradient_checkpointing = False # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.embed_tokens def set_input_embeddings(self, value): self.embed_tokens = value @add_start_docstrings_to_model_forward(MUSICGEN_DECODER_INPUTS_DOCSTRING) def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, encoder_hidden_states: Optional[torch.FloatTensor] = None, encoder_attention_mask: Optional[torch.LongTensor] = None, prompt_hidden_states: Optional[torch.FloatTensor] = None, prompt_attention_mask: Optional[torch.LongTensor] = None, head_mask: Optional[torch.Tensor] = None, cross_attn_head_mask: Optional[torch.Tensor] = None, past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, position_ids: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, cache_position=None, ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]: output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) use_cache = use_cache if use_cache is not None else self.config.use_cache return_dict = return_dict if return_dict is not None else self.config.use_return_dict # retrieve input_ids and inputs_embeds if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time") elif input_ids is not None: # (bsz * codebooks, seq_len) -> (bsz, codebooks, seq_len) input = input_ids.reshape(-1, self.num_codebooks, input_ids.shape[-1]) bsz, num_codebooks, seq_len = input.shape input_shape = (bsz, seq_len) elif inputs_embeds is not None: input_shape = inputs_embeds.size()[:-1] input = inputs_embeds[:, :, -1:] else: raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds") if inputs_embeds is None: inputs_embeds = sum([self.embed_tokens[codebook](input[:, codebook]) for codebook in range(num_codebooks)]) prepended_sequence_length = 0 # if prompt_hidden_states, fuse to inputs_embeds and update input shape if prompt_hidden_states is not None: prepended_sequence_length = prompt_hidden_states.shape[-2] inputs_embeds = torch.cat([prompt_hidden_states, inputs_embeds], dim=1) return_legacy_cache = False return_self_attention_cache = False if use_cache or past_key_values is not None: if isinstance(past_key_values, Cache) and not isinstance(past_key_values, EncoderDecoderCache): return_self_attention_cache = True past_key_values = EncoderDecoderCache(past_key_values, DynamicCache()) elif not isinstance(past_key_values, EncoderDecoderCache): return_legacy_cache = True logger.warning_once( "Passing a tuple of `past_key_values` is deprecated and will be removed in Transformers v4.43.0. " "You should pass an instance of `EncoderDecoderCache` instead, e.g. " "`past_key_values=EncoderDecoderCache.from_legacy_cache(past_key_values)`." ) past_key_values = EncoderDecoderCache.from_legacy_cache(past_key_values) past_key_values_length = 0 if cache_position is not None: past_key_values_length = cache_position[0] elif past_key_values is not None: past_key_values_length = past_key_values.get_seq_length() if cache_position is None: cache_position = torch.arange( past_key_values_length, past_key_values_length + input_shape[1] + prepended_sequence_length, device=inputs_embeds.device ) if position_ids is None: position_ids = cache_position.unsqueeze(0) # NOTE: 1. As it is, the masked ids from the prompt will still count in the positions embeddings # NOTE: 2. we want to concatenate the prompt attention mask and the decoder attention mask # i.i.f `prompt_cross_attention=False`. ParlerTTSForConditionalGeneration's taking care of setting # `prompt_attention_mask=None` if prompt_attention_mask is not None and attention_mask is not None: attention_mask = torch.cat([prompt_attention_mask, attention_mask], dim=1) elif prompt_attention_mask is not None: logger.warning_once( "`prompt_attention_mask` is specified but `attention_mask` is not. A full `attention_mask` will be created. Make sure this is the intended behaviour." ) if past_key_values_length == 0: attention_mask = torch.cat( [ prompt_attention_mask, torch.ones(input_shape, device=self.device, dtype=prompt_attention_mask.dtype), ], dim=1, ) else: # In the generation case of `prompt_cross_attention=True`, we need to recreate an attention mask from scratch # to be able to prepend the prompt attention mask. # Since we generate token per token, we can recompute the generated length from the information we have. generated_length = past_key_values_length - prompt_attention_mask.shape[1] + 1 attention_mask = torch.cat( [ prompt_attention_mask, torch.ones( (input_shape[0], generated_length), device=self.device, dtype=prompt_attention_mask.dtype ), ], dim=1, ) input_shape = inputs_embeds.size()[:-1] cos, sin = None, None if not self.rope_embeddings: # embed positions # TODO: As it is, the masked ids from the prompt will still count in the positions embeddings # maybe should modify position embeddings positions = self.embed_positions(inputs_embeds, past_key_values_length) hidden_states = inputs_embeds + positions.to(inputs_embeds.device) else: hidden_states = inputs_embeds if position_ids is None: if attention_mask is not None: # masked ids will **not** count in the position embeddings position_ids = attention_mask.long().cumsum(-1) - 1 position_ids.masked_fill_(attention_mask == 0, 1) else: position_ids = torch.arange( past_key_values_length, input_shape[1] + past_key_values_length, dtype=torch.long, device=inputs_embeds.device, ) position_ids = position_ids.unsqueeze(0) # Some generation methods already pass only the last input ID if position_ids.shape[1] > input_shape[1]: position_ids = position_ids[:, -input_shape[1] :] cos, sin = self.rotary_emb(hidden_states.device.type, position_ids) cos, sin = cos.to(hidden_states.dtype), sin.to(hidden_states.dtype) hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) causal_mask = self._update_causal_mask( attention_mask, inputs_embeds, cache_position, past_key_values.self_attention_cache if past_key_values is not None else None, output_attentions, ) if encoder_hidden_states is not None and encoder_attention_mask is not None: if self.encoder_attn_implementation == "flash_attention_2": encoder_attention_mask = encoder_attention_mask if 0 in encoder_attention_mask else None elif self.encoder_attn_implementation == "sdpa" and cross_attn_head_mask is None and not output_attentions: # output_attentions=True & cross_attn_head_mask can not be supported when using SDPA, and we fall back on # the manual implementation that requires a 4D causal mask in all cases. # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] encoder_attention_mask = _prepare_4d_attention_mask_for_sdpa( encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1], ) else: # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] encoder_attention_mask = _prepare_4d_attention_mask( encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1] ) if self.gradient_checkpointing and self.training: if use_cache: logger.warning_once( "`use_cache=True` is incompatible with gradient checkpointing`. Setting `use_cache=False`..." ) use_cache = False # decoder layers all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]): if attn_mask is not None: if attn_mask.size()[0] != len(self.layers): raise ValueError( f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for" f" {attn_mask.size()[0]}." ) for idx, decoder_layer in enumerate(self.layers): # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) if output_hidden_states: all_hidden_states += (hidden_states,) dropout_probability = random.uniform(0, 1) if self.training and (dropout_probability < self.layerdrop): continue if self.gradient_checkpointing and self.training: layer_outputs = self._gradient_checkpointing_func( decoder_layer.forward, hidden_states, causal_mask, cos, sin, encoder_hidden_states, encoder_attention_mask, head_mask[idx] if head_mask is not None else None, cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None, None, output_attentions, use_cache, cache_position, ) else: layer_outputs = decoder_layer( hidden_states, attention_mask=causal_mask, cos=cos, sin=sin, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, layer_head_mask=(head_mask[idx] if head_mask is not None else None), cross_attn_layer_head_mask=( cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None ), past_key_value=past_key_values if use_cache else None, output_attentions=output_attentions, use_cache=use_cache, cache_position=cache_position, ) hidden_states = layer_outputs[0] if output_attentions: all_self_attns += (layer_outputs[1],) if encoder_hidden_states is not None: all_cross_attentions += (layer_outputs[2],) hidden_states = self.layer_norm(hidden_states) # add hidden states from the last decoder layer if output_hidden_states: all_hidden_states += (hidden_states,) next_cache = past_key_values if use_cache else None if return_self_attention_cache: next_cache = past_key_values.self_attention_cache if return_legacy_cache: next_cache = past_key_values.to_legacy_cache() if not return_dict: return tuple( v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions] if v is not None ) return BaseModelOutputWithPastAndCrossAttentions( last_hidden_state=hidden_states, past_key_values=next_cache, hidden_states=all_hidden_states, attentions=all_self_attns, cross_attentions=all_cross_attentions, ) # Copied from transformers.models.llama.modeling_llama.LlamaModel._update_causal_mask def _update_causal_mask( self, attention_mask: torch.Tensor, input_tensor: torch.Tensor, cache_position: torch.Tensor, past_key_values: Cache, output_attentions: bool, ): # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes. # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114 if self.config._attn_implementation == "flash_attention_2": if attention_mask is not None and 0.0 in attention_mask: return attention_mask return None # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail # to infer the attention mask. past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0 using_static_cache = isinstance(past_key_values, StaticCache) # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions: if AttentionMaskConverter._ignore_causal_mask_sdpa( attention_mask, inputs_embeds=input_tensor, past_key_values_length=past_seen_tokens, is_training=self.training, ): return None dtype, device = input_tensor.dtype, input_tensor.device min_dtype = torch.finfo(dtype).min sequence_length = input_tensor.shape[1] if using_static_cache: target_length = past_key_values.get_max_length() else: target_length = ( attention_mask.shape[-1] if isinstance(attention_mask, torch.Tensor) else past_seen_tokens + sequence_length + 1 ) if attention_mask is not None and attention_mask.dim() == 4: # in this case we assume that the mask comes already in inverted form and requires no inversion or slicing if attention_mask.max() != 0: raise ValueError("Custom 4D attention mask should be passed in inverted form with max==0`") causal_mask = attention_mask else: causal_mask = torch.full( (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device ) if sequence_length != 1: causal_mask = torch.triu(causal_mask, diagonal=1) causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1) causal_mask = causal_mask[None, None, :, :].expand(input_tensor.shape[0], 1, -1, -1) if attention_mask is not None: causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit mask_length = attention_mask.shape[-1] padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :] padding_mask = padding_mask == 0 causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill( padding_mask, min_dtype ) if ( self.config._attn_implementation == "sdpa" and attention_mask is not None and attention_mask.device.type == "cuda" and not output_attentions ): # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path. # Details: https://github.com/pytorch/pytorch/issues/110213 causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype) return causal_mask @add_start_docstrings( "The bare ParlerTTS decoder model outputting raw hidden-states without any specific head on top.", MUSICGEN_START_DOCSTRING, ) # Copied from transformers.models.musicgen.modeling_musicgen.MusicgenModel with Musicgen->ParlerTTS class ParlerTTSModel(ParlerTTSPreTrainedModel): def __init__(self, config: ParlerTTSDecoderConfig): super().__init__(config) self.decoder = ParlerTTSDecoder(config) # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.decoder.embed_tokens def set_input_embeddings(self, value): self.decoder.embed_tokens = value def get_decoder(self): return self.decoder @add_start_docstrings_to_model_forward(MUSICGEN_DECODER_INPUTS_DOCSTRING) def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, encoder_hidden_states: Optional[torch.FloatTensor] = None, encoder_attention_mask: Optional[torch.LongTensor] = None, prompt_hidden_states: Optional[torch.FloatTensor] = None, prompt_attention_mask: Optional[torch.LongTensor] = None, head_mask: Optional[torch.Tensor] = None, cross_attn_head_mask: Optional[torch.Tensor] = None, past_key_values: Optional[Union[EncoderDecoderCache, Tuple[torch.FloatTensor]]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, ) -> Union[Tuple, BaseModelOutputWithPastAndCrossAttentions]: output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) use_cache = use_cache if use_cache is not None else self.config.use_cache return_dict = return_dict if return_dict is not None else self.config.use_return_dict # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn) decoder_outputs = self.decoder( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, encoder_attention_mask=encoder_attention_mask, encoder_hidden_states=encoder_hidden_states, prompt_hidden_states=prompt_hidden_states, prompt_attention_mask=prompt_attention_mask, head_mask=head_mask, cross_attn_head_mask=cross_attn_head_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, cache_position=cache_position, ) if not return_dict: return decoder_outputs return BaseModelOutputWithPastAndCrossAttentions( last_hidden_state=decoder_outputs.last_hidden_state, past_key_values=decoder_outputs.past_key_values, hidden_states=decoder_outputs.hidden_states, attentions=decoder_outputs.attentions, cross_attentions=decoder_outputs.cross_attentions, ) @add_start_docstrings( "The Parler-TTS decoder model with a language modelling head on top.", MUSICGEN_START_DOCSTRING, ) class ParlerTTSForCausalLM(ParlerTTSPreTrainedModel): def __init__(self, config: ParlerTTSDecoderConfig): super().__init__(config) self.model = ParlerTTSModel(config) self.num_codebooks = config.num_codebooks self.lm_heads = nn.ModuleList( [nn.Linear(config.hidden_size, config.vocab_size, bias=False) for _ in range(config.num_codebooks)] ) # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.model.decoder.embed_tokens def set_input_embeddings(self, value): self.model.decoder.embed_tokens = value def get_output_embeddings(self): return self.lm_heads def set_output_embeddings(self, new_embeddings): self.lm_heads = new_embeddings def set_decoder(self, decoder): self.model.decoder = decoder def get_decoder(self): return self.model.decoder @add_start_docstrings_to_model_forward(MUSICGEN_DECODER_INPUTS_DOCSTRING) @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC) def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, encoder_hidden_states: Optional[torch.FloatTensor] = None, encoder_attention_mask: Optional[torch.LongTensor] = None, prompt_hidden_states: Optional[torch.FloatTensor] = None, prompt_attention_mask: Optional[torch.LongTensor] = None, head_mask: Optional[torch.Tensor] = None, cross_attn_head_mask: Optional[torch.Tensor] = None, past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]: r""" labels (`torch.LongTensor` of shape `(batch_size, sequence_length, num_codebooks)`, *optional*): Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100` are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]` Returns: """ return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.model( input_ids, attention_mask=attention_mask, position_ids=position_ids, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask, prompt_hidden_states=prompt_hidden_states, prompt_attention_mask=prompt_attention_mask, head_mask=head_mask, cross_attn_head_mask=cross_attn_head_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, cache_position=cache_position, ) hidden_states = outputs[0] lm_logits = torch.stack([head(hidden_states) for head in self.lm_heads], dim=1) loss = None if labels is not None: # since encoder hidden states have concatenated to hidden states, take the last hidden states corresponding to labels logits = lm_logits[:, :, -labels.shape[1] :] loss_fct = CrossEntropyLoss() loss = torch.zeros([], device=self.device) # (bsz, vocab_size, seq_len, num_codebooks), (bsz, seq_len, num_codebooks) labels = labels.masked_fill(labels == self.config.bos_token_id, -100) # we use every codebooks token AND one single EOS at the end of each codebooks mask = (input_ids.transpose(1, 2) != self.config.eos_token_id) & ((labels != -100)) # per codebook cross-entropy for codebook in range(self.config.num_codebooks): codebook_logits = logits[:, codebook].contiguous().view(-1, logits.shape[-1]) codebook_mask = mask[..., codebook].contiguous().view(-1) codebook_labels = labels[..., codebook].contiguous().view(-1) codebook_loss = loss_fct(codebook_logits[codebook_mask], codebook_labels[codebook_mask]) loss += codebook_loss loss = loss / self.config.num_codebooks # (bsz, num_codebooks, seq_len, vocab_size) -> (bsz * num_codebooks, seq_len, vocab_size) lm_logits = lm_logits.reshape(-1, *lm_logits.shape[2:]) if not return_dict: output = (lm_logits,) + outputs[1:] return ((loss,) + output) if loss is not None else output return CausalLMOutputWithCrossAttentions( loss=loss, logits=lm_logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, cross_attentions=outputs.cross_attentions, ) def prepare_inputs_for_generation( self, input_ids, attention_mask=None, encoder_hidden_states=None, encoder_attention_mask=None, prompt_hidden_states=None, prompt_attention_mask=None, head_mask=None, cross_attn_head_mask=None, past_key_values=None, use_cache=True, delay_pattern_mask=None, cache_position=None, inputs_embeds=None, **kwargs, ): if delay_pattern_mask is None: input_ids, delay_pattern_mask = self.build_delay_pattern_mask( input_ids, bos_token_id=self.generation_config.bos_token_id, pad_token_id=self.generation_config.pad_token_id, max_length=self.generation_config.max_length, ) # apply the delay pattern mask input_ids = self.apply_delay_pattern_mask(input_ids, delay_pattern_mask) position_ids = kwargs.get("position_ids", None) if attention_mask is not None and position_ids is None: # create position_ids on the fly for batch generation position_ids = attention_mask.long().cumsum(-1) - 1 position_ids.masked_fill_(attention_mask == 0, 1) position_ids = kwargs.get("position_ids", None) if attention_mask is not None and position_ids is None: # create position_ids on the fly for batch generation position_ids = attention_mask.long().cumsum(-1) - 1 position_ids.masked_fill_(attention_mask == 0, 1) if past_key_values is not None: input_ids = input_ids[:, -1:] if position_ids is not None: position_ids = position_ids[:, -input_ids.shape[1] :] # we only want to use prompt signal in the 1st generation step but keeping the attention mask prompt_hidden_states = None return { "input_ids": input_ids.contiguous(), # `contiguous()` needed for compilation use cases "attention_mask": attention_mask, "position_ids": position_ids, "encoder_hidden_states": encoder_hidden_states, "encoder_attention_mask": encoder_attention_mask, "prompt_hidden_states": prompt_hidden_states, "prompt_attention_mask": prompt_attention_mask, "head_mask": head_mask, "cross_attn_head_mask": cross_attn_head_mask, "past_key_values": past_key_values, "use_cache": use_cache, "cache_position": cache_position, "inputs_embeds": inputs_embeds, } # Ignore copy def build_delay_pattern_mask( self, input_ids: torch.LongTensor, bos_token_id: int, pad_token_id: int, max_length: int = None ): """Build a delayed pattern mask to the input_ids. Each codebook is offset by the previous codebook by one, giving a delayed pattern mask at the start of sequence and end of sequence. Take the example where there are 4 codebooks and a max sequence length of 8, we have the delayed pattern mask of shape `(codebooks, seq_len)`: - [B, -1, -1, -1, -1, P, P, P] - [B, B, -1, -1, -1, -1, P, P] - [B, B, B, -1, -1, -1, -1, P] - [B, B, B, B, -1, -1, -1, -1] where P is the special padding token id and -1 indicates that the token is valid for prediction. If we include a prompt (decoder input ids), the -1 positions indicate where new tokens should be predicted. Otherwise, the mask is set to the value in the prompt: - [B, a, b, -1, -1, P, P, P] - [B, B, c, d, -1, -1, P, P] - [B, B, B, e, f, -1, -1, P] - [B, B, B, B, g, h, -1, -1] where a-h indicate the input prompt (decoder input ids) that are offset by 1. Now, we only override the -1 tokens in our prediction. """ max_length = max_length if max_length is not None else self.generation_config.max_length return build_delay_pattern_mask(input_ids, bos_token_id, pad_token_id, max_length, self.num_codebooks) @staticmethod def apply_delay_pattern_mask(input_ids, decoder_pad_token_mask): """Apply a delay pattern mask to the decoder input ids, only preserving predictions where the mask is set to -1, and otherwise setting to the value detailed in the mask.""" return apply_delay_pattern_mask(input_ids, decoder_pad_token_mask) @torch.no_grad() def generate( self, inputs: Optional[torch.Tensor] = None, generation_config: Optional[GenerationConfig] = None, logits_processor: Optional[LogitsProcessorList] = None, stopping_criteria: Optional[StoppingCriteriaList] = None, synced_gpus: Optional[bool] = None, streamer: Optional["BaseStreamer"] = None, **kwargs, ): """ Generates sequences of token ids for models with a language modeling head. <Tip warning={true}> Most generation-controlling parameters are set in `generation_config` which, if not passed, will be set to the model's default generation configuration. You can override any `generation_config` by passing the corresponding parameters to generate(), e.g. `.generate(inputs, num_beams=4, do_sample=True)`. For an overview of generation strategies and code examples, check out the [following guide](./generation_strategies). </Tip> Parameters: inputs (`torch.Tensor` of varying shape depending on the modality, *optional*): The sequence used as a prompt for the generation or as model inputs to the encoder. If `None` the method initializes it with `bos_token_id` and a batch size of 1. For decoder-only models `inputs` should be in the format `input_ids`. For encoder-decoder models *inputs* can represent any of `input_ids`, `input_values`, `input_features`, or `pixel_values`. generation_config (`~generation.GenerationConfig`, *optional*): The generation configuration to be used as base parametrization for the generation call. `**kwargs` passed to generate matching the attributes of `generation_config` will override them. If `generation_config` is not provided, the default will be used, which had the following loading priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s default values, whose documentation should be checked to parameterize generation. logits_processor (`LogitsProcessorList`, *optional*): Custom logits processors that complement the default logits processors built from arguments and generation config. If a logit processor is passed that is already created with the arguments or a generation config an error is thrown. This feature is intended for advanced users. stopping_criteria (`StoppingCriteriaList`, *optional*): Custom stopping criteria that complement the default stopping criteria built from arguments and a generation config. If a stopping criteria is passed that is already created with the arguments or a generation config an error is thrown. This feature is intended for advanced users. synced_gpus (`bool`, *optional*, defaults to `False`): Whether to continue running the while loop until max_length (needed for ZeRO stage 3) streamer (`BaseStreamer`, *optional*): Streamer object that will be used to stream the generated sequences. Generated tokens are passed through `streamer.put(token_ids)` and the streamer is responsible for any further processing. kwargs (`Dict[str, Any]`, *optional*): Ad hoc parametrization of `generate_config` and/or additional model-specific kwargs that will be forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with *decoder_*. Return: [`~utils.ModelOutput`] or `torch.LongTensor`: A [`~utils.ModelOutput`] (if `return_dict_in_generate=True` or when `config.return_dict_in_generate=True`) or a `torch.FloatTensor`. If the model is *not* an encoder-decoder model (`model.config.is_encoder_decoder=False`), the possible [`~utils.ModelOutput`] types are: - [`~generation.GenerateDecoderOnlyOutput`], - [`~generation.GenerateBeamDecoderOnlyOutput`] If the model is an encoder-decoder model (`model.config.is_encoder_decoder=True`), the possible [`~utils.ModelOutput`] types are: - [`~generation.GenerateEncoderDecoderOutput`], - [`~generation.GenerateBeamEncoderDecoderOutput`] """ # 1. Handle `generation_config` and kwargs that might update it, and validate the resulting objects if generation_config is None: generation_config = self.generation_config generation_config = copy.deepcopy(generation_config) model_kwargs = generation_config.update(**kwargs) # All unused kwargs must be model kwargs generation_config.validate() self._validate_model_kwargs(model_kwargs.copy()) # 2. Set generation parameters if not already defined logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList() stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList() if generation_config.pad_token_id is None and generation_config.eos_token_id is not None: if model_kwargs.get("attention_mask", None) is None: logger.warning( "The attention mask and the pad token id were not set. As a consequence, you may observe " "unexpected behavior. Please pass your input's `attention_mask` to obtain reliable results." ) eos_token_id = generation_config.eos_token_id if isinstance(eos_token_id, list): eos_token_id = eos_token_id[0] logger.warning(f"Setting `pad_token_id` to `eos_token_id`:{eos_token_id} for open-end generation.") generation_config.pad_token_id = eos_token_id # 3. Define model inputs # inputs_tensor has to be defined # model_input_name is defined if model-specific keyword input is passed # otherwise model_input_name is None # all model-specific keyword inputs are removed from `model_kwargs` input_ids, model_input_name, model_kwargs = self._prepare_model_inputs( inputs, generation_config.bos_token_id, model_kwargs ) batch_size = input_ids.shape[0] // self.num_codebooks kwargs_has_attention_mask = model_kwargs.get("attention_mask", None) is not None self._prepare_special_tokens(generation_config, kwargs_has_attention_mask, device=input_ids.device) # 4. Define other model kwargs model_kwargs["use_cache"] = generation_config.use_cache requires_attention_mask = "encoder_outputs" not in model_kwargs if model_kwargs.get("attention_mask", None) is None and requires_attention_mask: model_kwargs["attention_mask"] = self._prepare_attention_mask_for_generation( input_ids, generation_config.pad_token_id, generation_config.eos_token_id ) # 5. Prepare `max_length` depending on other stopping criteria. input_ids_seq_length = input_ids.shape[-1] has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None if has_default_max_length and generation_config.max_new_tokens is None and generation_config.max_length == 20: logger.warning( f"Using the model-agnostic default `max_length` (={generation_config.max_length}) " "to control the generation length. recommend setting `max_new_tokens` to control the maximum length of the generation." ) elif generation_config.max_new_tokens is not None: if not has_default_max_length: logger.warning( f"Both `max_new_tokens` (={generation_config.max_new_tokens}) and `max_length`(=" f"{generation_config.max_length}) seem to have been set. `max_new_tokens` will take precedence. " "Please refer to the documentation for more information. " "(https://huggingface.co/docs/transformers/main/en/main_classes/text_generation)" ) generation_config.max_length = generation_config.max_new_tokens + input_ids_seq_length if generation_config.min_length is not None and generation_config.min_length > generation_config.max_length: raise ValueError( f"Unfeasible length constraints: the minimum length ({generation_config.min_length}) is larger than" f" the maximum length ({generation_config.max_length})" ) if input_ids_seq_length >= generation_config.max_length: logger.warning( f"Input length of decoder_input_ids is {input_ids_seq_length}, but `max_length` is set to" f" {generation_config.max_length}. This can lead to unexpected behavior. You should consider" " increasing `max_new_tokens`." ) # 6. Prepare `input_ids` which will be used for auto-regressive generation # Build the delay pattern mask for offsetting each codebook prediction by 1 (this behaviour is specific to Parler-TTS) input_ids, delay_pattern_mask = self.build_delay_pattern_mask( input_ids, bos_token_id=generation_config.bos_token_id, pad_token_id=generation_config.pad_token_id, max_length=generation_config.max_length, ) if streamer is not None: streamer.put(input_ids.cpu()) # stash the delay mask so that we don't have to recompute it in each forward pass model_kwargs["delay_pattern_mask"] = delay_pattern_mask # 7. determine generation mode is_greedy_gen_mode = ( (generation_config.num_beams == 1) and (generation_config.num_beam_groups == 1) and generation_config.do_sample is False ) is_sample_gen_mode = ( (generation_config.num_beams == 1) and (generation_config.num_beam_groups == 1) and generation_config.do_sample is True ) # 8. prepare distribution pre_processing samplers logits_processor = self._get_logits_processor( generation_config=generation_config, input_ids_seq_length=input_ids_seq_length, encoder_input_ids=input_ids, prefix_allowed_tokens_fn=None, logits_processor=logits_processor, device=input_ids.device, ) # 9. prepare stopping criteria stopping_criteria = self._get_stopping_criteria( generation_config=generation_config, stopping_criteria=stopping_criteria ) if is_greedy_gen_mode: if generation_config.num_return_sequences > 1: raise ValueError( "num_return_sequences has to be 1 when doing greedy search, " f"but is {generation_config.num_return_sequences}." ) # 10. run greedy search outputs = self._sample( input_ids, logits_processor=logits_processor, stopping_criteria=stopping_criteria, generation_config=generation_config, synced_gpus=synced_gpus, streamer=streamer, **model_kwargs, ) elif is_sample_gen_mode: # 10. prepare logits warper logits_warper = self._get_logits_warper(generation_config, device=input_ids.device) # expand input_ids with `num_return_sequences` additional sequences per batch input_ids, model_kwargs = self._expand_inputs_for_generation( input_ids=input_ids, expand_size=generation_config.num_return_sequences, **model_kwargs, ) # 11. run sample outputs = self._sample( input_ids, logits_processor=logits_processor, logits_warper=logits_warper, stopping_criteria=stopping_criteria, generation_config=generation_config, synced_gpus=synced_gpus, streamer=streamer, **model_kwargs, ) else: raise ValueError( "Got incompatible mode for generation, should be one of greedy or sampling. " "Ensure that beam search is de-activated by setting `num_beams=1` and `num_beam_groups=1`." ) if generation_config.return_dict_in_generate: output_ids = outputs.sequences else: output_ids = outputs # apply the pattern mask to the final ids output_ids = self.apply_delay_pattern_mask(output_ids, model_kwargs["delay_pattern_mask"]) # revert the pattern delay mask by filtering the eos and bos token ids from the delay pattern mask _, mask = self.build_delay_pattern_mask( input_ids, bos_token_id=generation_config.bos_token_id, pad_token_id=generation_config.pad_token_id, max_length=output_ids.shape[1], ) mask = (mask != generation_config.bos_token_id) & (mask != generation_config.pad_token_id) output_ids = output_ids[mask].reshape(batch_size, self.num_codebooks, -1) if generation_config.return_dict_in_generate: outputs.sequences = output_ids return outputs else: return output_ids @add_start_docstrings( "The composite Parler-TTS model with a text encoder, audio encoder and ParlerTTS decoder, " "for music generation tasks with one or both of text and audio prompts.", MUSICGEN_START_DOCSTRING, ) class ParlerTTSForConditionalGeneration(PreTrainedModel): config_class = ParlerTTSConfig base_model_prefix = "encoder_decoder" main_input_name = "input_ids" supports_gradient_checkpointing = True _supports_flash_attn_2 = True _supports_sdpa = True _supports_cache_class = True _supports_static_cache = True def __init__( self, config: Optional[ParlerTTSConfig] = None, text_encoder: Optional[PreTrainedModel] = None, audio_encoder: Optional[PreTrainedModel] = None, decoder: Optional[ParlerTTSForCausalLM] = None, ): if config is None and (text_encoder is None or audio_encoder is None or decoder is None): raise ValueError( "Either a configuration has to be provided, or all three of text encoder, audio encoder and Parler-TTS decoder." ) if config is None: config = ParlerTTSConfig.from_sub_models_config(text_encoder.config, audio_encoder.config, decoder.config) else: if not isinstance(config, self.config_class): raise ValueError(f"Config: {config} has to be of type {self.config_class}") if config.decoder.cross_attention_hidden_size is not None: if config.decoder.cross_attention_hidden_size != config.text_encoder.hidden_size: raise ValueError( "If `cross_attention_hidden_size` is specified in the Parler-TTS decoder's configuration, it has to be equal" f" to the text encoder's `hidden_size`. Got {config.decoder.cross_attention_hidden_size} for" f" `config.decoder.cross_attention_hidden_size` and {config.text_encoder.hidden_size} for" " `config.text_encoder.hidden_size`." ) # initialize with config super().__init__(config) if text_encoder is None: from transformers.models.auto.modeling_auto import AutoModelForTextEncoding text_encoder = AutoModelForTextEncoding.from_config(config.text_encoder) if audio_encoder is None: from transformers.models.auto.modeling_auto import AutoModel audio_encoder = AutoModel.from_config(config.audio_encoder) if decoder is None: decoder = ParlerTTSForCausalLM(config.decoder) self.text_encoder = text_encoder self.audio_encoder = audio_encoder self.decoder = decoder if self.text_encoder.config.to_dict() != self.config.text_encoder.to_dict(): logger.warning( f"Config of the text_encoder: {self.text_encoder.__class__} is overwritten by shared text_encoder config:" f" {self.config.text_encoder}" ) if self.audio_encoder.config.to_dict() != self.config.audio_encoder.to_dict(): logger.warning( f"Config of the audio_encoder: {self.audio_encoder.__class__} is overwritten by shared audio_encoder config:" f" {self.config.audio_encoder}" ) if self.decoder.config.to_dict() != self.config.decoder.to_dict(): logger.warning( f"Config of the decoder: {self.decoder.__class__} is overwritten by shared decoder config:" f" {self.config.decoder}" ) # make sure that the individual model's config refers to the shared config # so that the updates to the config will be synced self.text_encoder.config = self.config.text_encoder self.audio_encoder.config = self.config.audio_encoder self.decoder.config = self.config.decoder # text encoder outputs might need to be projected to different dimension for decoder if ( self.text_encoder.config.hidden_size != self.decoder.config.hidden_size and self.decoder.config.cross_attention_hidden_size is None ): self.enc_to_dec_proj = nn.Linear(self.text_encoder.config.hidden_size, self.decoder.config.hidden_size) # prompt embeddings self.embed_prompts = nn.Embedding(config.vocab_size, self.decoder.config.hidden_size) self.prompt_cross_attention = config.prompt_cross_attention if config.prompt_cross_attention: self.embed_positions = ParlerTTSSinusoidalPositionalEmbedding( config.decoder.max_position_embeddings, config.decoder.hidden_size, ) if self.text_encoder.get_output_embeddings() is not None: raise ValueError( f"The encoder {self.text_encoder} should not have a LM Head. Please use a model without and LM Head" ) decoder_signature = set(inspect.signature(self.decoder.forward).parameters.keys()) if "encoder_hidden_states" not in decoder_signature: raise ValueError( "The selected decoder is not prepared for the encoder hidden states to be passed. Please see the " "following discussion on GitHub: https://github.com/huggingface/transformers/issues/23350" ) # Initialize projection and embedding layers and tie text encoder and decoder weights if set accordingly self.post_init() def _init_weights(self, module): std = self.decoder.config.initializer_factor if isinstance(module, (nn.Linear, nn.Conv1d)): module.weight.data.normal_(mean=0.0, std=std) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=std) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_() def tie_weights(self): # tie text encoder & decoder if needed if self.config.tie_encoder_decoder: # tie text encoder and decoder base model decoder_base_model_prefix = self.decoder.base_model_prefix self._tie_encoder_decoder_weights( self.text_encoder, self.decoder._modules[decoder_base_model_prefix], self.decoder.base_model_prefix ) def get_audio_encoder(self): return self.audio_encoder def get_text_encoder(self): return self.text_encoder def get_encoder(self): # get the text encoder to compute the encoder hidden-states for generation return self.get_text_encoder() def get_decoder(self): return self.decoder def get_input_embeddings(self): return self.text_encoder.get_input_embeddings() def get_output_embeddings(self): return self.decoder.get_output_embeddings() def set_output_embeddings(self, new_embeddings): return self.decoder.set_output_embeddings(new_embeddings) @classmethod def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): r""" Example: ```python >>> from parler_tts import ParlerTTSForConditionalGeneration >>> model = ParlerTTSForConditionalGeneration.from_pretrained("facebook/parler_tts-small") ```""" # At the moment fast initialization is not supported for composite models if kwargs.get("_fast_init", False): logger.warning( "Fast initialization is currently not supported for ParlerTTSForConditionalGeneration. " "Falling back to slow initialization..." ) kwargs["_fast_init"] = False return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs) @classmethod def from_sub_models_pretrained( cls, text_encoder_pretrained_model_name_or_path: str = None, audio_encoder_pretrained_model_name_or_path: str = None, decoder_pretrained_model_name_or_path: str = None, *model_args, **kwargs, ) -> PreTrainedModel: r""" Instantiate a text encoder, an audio encoder, and a Parler-TTS decoder from one, two or three base classes of the library from pretrained model checkpoints. The model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated). To train the model, you need to first set it back in training mode with `model.train()`. Params: text_encoder_pretrained_model_name_or_path (`str`, *optional*): Information necessary to initiate the text encoder. Can be either: - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co. Valid model ids can be located at the root-level, like `t5-base`, or namespaced under a user or organization name, like `google/flan-t5-base. - A path to a *directory* containing model weights saved using [`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`. audio_encoder_pretrained_model_name_or_path (`str`, *optional*): Information necessary to initiate the audio encoder. Can be either: - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co. Valid model ids can be located at the root-level, like `bert-base-uncased`, or namespaced under a user or organization name, like `facebook/encodec_24khz`. - A path to a *directory* containing model weights saved using [`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`. decoder_pretrained_model_name_or_path (`str`, *optional*, defaults to `None`): Information necessary to initiate the decoder. Can be either: - A string, the *model id* of a pretrained model hosted inside a model repo on huggingface.co. Valid model ids can be located at the root-level, like `gpt2`, or namespaced under a user or organization name, like `facebook/parler_tts-small`. - A path to a *directory* containing model weights saved using [`~PreTrainedModel.save_pretrained`], e.g., `./my_model_directory/`. model_args (remaining positional arguments, *optional*): All remaining positional arguments will be passed to the underlying model's `__init__` method. kwargs (remaining dictionary of keyword arguments, *optional*): Can be used to update the configuration object (after it being loaded) and initiate the model (e.g., `output_attentions=True`). - To update the text encoder configuration, use the prefix *text_encoder_* for each configuration parameter. - To update the audio encoder configuration, use the prefix *audio_encoder_* for each configuration parameter. - To update the decoder configuration, use the prefix *decoder_* for each configuration parameter. - To update the parent model configuration, do not use a prefix for each configuration parameter. Behaves differently depending on whether a `config` is provided or automatically loaded. Example: ```python >>> from parler_tts import ParlerTTSForConditionalGeneration >>> # initialize a parler_tts model from a t5 text encoder, encodec audio encoder, and parler_tts decoder >>> model = ParlerTTSForConditionalGeneration.from_sub_models_pretrained( ... text_encoder_pretrained_model_name_or_path="t5-base", ... audio_encoder_pretrained_model_name_or_path="facebook/encodec_24khz", ... decoder_pretrained_model_name_or_path="facebook/parler_tts-small", ... ) >>> # saving model after fine-tuning >>> model.save_pretrained("./parler_tts-ft") >>> # load fine-tuned model >>> model = ParlerTTSForConditionalGeneration.from_pretrained("./parler_tts-ft") ```""" kwargs_text_encoder = { argument[len("text_encoder_") :]: value for argument, value in kwargs.items() if argument.startswith("text_encoder_") } kwargs_audio_encoder = { argument[len("audio_encoder_") :]: value for argument, value in kwargs.items() if argument.startswith("audio_encoder_") } kwargs_decoder = { argument[len("decoder_") :]: value for argument, value in kwargs.items() if argument.startswith("decoder_") } # remove text encoder, audio encoder and decoder kwargs from kwargs for key in kwargs_text_encoder.keys(): del kwargs["text_encoder_" + key] for key in kwargs_audio_encoder.keys(): del kwargs["audio_encoder_" + key] for key in kwargs_decoder.keys(): del kwargs["decoder_" + key] # Load and initialize the encoder and decoder # The distinction between encoder and decoder at the model level is made # by the value of the flag `is_decoder` that we need to set correctly. text_encoder = kwargs_text_encoder.pop("model", None) if text_encoder is None: if text_encoder_pretrained_model_name_or_path is None: raise ValueError( "If `text_encoder_model` is not defined as an argument, a `text_encoder_pretrained_model_name_or_path` has " "to be defined." ) if "config" not in kwargs_text_encoder: encoder_config, kwargs_text_encoder = AutoConfig.from_pretrained( text_encoder_pretrained_model_name_or_path, **kwargs_text_encoder, return_unused_kwargs=True ) if encoder_config.is_decoder is True or encoder_config.add_cross_attention is True: logger.info( f"Initializing {text_encoder_pretrained_model_name_or_path} as a text_encoder model " "from a decoder model. Cross-attention and casual mask are disabled." ) encoder_config.is_decoder = False encoder_config.add_cross_attention = False kwargs_text_encoder["config"] = encoder_config text_encoder = AutoModelForTextEncoding.from_pretrained( text_encoder_pretrained_model_name_or_path, *model_args, **kwargs_text_encoder ) audio_encoder = kwargs_audio_encoder.pop("model", None) if audio_encoder is None: if audio_encoder_pretrained_model_name_or_path is None: raise ValueError( "If `audio_encoder_model` is not defined as an argument, an `audio_encoder_pretrained_model_name_or_path` has " "to be defined." ) if "config" not in kwargs_audio_encoder: encoder_config, kwargs_audio_encoder = AutoConfig.from_pretrained( audio_encoder_pretrained_model_name_or_path, **kwargs_audio_encoder, return_unused_kwargs=True ) if encoder_config.is_decoder is True or encoder_config.add_cross_attention is True: logger.info( f"Initializing {audio_encoder_pretrained_model_name_or_path} as an audio_encoder model " "from a decoder model. Cross-attention and casual mask are disabled." ) encoder_config.is_decoder = False encoder_config.add_cross_attention = False kwargs_audio_encoder["config"] = encoder_config audio_encoder = AutoModel.from_pretrained( audio_encoder_pretrained_model_name_or_path, *model_args, **kwargs_audio_encoder ) decoder = kwargs_decoder.pop("model", None) if decoder is None: if decoder_pretrained_model_name_or_path is None: raise ValueError( "If `decoder_model` is not defined as an argument, a `decoder_pretrained_model_name_or_path` has " "to be defined." ) if "config" not in kwargs_decoder: decoder_config, kwargs_decoder = ParlerTTSDecoderConfig.from_pretrained( decoder_pretrained_model_name_or_path, **kwargs_decoder, return_unused_kwargs=True ) if isinstance(decoder_config, ParlerTTSConfig): decoder_config = decoder_config.decoder if decoder_config.is_decoder is False or decoder_config.add_cross_attention is False: logger.info( f"Initializing {decoder_pretrained_model_name_or_path} as a decoder model. Cross attention" f" layers are added to {decoder_pretrained_model_name_or_path} and randomly initialized if" f" {decoder_pretrained_model_name_or_path}'s architecture allows for cross attention layers." ) decoder_config.is_decoder = True decoder_config.add_cross_attention = True kwargs_decoder["config"] = decoder_config if kwargs_decoder["config"].is_decoder is False or kwargs_decoder["config"].add_cross_attention is False: logger.warning( f"Decoder model {decoder_pretrained_model_name_or_path} is not initialized as a decoder. " f"In order to initialize {decoder_pretrained_model_name_or_path} as a decoder, " "make sure that the attributes `is_decoder` and `add_cross_attention` of `decoder_config` " "passed to `.from_sub_models_pretrained(...)` are set to `True` or do not pass a " "`decoder_config` to `.from_sub_models_pretrained(...)`" ) decoder = ParlerTTSForCausalLM.from_pretrained(decoder_pretrained_model_name_or_path, **kwargs_decoder) # instantiate config with corresponding kwargs config = ParlerTTSConfig.from_sub_models_config( text_encoder.config, audio_encoder.config, decoder.config, **kwargs ) return cls(text_encoder=text_encoder, audio_encoder=audio_encoder, decoder=decoder, config=config) @add_start_docstrings_to_model_forward(MUSICGEN_INPUTS_DOCSTRING) @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC) def forward( self, input_ids: Optional[torch.LongTensor] = None, attention_mask: Optional[torch.BoolTensor] = None, input_values: Optional[torch.FloatTensor] = None, padding_mask: Optional[torch.BoolTensor] = None, decoder_input_ids: Optional[torch.LongTensor] = None, decoder_attention_mask: Optional[torch.BoolTensor] = None, encoder_outputs: Optional[Tuple[torch.FloatTensor]] = None, past_key_values: Optional[Union[EncoderDecoderCache, Tuple[torch.FloatTensor]]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, decoder_inputs_embeds: Optional[torch.FloatTensor] = None, prompt_input_ids: Optional[torch.FloatTensor] = None, prompt_attention_mask: Optional[torch.LongTensor] = None, prompt_hidden_states: Optional[torch.FloatTensor] = None, decoder_position_ids: Optional[torch.LongTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, cache_position: Optional[torch.LongTensor] = None, **kwargs, ) -> Union[Tuple, Seq2SeqLMOutput]: r""" Returns: Examples: ```python >>> from transformers import AutoProcessor, ParlerTTSForConditionalGeneration >>> import torch >>> processor = AutoProcessor.from_pretrained("facebook/parler_tts-small") >>> model = ParlerTTSForConditionalGeneration.from_pretrained("facebook/parler_tts-small") >>> inputs = processor( ... text=["80s pop track with bassy drums and synth", "90s rock song with loud guitars and heavy drums"], ... padding=True, ... return_tensors="pt", ... ) >>> pad_token_id = model.generation_config.pad_token_id >>> decoder_input_ids = ( ... torch.ones((inputs.input_ids.shape[0] * model.decoder.num_codebooks, 1), dtype=torch.long) ... * pad_token_id ... ) >>> logits = model(**inputs, decoder_input_ids=decoder_input_ids).logits >>> logits.shape # (bsz * num_codebooks, tgt_len, vocab_size) torch.Size([8, 1, 2048]) ```""" return_dict = return_dict if return_dict is not None else self.config.use_return_dict kwargs_text_encoder = { argument[len("text_encoder_")]: value for argument, value in kwargs.items() if argument.startswith("text_encoder_") } kwargs_audio_encoder = { argument[len("audio_encoder_")]: value for argument, value in kwargs.items() if argument.startswith("audio_encoder_") } kwargs_decoder = { argument[len("decoder_") :]: value for argument, value in kwargs.items() if argument.startswith("decoder_") } if prompt_hidden_states is None: if prompt_input_ids is not None: prompt_hidden_states = self.embed_prompts(prompt_input_ids) if encoder_outputs is None: encoder_outputs = self.text_encoder( input_ids=input_ids, attention_mask=attention_mask, inputs_embeds=inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, **kwargs_text_encoder, ) encoder_hidden_states = encoder_outputs[0] # optionally project encoder_hidden_states if ( self.text_encoder.config.hidden_size != self.decoder.config.hidden_size and self.decoder.config.cross_attention_hidden_size is None ): encoder_hidden_states = self.enc_to_dec_proj(encoder_hidden_states) if attention_mask is not None: encoder_hidden_states = encoder_hidden_states * attention_mask[..., None] if prompt_hidden_states is not None and self.prompt_cross_attention: # add sinusoidal positional embedding positions = self.embed_positions(prompt_hidden_states, 0) prompt_hidden_states = prompt_hidden_states + positions.to(prompt_hidden_states.device) if prompt_attention_mask is not None and attention_mask is None: attention_mask = torch.ones( encoder_hidden_states.shape[:2], device=self.device, dtype=prompt_attention_mask.dtype ) elif attention_mask is not None and prompt_attention_mask is None: prompt_attention_mask = torch.ones( prompt_hidden_states.shape[:2], device=self.device, dtype=attention_mask.dtype ) # concatenate text description states with prompt description states encoder_hidden_states = torch.cat([encoder_hidden_states, prompt_hidden_states], dim=1) if prompt_attention_mask is not None: attention_mask = torch.cat([attention_mask, prompt_attention_mask], dim=1) prompt_hidden_states = None prompt_attention_mask = None encoder_outputs["last_hidden_state"] = encoder_hidden_states elif isinstance(encoder_outputs, tuple): encoder_outputs = BaseModelOutput(*encoder_outputs) encoder_hidden_states = encoder_outputs.last_hidden_state if (labels is not None) and (decoder_input_ids is None and decoder_inputs_embeds is None): decoder_input_ids = shift_tokens_right( labels, self.config.pad_token_id, self.config.decoder_start_token_id ).transpose(1, 2) elif decoder_input_ids is None and decoder_inputs_embeds is None: audio_encoder_outputs = self.audio_encoder( input_values=input_values, padding_mask=padding_mask, **kwargs_audio_encoder, ) audio_codes = audio_encoder_outputs.audio_codes frames, bsz, codebooks, seq_len = audio_codes.shape if frames != 1: raise ValueError( f"Expected 1 frame in the audio code outputs, got {frames} frames. Ensure chunking is " "disabled by setting `chunk_length=None` in the audio encoder." ) if self.config.decoder.audio_channels == 2 and audio_codes.shape[2] == self.decoder.num_codebooks // 2: # mono input through encodec that we convert to stereo audio_codes = audio_codes.repeat_interleave(2, dim=2) decoder_input_ids = audio_codes[0, ...].reshape(bsz * self.decoder.num_codebooks, seq_len) # Decode decoder_outputs = self.decoder( input_ids=decoder_input_ids, attention_mask=decoder_attention_mask, position_ids=decoder_position_ids, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=attention_mask, prompt_hidden_states=prompt_hidden_states, prompt_attention_mask=prompt_attention_mask, inputs_embeds=decoder_inputs_embeds, output_attentions=output_attentions, output_hidden_states=output_hidden_states, use_cache=use_cache, past_key_values=past_key_values, return_dict=return_dict, labels=labels, cache_position=cache_position, **kwargs_decoder, ) if not return_dict: return decoder_outputs + (encoder_hidden_states,) return Seq2SeqLMOutput( loss=decoder_outputs.loss, logits=decoder_outputs.logits, past_key_values=decoder_outputs.past_key_values, decoder_hidden_states=decoder_outputs.hidden_states, decoder_attentions=decoder_outputs.attentions, cross_attentions=decoder_outputs.cross_attentions, encoder_last_hidden_state=encoder_outputs.last_hidden_state, encoder_hidden_states=encoder_outputs.hidden_states, encoder_attentions=encoder_outputs.attentions, ) def prepare_inputs_for_generation( self, decoder_input_ids, past_key_values=None, attention_mask=None, head_mask=None, decoder_attention_mask=None, decoder_head_mask=None, prompt_hidden_states=None, prompt_attention_mask=None, cross_attn_head_mask=None, use_cache=None, encoder_outputs=None, decoder_delay_pattern_mask=None, cache_position=None, inputs_embeds=None, **kwargs, ): if decoder_delay_pattern_mask is None: decoder_input_ids, decoder_delay_pattern_mask = self.decoder.build_delay_pattern_mask( decoder_input_ids, bos_token_id=self.generation_config.bos_token_id, pad_token_id=self.generation_config.pad_token_id, max_length=self.generation_config.max_length, ) # apply the delay pattern mask decoder_input_ids = self.decoder.apply_delay_pattern_mask(decoder_input_ids, decoder_delay_pattern_mask) past_length = 0 if past_key_values is not None: if isinstance(past_key_values, EncoderDecoderCache): past_length = cache_position[0] if cache_position is not None else past_key_values.get_seq_length() if past_key_values.get_seq_length() > 0: # we only want to use prompt signal in the 1st generation step prompt_hidden_states = None else: past_length = past_key_values[0][0].shape[2] # we only want to use prompt signal in the 1st generation step prompt_hidden_states = None # Some generation methods already pass only the last input ID if decoder_input_ids.shape[1] > past_length: remove_prefix_length = past_length else: # Default to old behavior: keep only final ID remove_prefix_length = decoder_input_ids.shape[1] - 1 decoder_input_ids = decoder_input_ids[:, remove_prefix_length:] if cache_position is None: cache_position = torch.arange( past_length, past_length + decoder_input_ids.shape[1], device=decoder_input_ids.device ) elif use_cache: cur_len = decoder_input_ids.shape[1] if prompt_hidden_states is not None and not self.prompt_cross_attention: # meaning we are in 1st generation step and prompt_hidden_state will be prepended cur_len += prompt_hidden_states.shape[1] cache_position = cache_position[-cur_len:] if decoder_attention_mask is None and prompt_attention_mask is not None: input = decoder_input_ids.reshape(-1, self.decoder.num_codebooks, decoder_input_ids.shape[-1]) bsz, _, seq_len = input.shape input_shape = (bsz, seq_len) past_key_values_length = 0 if cache_position is not None: past_key_values_length = cache_position[0] elif past_key_values is not None: past_key_values_length = past_key_values.get_seq_length() logger.warning_once( "`prompt_attention_mask` is specified but `attention_mask` is not. A full `attention_mask` will be created. Make sure this is the intended behaviour." ) if past_key_values is None or ( isinstance(past_key_values, EncoderDecoderCache) and past_key_values.get_seq_length() == 0 ): decoder_attention_mask = torch.ones(input_shape, device=self.device, dtype=decoder_input_ids.dtype) elif prompt_attention_mask is not None: # In the generation case of `prompt_cross_attention=True`, we need to recreate an attention mask from scratch # to be able to prepend the prompt attention mask. # Since we generate token per token, we can recompute the generated length from the information we have. generated_length = past_key_values_length - prompt_attention_mask.shape[1] + 1 decoder_attention_mask = torch.ones( (input_shape[0], generated_length), device=self.device, dtype=prompt_attention_mask.dtype ) return { "input_ids": None, # encoder_outputs is defined. input_ids not needed "encoder_outputs": encoder_outputs, "past_key_values": past_key_values, "decoder_input_ids": decoder_input_ids.contiguous(), "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, "prompt_hidden_states": prompt_hidden_states, "prompt_attention_mask": prompt_attention_mask, "use_cache": use_cache, "cache_position": cache_position, "inputs_embeds": inputs_embeds, } def _prepare_decoder_input_ids_for_generation( self, batch_size: int, model_input_name: str, model_kwargs: Dict[str, torch.Tensor], decoder_start_token_id: int = None, bos_token_id: int = None, device: torch.device = None, ) -> Tuple[torch.LongTensor, Dict[str, torch.Tensor]]: """Prepares `decoder_input_ids` for generation with encoder-decoder models""" # 1. Check whether the user has defined `decoder_input_ids` manually. To facilitate in terms of input naming, # we also allow the user to pass it under `input_ids`, if the encoder does not use it as the main input. if model_kwargs is not None and "decoder_input_ids" in model_kwargs: decoder_input_ids = model_kwargs.pop("decoder_input_ids") elif "input_ids" in model_kwargs and model_input_name != "input_ids": decoder_input_ids = model_kwargs.pop("input_ids") else: decoder_input_ids = None # 2. Encoder-decoder models expect the `decoder_input_ids` to start with a special token. Let's ensure that. decoder_start_token_id = self._get_decoder_start_token_id(decoder_start_token_id, bos_token_id) if device is None: device = self.device decoder_input_ids_start = ( torch.ones((batch_size * self.decoder.num_codebooks, 1), dtype=torch.long, device=device) * decoder_start_token_id ) # no user input -> use decoder_start_token_id as decoder_input_ids if decoder_input_ids is None: decoder_input_ids = decoder_input_ids_start # user input but doesn't start with decoder_start_token_id -> prepend decoder_start_token_id (and adjust # decoder_attention_mask if provided) elif (decoder_input_ids[..., 0] != decoder_start_token_id).all().item(): decoder_input_ids = torch.cat([decoder_input_ids_start, decoder_input_ids], dim=-1) if "decoder_attention_mask" in model_kwargs: decoder_attention_mask = model_kwargs["decoder_attention_mask"] decoder_attention_mask = torch.cat( (torch.ones_like(decoder_attention_mask)[:, :1], decoder_attention_mask), dim=-1, ) model_kwargs["decoder_attention_mask"] = decoder_attention_mask if not self.prompt_cross_attention: prompt_hidden_states = model_kwargs["prompt_hidden_states"] num_codebooks = self.decoder.num_codebooks input = decoder_input_ids.reshape(-1, num_codebooks, decoder_input_ids.shape[-1]) inputs_embeds = sum( [ self.decoder.model.decoder.embed_tokens[codebook](input[:, codebook]) for codebook in range(num_codebooks) ] ) inputs_embeds = torch.cat([prompt_hidden_states, inputs_embeds], dim=1) model_kwargs["inputs_embeds"] = inputs_embeds return decoder_input_ids, model_kwargs def _prepare_text_encoder_kwargs_for_generation( self, inputs_tensor: torch.Tensor, model_kwargs, model_input_name: Optional[str], generation_config: GenerationConfig, ) -> Dict[str, Any]: # 1. get text encoder encoder = self.get_text_encoder() # Compatibility with Accelerate big model inference: we need the encoder to outputs stuff on the same device # as the inputs. if hasattr(encoder, "_hf_hook"): encoder._hf_hook.io_same_device = True # 2. Prepare encoder args and encoder kwargs from model kwargs. irrelevant_prefix = ["decoder_", "cross_attn", "use_cache"] encoder_kwargs = { argument: value for argument, value in model_kwargs.items() if not any(argument.startswith(p) for p in irrelevant_prefix) } encoder_signature = set(inspect.signature(encoder.forward).parameters) encoder_accepts_wildcard = "kwargs" in encoder_signature or "model_kwargs" in encoder_signature if not encoder_accepts_wildcard: encoder_kwargs = { argument: value for argument, value in encoder_kwargs.items() if argument in encoder_signature } encoder_kwargs["output_attentions"] = generation_config.output_attentions encoder_kwargs["output_hidden_states"] = generation_config.output_hidden_states # 3. make sure that encoder returns `ModelOutput` model_input_name = model_input_name if model_input_name is not None else self.text_encoder.main_input_name encoder_kwargs["return_dict"] = True encoder_kwargs[model_input_name] = inputs_tensor last_hidden_state = encoder(**encoder_kwargs).last_hidden_state # we optionnally project last_hidden_state to avoid recomputing every time encoder_hidden_states = last_hidden_state if ( self.text_encoder.config.hidden_size != self.decoder.config.hidden_size and self.decoder.config.cross_attention_hidden_size is None ): encoder_hidden_states = self.enc_to_dec_proj(encoder_hidden_states) if model_kwargs["attention_mask"] is not None: encoder_hidden_states = encoder_hidden_states * model_kwargs["attention_mask"][..., None] model_kwargs["encoder_outputs"] = BaseModelOutput(last_hidden_state=encoder_hidden_states) return model_kwargs def _prepare_prompt_kwargs_for_generation(self, prompt_input_ids, model_kwargs): prompt_hidden_states = self.embed_prompts(prompt_input_ids) if self.prompt_cross_attention: # add sinusoidal positional embedding positions = self.embed_positions(prompt_hidden_states, 0) prompt_hidden_states = prompt_hidden_states + positions.to(prompt_hidden_states.device) attention_mask = model_kwargs.get("attention_mask", None) prompt_attention_mask = model_kwargs.get("prompt_attention_mask", None) encoder_hidden_states = model_kwargs["encoder_outputs"].last_hidden_state if prompt_attention_mask is not None and attention_mask is None: attention_mask = torch.ones( encoder_hidden_states.shape[:2], device=self.device, dtype=prompt_attention_mask.dtype ) elif attention_mask is not None and prompt_attention_mask is None: prompt_attention_mask = torch.ones( prompt_hidden_states.shape[:2], device=self.device, dtype=attention_mask.dtype ) # concatenate text description states with prompt description states encoder_hidden_states = torch.cat([encoder_hidden_states, prompt_hidden_states], dim=1) if prompt_attention_mask is not None: attention_mask = torch.cat([attention_mask, prompt_attention_mask], dim=1) model_kwargs["encoder_outputs"].last_hidden_state = encoder_hidden_states model_kwargs["attention_mask"] = attention_mask # in this case, since we already concatenated the prompt hidden states and attention mask, we don't need them anymore. model_kwargs["prompt_hidden_states"] = None model_kwargs["prompt_attention_mask"] = None else: model_kwargs["prompt_hidden_states"] = prompt_hidden_states # we're keeping the prompt attention mask because it has to be prepended to the decoder attention mask on the fly return model_kwargs def _prepare_audio_encoder_kwargs_for_generation( self, input_values, model_kwargs, model_input_name: Optional[str] = None ): # 1. get audio encoder encoder = self.get_audio_encoder() # Compatibility with Accelerate big model inference: we need the encoder to outputs stuff on the same device # as the inputs. if hasattr(encoder, "_hf_hook"): encoder._hf_hook.io_same_device = True # 2. Prepare encoder args and encoder kwargs from model kwargs. irrelevant_prefix = ["decoder_", "cross_attn", "use_cache"] encoder_kwargs = { argument: value for argument, value in model_kwargs.items() if not any(argument.startswith(p) for p in irrelevant_prefix) } encoder_signature = set(inspect.signature(encoder.forward).parameters) encoder_accepts_wildcard = "kwargs" in encoder_signature or "model_kwargs" in encoder_signature if not encoder_accepts_wildcard: encoder_kwargs = { argument: value for argument, value in encoder_kwargs.items() if argument in encoder_signature } # 3. make sure that encoder returns `ModelOutput` model_input_name = model_input_name if model_input_name is not None else self.audio_encoder.main_input_name encoder_kwargs["return_dict"] = True encoder_kwargs[model_input_name] = input_values audio_encoder_outputs = encoder.encode(**encoder_kwargs) audio_codes = audio_encoder_outputs.audio_codes audio_scales = audio_encoder_outputs.audio_scales frames, bsz, codebooks, seq_len = audio_codes.shape if frames != 1: raise ValueError( f"Expected 1 frame in the audio code outputs, got {frames} frames. Ensure chunking is " "disabled by setting `chunk_length=None` in the audio encoder." ) decoder_input_ids = audio_codes[0, ...].reshape(bsz * self.decoder.num_codebooks, seq_len) model_kwargs["decoder_input_ids"] = decoder_input_ids model_kwargs["audio_scales"] = audio_scales return model_kwargs def prepare_decoder_input_ids_from_labels(self, labels: torch.Tensor): return shift_tokens_right( labels, self.config.decoder.pad_token_id, self.config.decoder.bos_token_id ).transpose(1, 2) def resize_token_embeddings(self, *args, **kwargs): raise NotImplementedError( "Resizing the embedding layers via the EncoderDecoderModel directly is not supported. Please use the" " respective methods of the wrapped objects (model.encoder.resize_token_embeddings(...) or" " model.decoder.resize_token_embeddings(...))" ) def _maybe_initialize_input_ids_for_generation( self, inputs: Optional[torch.Tensor] = None, bos_token_id: Optional[int] = None, model_kwargs: Optional[Dict[str, torch.Tensor]] = None, ) -> torch.LongTensor: """Initializes input ids for generation, if necessary.""" if inputs is not None: return inputs encoder_outputs = model_kwargs.get("encoder_outputs") if encoder_outputs is not None: # make dummy input_ids with value -100, as a sanity check ensuring that they won't be used for encoding shape = encoder_outputs[0].size()[:-1] return torch.ones(shape, dtype=torch.long, device=self.device) * -100 if bos_token_id is None: raise ValueError("`bos_token_id` has to be defined when no `input_ids` are provided.") # If there is some tensor in `model_kwargs`, we can infer the batch size from it. This is helpful with # soft-prompting or in multimodal implementations built on top of decoder-only language models. batch_size = 1 for value in model_kwargs.values(): if isinstance(value, torch.Tensor): batch_size = value.shape[0] break return torch.ones((batch_size, 1), dtype=torch.long, device=self.device) * bos_token_id def _get_decoder_start_token_id( self, decoder_start_token_id: Union[int, List[int]] = None, bos_token_id: int = None ) -> int: decoder_start_token_id = ( decoder_start_token_id if decoder_start_token_id is not None else self.generation_config.decoder_start_token_id ) bos_token_id = bos_token_id if bos_token_id is not None else self.generation_config.bos_token_id if decoder_start_token_id is not None: return decoder_start_token_id elif bos_token_id is not None: return bos_token_id raise ValueError( "`decoder_start_token_id` or `bos_token_id` has to be defined for encoder-decoder generation." ) def _get_cache(self, cache_implementation: str, max_batch_size: int, max_cache_len: int, model_kwargs) -> Cache: """ Sets a cache for `generate`, that will persist across calls. A new cache will only be initialized a new `generate` call requires a larger cache. Returns the resulting cache object. """ cache_cls: Cache = NEED_SETUP_CACHE_CLASSES_MAPPING[cache_implementation] requires_cross_attention_cache = ( self.config.is_encoder_decoder or model_kwargs.get("encoder_outputs") is not None ) if hasattr(self, "_cache"): cache_to_check = self._cache.self_attention_cache if requires_cross_attention_cache else self._cache if cache_implementation == "sliding_window": max_cache_len = min(self.config.sliding_window, max_cache_len) need_new_cache = ( not hasattr(self, "_cache") or (not isinstance(cache_to_check, cache_cls)) or cache_to_check.max_batch_size != max_batch_size or cache_to_check.max_cache_len < max_cache_len ) if requires_cross_attention_cache and hasattr(self, "_cache"): need_new_cache = ( need_new_cache or self._cache.cross_attention_cache.max_cache_len != model_kwargs["encoder_outputs"][0].shape[1] ) if need_new_cache: if hasattr(self.config, "_pre_quantization_dtype"): cache_dtype = self.config._pre_quantization_dtype else: cache_dtype = self.dtype cache_kwargs = { "config": self.config.decoder, "max_batch_size": max_batch_size, "max_cache_len": max_cache_len, "device": self.device, "dtype": cache_dtype, } self._cache = cache_cls(**cache_kwargs) if requires_cross_attention_cache: encoder_kwargs = cache_kwargs.copy() encoder_kwargs["max_cache_len"] = model_kwargs["encoder_outputs"][0].shape[1] config_cross_attention_cache = copy.deepcopy(self.config.decoder) config_cross_attention_cache.update( {"num_key_value_heads": self.config.decoder.num_cross_attention_key_value_heads} ) encoder_kwargs["config"] = config_cross_attention_cache self._cache = EncoderDecoderCache(self._cache, cache_cls(**encoder_kwargs)) else: self._cache.reset() return self._cache def freeze_encoders(self, freeze_text_encoder=True): if freeze_text_encoder: for param in self.text_encoder.parameters(): param.requires_grad = False self.text_encoder._requires_grad = False for param in self.audio_encoder.parameters(): param.requires_grad = False self.audio_encoder._requires_grad = False @torch.no_grad() def generate( self, inputs: Optional[torch.Tensor] = None, generation_config: Optional[GenerationConfig] = None, logits_processor: Optional[LogitsProcessorList] = None, stopping_criteria: Optional[StoppingCriteriaList] = None, synced_gpus: Optional[bool] = None, streamer: Optional["BaseStreamer"] = None, **kwargs, ): """ Generates sequences of token ids for models with a language modeling head. <Tip warning={true}> Most generation-controlling parameters are set in `generation_config` which, if not passed, will be set to the model's default generation configuration. You can override any `generation_config` by passing the corresponding parameters to generate(), e.g. `.generate(inputs, num_beams=4, do_sample=True)`. For an overview of generation strategies and code examples, check out the [following guide](./generation_strategies). </Tip> Parameters: inputs (`torch.Tensor` of varying shape depending on the modality, *optional*): The sequence used as a prompt for the generation or as model inputs to the encoder. If `None` the method initializes it with `bos_token_id` and a batch size of 1. For decoder-only models `inputs` should be in the format `input_ids`. For encoder-decoder models *inputs* can represent any of `input_ids`, `input_values`, `input_features`, or `pixel_values`. generation_config (`~generation.GenerationConfig`, *optional*): The generation configuration to be used as base parametrization for the generation call. `**kwargs` passed to generate matching the attributes of `generation_config` will override them. If `generation_config` is not provided, the default will be used, which had the following loading priority: 1) from the `generation_config.json` model file, if it exists; 2) from the model configuration. Please note that unspecified parameters will inherit [`~generation.GenerationConfig`]'s default values, whose documentation should be checked to parameterize generation. logits_processor (`LogitsProcessorList`, *optional*): Custom logits processors that complement the default logits processors built from arguments and generation config. If a logit processor is passed that is already created with the arguments or a generation config an error is thrown. This feature is intended for advanced users. stopping_criteria (`StoppingCriteriaList`, *optional*): Custom stopping criteria that complement the default stopping criteria built from arguments and a generation config. If a stopping criteria is passed that is already created with the arguments or a generation config an error is thrown. This feature is intended for advanced users. synced_gpus (`bool`, *optional*, defaults to `False`): Whether to continue running the while loop until max_length (needed for ZeRO stage 3) streamer (`BaseStreamer`, *optional*): Streamer object that will be used to stream the generated sequences. Generated tokens are passed through `streamer.put(token_ids)` and the streamer is responsible for any further processing. kwargs (`Dict[str, Any]`, *optional*): Ad hoc parametrization of `generate_config` and/or additional model-specific kwargs that will be forwarded to the `forward` function of the model. If the model is an encoder-decoder model, encoder specific kwargs should not be prefixed and decoder specific kwargs should be prefixed with *decoder_*. Return: [`~utils.ModelOutput`] or `torch.LongTensor`: A [`~utils.ModelOutput`] (if `return_dict_in_generate=True` or when `config.return_dict_in_generate=True`) or a `torch.FloatTensor`. If the model is *not* an encoder-decoder model (`model.config.is_encoder_decoder=False`), the possible [`~utils.ModelOutput`] types are: - [`~generation.GenerateDecoderOnlyOutput`], - [`~generation.GenerateBeamDecoderOnlyOutput`] If the model is an encoder-decoder model (`model.config.is_encoder_decoder=True`), the possible [`~utils.ModelOutput`] types are: - [`~generation.GenerateEncoderDecoderOutput`], - [`~generation.GenerateBeamEncoderDecoderOutput`] """ # 1. Handle `generation_config` and kwargs that might update it, and validate the resulting objects if generation_config is None: generation_config = self.generation_config generation_config = copy.deepcopy(generation_config) model_kwargs = generation_config.update(**kwargs) # All unused kwargs must be model kwargs generation_config.validate() self._validate_model_kwargs(model_kwargs.copy()) if model_kwargs.get("encoder_outputs") is not None and type(model_kwargs["encoder_outputs"]) == tuple: # wrap the unconditional outputs as a BaseModelOutput for compatibility with the rest of generate model_kwargs["encoder_outputs"] = BaseModelOutput(last_hidden_state=model_kwargs["encoder_outputs"][0]) # 2. Set generation parameters if not already defined logits_processor = logits_processor if logits_processor is not None else LogitsProcessorList() stopping_criteria = stopping_criteria if stopping_criteria is not None else StoppingCriteriaList() requires_attention_mask = "encoder_outputs" not in model_kwargs kwargs_has_attention_mask = model_kwargs.get("attention_mask", None) is not None # 3. Define model inputs inputs_tensor, model_input_name, model_kwargs = self._prepare_model_inputs( inputs, generation_config.bos_token_id, model_kwargs ) batch_size = inputs_tensor.shape[0] self._prepare_special_tokens(generation_config, kwargs_has_attention_mask, device=inputs_tensor.device) # 4. Define other model kwargs model_kwargs["use_cache"] = generation_config.use_cache if model_kwargs.get("attention_mask", None) is None and requires_attention_mask: model_kwargs["attention_mask"] = self._prepare_attention_mask_for_generation( inputs_tensor, generation_config._pad_token_tensor, generation_config._eos_token_tensor ) if "encoder_outputs" not in model_kwargs: # encoder_outputs are created and added to `model_kwargs` model_kwargs = self._prepare_text_encoder_kwargs_for_generation( inputs_tensor, model_kwargs, model_input_name, generation_config ) if "prompt_hidden_states" not in model_kwargs and "prompt_input_ids" in model_kwargs: # `prompt_hidden_states` are created and added to `model_kwargs` model_kwargs = self._prepare_prompt_kwargs_for_generation( model_kwargs["prompt_input_ids"], model_kwargs, ) if "decoder_input_ids" not in model_kwargs and "input_values" in model_kwargs: model_kwargs = self._prepare_audio_encoder_kwargs_for_generation( model_kwargs["input_values"], model_kwargs, ) # 5. Prepare `input_ids` which will be used for auto-regressive generation input_ids, model_kwargs = self._prepare_decoder_input_ids_for_generation( batch_size=batch_size, model_input_name=model_input_name, model_kwargs=model_kwargs, decoder_start_token_id=generation_config._decoder_start_token_tensor, bos_token_id=generation_config._bos_token_tensor, device=inputs_tensor.device, ) # 6. Prepare `max_length` depending on other stopping criteria. input_ids_length = input_ids.shape[-1] has_default_max_length = kwargs.get("max_length") is None and generation_config.max_length is not None has_default_min_length = kwargs.get("min_length") is None and generation_config.min_length is not None generation_config = self._prepare_generated_length( generation_config=generation_config, has_default_max_length=has_default_max_length, has_default_min_length=has_default_min_length, model_input_name=model_input_name, inputs_tensor=inputs_tensor, input_ids_length=input_ids_length, ) if generation_config.cache_implementation is not None and model_kwargs.get("past_key_values") is not None: raise ValueError( "Passing both `cache_implementation` (used to initialize certain caches) and `past_key_values` (a " "Cache object) is unsupported. Please use only one of the two." ) elif generation_config.cache_implementation is not None: if generation_config.cache_implementation in NEED_SETUP_CACHE_CLASSES_MAPPING: if generation_config.cache_implementation == "static" and not self._supports_static_cache: raise ValueError( "This model does not support `cache_implementation='static'`. Please check the following " "issue: https://github.com/huggingface/transformers/issues/28981" ) if not self.prompt_cross_attention: # when we prepend prompt_hidden_state to inputs_embeds, max_cache_len needs to be actualised # generation_config.max_length has already been increased by input_ids_length which is # already counted in input_embeds_seq_length so we remove it input_embeds_seq_length = model_kwargs["inputs_embeds"].shape[1] max_cache_len = generation_config.max_length + input_embeds_seq_length - input_ids_length else: max_cache_len = self.generation_config.max_length model_kwargs["past_key_values"] = self._get_cache( generation_config.cache_implementation, getattr(generation_config, "num_beams", 1) * batch_size, max_cache_len, model_kwargs, ) elif generation_config.cache_implementation == "quantized": raise ValueError( "This model does not support the quantized cache. If you want your model to support quantized " "cache, please open an issue on the Parler-TTS repository https://github.com/huggingface/parler-tts" ) # Use DynamicCache() instance by default. This will avoid back and forth from legacy format that # keeps copying the cache thus using much more memory elif generation_config.cache_implementation is None and self._supports_default_dynamic_cache(): past = model_kwargs.get("past_key_values", None) requires_cross_attention_cache = ( self.config.is_encoder_decoder or model_kwargs.get("encoder_outputs") is not None ) if past is None: model_kwargs["past_key_values"] = ( DynamicCache() if not requires_cross_attention_cache else EncoderDecoderCache(DynamicCache(), DynamicCache()) ) elif isinstance(past, tuple): model_kwargs["past_key_values"] = ( DynamicCache.from_legacy_cache(past) if not requires_cross_attention_cache else EncoderDecoderCache.from_legacy_cache(past) ) # build the delay pattern mask for offsetting each codebook prediction by 1 (this behaviour is specific to Parler-TTS) input_ids, decoder_delay_pattern_mask = self.decoder.build_delay_pattern_mask( input_ids, bos_token_id=generation_config._bos_token_tensor, pad_token_id=generation_config._pad_token_tensor, max_length=generation_config.max_length, ) # stash the delay mask so that we don't have to recompute in each forward pass model_kwargs["decoder_delay_pattern_mask"] = decoder_delay_pattern_mask # input_ids are ready to be placed on the streamer (if used) if streamer is not None: streamer.put(input_ids.cpu()) # 7. determine generation mode is_greedy_gen_mode = ( (generation_config.num_beams == 1) and (generation_config.num_beam_groups == 1) and generation_config.do_sample is False ) is_sample_gen_mode = ( (generation_config.num_beams == 1) and (generation_config.num_beam_groups == 1) and generation_config.do_sample is True ) # 8. prepare distribution pre_processing samplers logits_processor = self._get_logits_processor( generation_config=generation_config, input_ids_seq_length=input_ids_length, encoder_input_ids=inputs_tensor, prefix_allowed_tokens_fn=None, logits_processor=logits_processor, device=input_ids.device, ) # 9. prepare stopping criteria stopping_criteria = self._get_stopping_criteria( generation_config=generation_config, stopping_criteria=stopping_criteria ) if is_greedy_gen_mode: if generation_config.num_return_sequences > 1: raise ValueError( "num_return_sequences has to be 1 when doing greedy search, " f"but is {generation_config.num_return_sequences}." ) # 10. run greedy search outputs = self._sample( input_ids, logits_processor=logits_processor, stopping_criteria=stopping_criteria, generation_config=generation_config, synced_gpus=synced_gpus, streamer=streamer, **model_kwargs, ) elif is_sample_gen_mode: # 10. prepare logits warper logits_warper = self._get_logits_warper(generation_config, device=input_ids.device) # expand input_ids with `num_return_sequences` additional sequences per batch input_ids, model_kwargs = self._expand_inputs_for_generation( input_ids=input_ids, expand_size=generation_config.num_return_sequences, is_encoder_decoder=self.config.is_encoder_decoder, **model_kwargs, ) # 11. run sample outputs = self._sample( input_ids, logits_processor=logits_processor, logits_warper=logits_warper, stopping_criteria=stopping_criteria, generation_config=generation_config, synced_gpus=synced_gpus, streamer=streamer, **model_kwargs, ) else: raise ValueError( "Got incompatible mode for generation, should be one of greedy or sampling. " "Ensure that beam search is de-activated by setting `num_beams=1` and `num_beam_groups=1`." ) if generation_config.return_dict_in_generate: output_ids = outputs.sequences else: output_ids = outputs # Apply the pattern mask to the final ids output_ids = self.decoder.apply_delay_pattern_mask(output_ids, model_kwargs["decoder_delay_pattern_mask"]) # Revert the pattern delay mask by filtering the eos and bos token ids from the delay pattern mask _, mask = self.decoder.build_delay_pattern_mask( input_ids, bos_token_id=generation_config._bos_token_tensor, pad_token_id=generation_config._pad_token_tensor, max_length=output_ids.shape[1], ) mask = (mask != generation_config.bos_token_id) & (mask != generation_config.pad_token_id) output_ids = output_ids[mask].reshape(batch_size, self.decoder.num_codebooks, -1) # append the frame dimension back to the audio codes output_ids = output_ids[None, ...] audio_scales = model_kwargs.get("audio_scales") if audio_scales is None: audio_scales = [None] * batch_size decode_sequentially = ( generation_config.bos_token_id in output_ids or generation_config.pad_token_id in output_ids or generation_config.eos_token_id in output_ids ) if not decode_sequentially: output_values = self.audio_encoder.decode( output_ids, audio_scales=audio_scales, ).audio_values.squeeze(1) output_lengths = [audio.shape[0] for audio in output_values] else: output_values = [] for sample_id in range(batch_size): sample = output_ids[:, sample_id] sample_mask = (sample >= self.audio_encoder.config.codebook_size).sum(dim=(0, 1)) == 0 if sample_mask.sum() > 0: sample = sample[:, :, sample_mask] sample = self.audio_encoder.decode(sample[None, ...], [audio_scales[sample_id]]).audio_values output_values.append(sample.transpose(0, 2)) else: output_values.append(torch.zeros((1, 1, 1)).to(self.device)) output_lengths = [audio.shape[0] for audio in output_values] output_values = ( torch.nn.utils.rnn.pad_sequence(output_values, batch_first=True, padding_value=0) .squeeze(-1) .squeeze(-1) ) if generation_config.return_dict_in_generate: outputs["audios_length"] = output_lengths outputs.sequences = output_values return outputs else: return output_values
parler-tts/parler_tts/modeling_parler_tts.py/0
{ "file_path": "parler-tts/parler_tts/modeling_parler_tts.py", "repo_id": "parler-tts", "token_count": 76876 }
179
<!--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. ⚠️ 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. --> # Quantization Quantization represents data with fewer bits, making it a useful technique for reducing memory-usage and accelerating inference especially when it comes to large language models (LLMs). There are several ways to quantize a model including: * optimizing which model weights are quantized with the [AWQ](https://hf.co/papers/2306.00978) algorithm * independently quantizing each row of a weight matrix with the [GPTQ](https://hf.co/papers/2210.17323) algorithm * quantizing to 8-bit and 4-bit precision with the [bitsandbytes](https://github.com/TimDettmers/bitsandbytes) library * quantizing to as low as 2-bit precision with the [AQLM](https://arxiv.org/abs/2401.06118) algorithm However, after a model is quantized it isn't typically further trained for downstream tasks because training can be unstable due to the lower precision of the weights and activations. But since PEFT methods only add *extra* trainable parameters, this allows you to train a quantized model with a PEFT adapter on top! Combining quantization with PEFT can be a good strategy for training even the largest models on a single GPU. For example, [QLoRA](https://hf.co/papers/2305.14314) is a method that quantizes a model to 4-bits and then trains it with LoRA. This method allows you to finetune a 65B parameter model on a single 48GB GPU! In this guide, you'll see how to quantize a model to 4-bits and train it with LoRA. ## Quantize a model [bitsandbytes](https://github.com/TimDettmers/bitsandbytes) is a quantization library with a Transformers integration. With this integration, you can quantize a model to 8 or 4-bits and enable many other options by configuring the [`~transformers.BitsAndBytesConfig`] class. For example, you can: * set `load_in_4bit=True` to quantize the model to 4-bits when you load it * set `bnb_4bit_quant_type="nf4"` to use a special 4-bit data type for weights initialized from a normal distribution * set `bnb_4bit_use_double_quant=True` to use a nested quantization scheme to quantize the already quantized weights * set `bnb_4bit_compute_dtype=torch.bfloat16` to use bfloat16 for faster computation ```py import torch from transformers import BitsAndBytesConfig config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.bfloat16, ) ``` Pass the `config` to the [`~transformers.AutoModelForCausalLM.from_pretrained`] method. ```py from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1", quantization_config=config) ``` Next, you should call the [`~peft.utils.prepare_model_for_kbit_training`] function to preprocess the quantized model for training. ```py from peft import prepare_model_for_kbit_training model = prepare_model_for_kbit_training(model) ``` Now that the quantized model is ready, let's set up a configuration. ## LoraConfig Create a [`LoraConfig`] with the following parameters (or choose your own): ```py from peft import LoraConfig config = LoraConfig( r=16, lora_alpha=8, target_modules=["q_proj", "k_proj", "v_proj", "o_proj"], lora_dropout=0.05, bias="none", task_type="CAUSAL_LM" ) ``` Then use the [`get_peft_model`] function to create a [`PeftModel`] from the quantized model and configuration. ```py from peft import get_peft_model model = get_peft_model(model, config) ``` You're all set for training with whichever training method you prefer! ### LoftQ initialization [LoftQ](https://hf.co/papers/2310.08659) initializes LoRA weights such that the quantization error is minimized, and it can improve performance when training quantized models. To get started, follow [these instructions](https://github.com/huggingface/peft/tree/main/examples/loftq_finetuning). In general, for LoftQ to work best, it is recommended to target as many layers with LoRA as possible, since those not targeted cannot have LoftQ applied. This means that passing `LoraConfig(..., target_modules="all-linear")` will most likely give the best results. Also, you should use `nf4` as quant type in your quantization config when using 4bit quantization, i.e. `BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4")`. ### QLoRA-style training QLoRA adds trainable weights to all the linear layers in the transformer architecture. Since the attribute names for these linear layers can vary across architectures, set `target_modules` to `"all-linear"` to add LoRA to all the linear layers: ```py config = LoraConfig(target_modules="all-linear", ...) ``` ## AQLM quantization Additive Quantization of Language Models ([AQLM](https://arxiv.org/abs/2401.06118)) is a Large Language Models compression method. It quantizes multiple weights together and takes advantage of interdependencies between them. AQLM represents groups of 8-16 weights as a sum of multiple vector codes. This allows it to compress models down to as low as 2-bit with considerably low accuracy losses. Since the AQLM quantization process is computationally expensive, a use of prequantized models is recommended. A partial list of available models can be found in the official aqlm [repository](https://github.com/Vahe1994/AQLM). The models support LoRA adapter tuning. To tune the quantized model you'll need to install the `aqlm` inference library: `pip install aqlm>=1.0.2`. Finetuned LoRA adapters shall be saved separately, as merging them with AQLM quantized weights is not possible. ```py quantized_model = AutoModelForCausalLM.from_pretrained( "BlackSamorez/Mixtral-8x7b-AQLM-2Bit-1x16-hf-test-dispatch", torch_dtype="auto", device_map="auto", low_cpu_mem_usage=True, ) peft_config = LoraConfig(...) quantized_model = get_peft_model(quantized_model, peft_config) ``` You can refer to the [Google Colab](https://colab.research.google.com/drive/12GTp1FCj5_0SnnNQH18h_2XFh9vS_guX?usp=sharing) example for an overview of AQLM+LoRA finetuning. ## EETQ quantization You can also perform LoRA fine-tuning on EETQ quantized models. [EETQ](https://github.com/NetEase-FuXi/EETQ) package offers simple and efficient way to perform 8-bit quantization, which is claimed to be faster than the `LLM.int8()` algorithm. First, make sure that you have a transformers version that is compatible with EETQ (e.g. by installing it from latest pypi or from source). ```py import torch from transformers import EetqConfig config = EetqConfig("int8") ``` Pass the `config` to the [`~transformers.AutoModelForCausalLM.from_pretrained`] method. ```py from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1", quantization_config=config) ``` and create a `LoraConfig` and pass it to `get_peft_model`: ```py from peft import LoraConfig, get_peft_model config = LoraConfig( r=16, lora_alpha=8, target_modules=["q_proj", "k_proj", "v_proj", "o_proj"], lora_dropout=0.05, bias="none", task_type="CAUSAL_LM" ) model = get_peft_model(model, config) ``` ## HQQ quantization The models that is quantized using Half-Quadratic Quantization of Large Machine Learning Models ([HQQ](https://mobiusml.github.io/hqq_blog/)) support LoRA adapter tuning. To tune the quantized model, you'll need to install the `hqq` library with: `pip install hqq`. ```python from hqq.engine.hf import HQQModelForCausalLM quantized_model = HQQModelForCausalLM.from_quantized(save_dir_or_hfhub, device='cuda') peft_config = LoraConfig(...) quantized_model = get_peft_model(quantized_model, peft_config) ``` Or using transformers version that is compatible with HQQ (e.g. by installing it from latest pypi or from source). ```python from transformers import HqqConfig, AutoModelForCausalLM quant_config = HqqConfig(nbits=4, group_size=64) quantized_model = AutoModelForCausalLM.from_pretrained(save_dir_or_hfhub, device_map=device_map, quantization_config=quant_config) peft_config = LoraConfig(...) quantized_model = get_peft_model(quantized_model, peft_config) ``` ## Next steps If you're interested in learning more about quantization, the following may be helpful: * Learn more about details about QLoRA and check out some benchmarks on its impact in the [Making LLMs even more accessible with bitsandbytes, 4-bit quantization and QLoRA](https://huggingface.co/blog/4bit-transformers-bitsandbytes) blog post. * Read more about different quantization schemes in the Transformers [Quantization](https://hf.co/docs/transformers/main/quantization) guide.
peft/docs/source/developer_guides/quantization.md/0
{ "file_path": "peft/docs/source/developer_guides/quantization.md", "repo_id": "peft", "token_count": 2855 }
180
<!--Copyright 2024 The HuggingFace Team. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ⚠️ 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. --> # LoRA methods A popular way to efficiently train large models is to insert (typically in the attention blocks) smaller trainable matrices that are a low-rank decomposition of the delta weight matrix to be learnt during finetuning. The pretrained model's original weight matrix is frozen and only the smaller matrices are updated during training. This reduces the number of trainable parameters, reducing memory usage and training time which can be very expensive for large models. There are several different ways to express the weight matrix as a low-rank decomposition, but [Low-Rank Adaptation (LoRA)](../conceptual_guides/adapter#low-rank-adaptation-lora) is the most common method. The PEFT library supports several other LoRA variants, such as [Low-Rank Hadamard Product (LoHa)](../conceptual_guides/adapter#low-rank-hadamard-product-loha), [Low-Rank Kronecker Product (LoKr)](../conceptual_guides/adapter#low-rank-kronecker-product-lokr), and [Adaptive Low-Rank Adaptation (AdaLoRA)](../conceptual_guides/adapter#adaptive-low-rank-adaptation-adalora). You can learn more about how these methods work conceptually in the [Adapters](../conceptual_guides/adapter) guide. If you're interested in applying these methods to other tasks and use cases like semantic segmentation, token classification, take a look at our [notebook collection](https://huggingface.co/collections/PEFT/notebooks-6573b28b33e5a4bf5b157fc1)! Additionally, PEFT supports the [X-LoRA](../conceptual_guides/adapter#mixture-of-lora-experts-x-lora) Mixture of LoRA Experts method. This guide will show you how to quickly train an image classification model - with a low-rank decomposition method - to identify the class of food shown in an image. <Tip> Some familiarity with the general process of training an image classification model would be really helpful and allow you to focus on the low-rank decomposition methods. If you're new, we recommend taking a look at the [Image classification](https://huggingface.co/docs/transformers/tasks/image_classification) guide first from the Transformers documentation. When you're ready, come back and see how easy it is to drop PEFT in to your training! </Tip> Before you begin, make sure you have all the necessary libraries installed. ```bash pip install -q peft transformers datasets ``` ## Dataset In this guide, you'll use the [Food-101](https://huggingface.co/datasets/food101) dataset which contains images of 101 food classes (take a look at the [dataset viewer](https://huggingface.co/datasets/food101/viewer/default/train) to get a better idea of what the dataset looks like). Load the dataset with the [`~datasets.load_dataset`] function. ```py from datasets import load_dataset ds = load_dataset("food101") ``` Each food class is labeled with an integer, so to make it easier to understand what these integers represent, you'll create a `label2id` and `id2label` dictionary to map the integer to its class label. ```py labels = ds["train"].features["label"].names label2id, id2label = dict(), dict() for i, label in enumerate(labels): label2id[label] = i id2label[i] = label id2label[2] "baklava" ``` Load an image processor to properly resize and normalize the pixel values of the training and evaluation images. ```py from transformers import AutoImageProcessor image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k") ``` You can also use the image processor to prepare some transformation functions for data augmentation and pixel scaling. ```py from torchvision.transforms import ( CenterCrop, Compose, Normalize, RandomHorizontalFlip, RandomResizedCrop, Resize, ToTensor, ) normalize = Normalize(mean=image_processor.image_mean, std=image_processor.image_std) train_transforms = Compose( [ RandomResizedCrop(image_processor.size["height"]), RandomHorizontalFlip(), ToTensor(), normalize, ] ) val_transforms = Compose( [ Resize(image_processor.size["height"]), CenterCrop(image_processor.size["height"]), ToTensor(), normalize, ] ) def preprocess_train(example_batch): example_batch["pixel_values"] = [train_transforms(image.convert("RGB")) for image in example_batch["image"]] return example_batch def preprocess_val(example_batch): example_batch["pixel_values"] = [val_transforms(image.convert("RGB")) for image in example_batch["image"]] return example_batch ``` Define the training and validation datasets, and use the [`~datasets.Dataset.set_transform`] function to apply the transformations on-the-fly. ```py train_ds = ds["train"] val_ds = ds["validation"] train_ds.set_transform(preprocess_train) val_ds.set_transform(preprocess_val) ``` Finally, you'll need a data collator to create a batch of training and evaluation data and convert the labels to `torch.tensor` objects. ```py import torch def collate_fn(examples): pixel_values = torch.stack([example["pixel_values"] for example in examples]) labels = torch.tensor([example["label"] for example in examples]) return {"pixel_values": pixel_values, "labels": labels} ``` ## Model Now let's load a pretrained model to use as the base model. This guide uses the [google/vit-base-patch16-224-in21k](https://huggingface.co/google/vit-base-patch16-224-in21k) model, but you can use any image classification model you want. Pass the `label2id` and `id2label` dictionaries to the model so it knows how to map the integer labels to their class labels, and you can optionally pass the `ignore_mismatched_sizes=True` parameter if you're finetuning a checkpoint that has already been finetuned. ```py from transformers import AutoModelForImageClassification, TrainingArguments, Trainer model = AutoModelForImageClassification.from_pretrained( "google/vit-base-patch16-224-in21k", label2id=label2id, id2label=id2label, ignore_mismatched_sizes=True, ) ``` ### PEFT configuration and model Every PEFT method requires a configuration that holds all the parameters specifying how the PEFT method should be applied. Once the configuration is setup, pass it to the [`~peft.get_peft_model`] function along with the base model to create a trainable [`PeftModel`]. <Tip> Call the [`~PeftModel.print_trainable_parameters`] method to compare the number of parameters of [`PeftModel`] versus the number of parameters in the base model! </Tip> <hfoptions id="loras"> <hfoption id="LoRA"> [LoRA](../conceptual_guides/adapter#low-rank-adaptation-lora) decomposes the weight update matrix into *two* smaller matrices. The size of these low-rank matrices is determined by its *rank* or `r`. A higher rank means the model has more parameters to train, but it also means the model has more learning capacity. You'll also want to specify the `target_modules` which determine where the smaller matrices are inserted. For this guide, you'll target the *query* and *value* matrices of the attention blocks. Other important parameters to set are `lora_alpha` (scaling factor), `bias` (whether `none`, `all` or only the LoRA bias parameters should be trained), and `modules_to_save` (the modules apart from the LoRA layers to be trained and saved). All of these parameters - and more - are found in the [`LoraConfig`]. ```py from peft import LoraConfig, get_peft_model config = LoraConfig( r=16, lora_alpha=16, target_modules=["query", "value"], lora_dropout=0.1, bias="none", modules_to_save=["classifier"], ) model = get_peft_model(model, config) model.print_trainable_parameters() "trainable params: 667,493 || all params: 86,543,818 || trainable%: 0.7712775047664294" ``` </hfoption> <hfoption id="LoHa"> [LoHa](../conceptual_guides/adapter#low-rank-hadamard-product-loha) decomposes the weight update matrix into *four* smaller matrices and each pair of smaller matrices is combined with the Hadamard product. This allows the weight update matrix to keep the same number of trainable parameters when compared to LoRA, but with a higher rank (`r^2` for LoHA when compared to `2*r` for LoRA). The size of the smaller matrices is determined by its *rank* or `r`. You'll also want to specify the `target_modules` which determines where the smaller matrices are inserted. For this guide, you'll target the *query* and *value* matrices of the attention blocks. Other important parameters to set are `alpha` (scaling factor), and `modules_to_save` (the modules apart from the LoHa layers to be trained and saved). All of these parameters - and more - are found in the [`LoHaConfig`]. ```py from peft import LoHaConfig, get_peft_model config = LoHaConfig( r=16, alpha=16, target_modules=["query", "value"], module_dropout=0.1, modules_to_save=["classifier"], ) model = get_peft_model(model, config) model.print_trainable_parameters() "trainable params: 1,257,317 || all params: 87,133,642 || trainable%: 1.4429753779831676" ``` </hfoption> <hfoption id="LoKr"> [LoKr](../conceptual_guides/adapter#low-rank-kronecker-product-lokr) expresses the weight update matrix as a decomposition of a Kronecker product, creating a block matrix that is able to preserve the rank of the original weight matrix. The size of the smaller matrices are determined by its *rank* or `r`. You'll also want to specify the `target_modules` which determines where the smaller matrices are inserted. For this guide, you'll target the *query* and *value* matrices of the attention blocks. Other important parameters to set are `alpha` (scaling factor), and `modules_to_save` (the modules apart from the LoKr layers to be trained and saved). All of these parameters - and more - are found in the [`LoKrConfig`]. ```py from peft import LoKrConfig, get_peft_model config = LoKrConfig( r=16, alpha=16, target_modules=["query", "value"], module_dropout=0.1, modules_to_save=["classifier"], ) model = get_peft_model(model, config) model.print_trainable_parameters() "trainable params: 116,069 || all params: 87,172,042 || trainable%: 0.13314934162033282" ``` </hfoption> <hfoption id="AdaLoRA"> [AdaLoRA](../conceptual_guides/adapter#adaptive-low-rank-adaptation-adalora) efficiently manages the LoRA parameter budget by assigning important weight matrices more parameters and pruning less important ones. In contrast, LoRA evenly distributes parameters across all modules. You can control the average desired *rank* or `r` of the matrices, and which modules to apply AdaLoRA to with `target_modules`. Other important parameters to set are `lora_alpha` (scaling factor), and `modules_to_save` (the modules apart from the AdaLoRA layers to be trained and saved). All of these parameters - and more - are found in the [`AdaLoraConfig`]. ```py from peft import AdaLoraConfig, get_peft_model config = AdaLoraConfig( r=8, init_r=12, tinit=200, tfinal=1000, deltaT=10, target_modules=["query", "value"], modules_to_save=["classifier"], ) model = get_peft_model(model, config) model.print_trainable_parameters() "trainable params: 520,325 || all params: 87,614,722 || trainable%: 0.5938785036606062" ``` </hfoption> </hfoptions> ### Training For training, let's use the [`~transformers.Trainer`] class from Transformers. The [`Trainer`] contains a PyTorch training loop, and when you're ready, call [`~transformers.Trainer.train`] to start training. To customize the training run, configure the training hyperparameters in the [`~transformers.TrainingArguments`] class. With LoRA-like methods, you can afford to use a higher batch size and learning rate. > [!WARNING] > AdaLoRA has an [`~AdaLoraModel.update_and_allocate`] method that should be called at each training step to update the parameter budget and mask, otherwise the adaptation step is not performed. This requires writing a custom training loop or subclassing the [`~transformers.Trainer`] to incorporate this method. As an example, take a look at this [custom training loop](https://github.com/huggingface/peft/blob/912ad41e96e03652cabf47522cd876076f7a0c4f/examples/conditional_generation/peft_adalora_seq2seq.py#L120). ```py from transformers import TrainingArguments, Trainer account = "stevhliu" peft_model_id = f"{account}/google/vit-base-patch16-224-in21k-lora" batch_size = 128 args = TrainingArguments( peft_model_id, remove_unused_columns=False, evaluation_strategy="epoch", save_strategy="epoch", learning_rate=5e-3, per_device_train_batch_size=batch_size, gradient_accumulation_steps=4, per_device_eval_batch_size=batch_size, fp16=True, num_train_epochs=5, logging_steps=10, load_best_model_at_end=True, label_names=["labels"], ) ``` Begin training with [`~transformers.Trainer.train`]. ```py trainer = Trainer( model, args, train_dataset=train_ds, eval_dataset=val_ds, tokenizer=image_processor, data_collator=collate_fn, ) trainer.train() ``` ## Share your model Once training is complete, you can upload your model to the Hub with the [`~transformers.PreTrainedModel.push_to_hub`] method. You’ll need to login to your Hugging Face account first and enter your token when prompted. ```py from huggingface_hub import notebook_login notebook_login() ``` Call [`~transformers.PreTrainedModel.push_to_hub`] to save your model to your repositoy. ```py model.push_to_hub(peft_model_id) ``` ## Inference Let's load the model from the Hub and test it out on a food image. ```py from peft import PeftConfig, PeftModel from transformers import AutoImageProcessor from PIL import Image import requests config = PeftConfig.from_pretrained("stevhliu/vit-base-patch16-224-in21k-lora") model = AutoModelForImageClassification.from_pretrained( config.base_model_name_or_path, label2id=label2id, id2label=id2label, ignore_mismatched_sizes=True, ) model = PeftModel.from_pretrained(model, "stevhliu/vit-base-patch16-224-in21k-lora") url = "https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/beignets.jpeg" image = Image.open(requests.get(url, stream=True).raw) image ``` <div class="flex justify-center"> <img src="https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/beignets.jpeg"> </div> Convert the image to RGB and return the underlying PyTorch tensors. ```py encoding = image_processor(image.convert("RGB"), return_tensors="pt") ``` Now run the model and return the predicted class! ```py with torch.no_grad(): outputs = model(**encoding) logits = outputs.logits predicted_class_idx = logits.argmax(-1).item() print("Predicted class:", model.config.id2label[predicted_class_idx]) "Predicted class: beignets" ```
peft/docs/source/task_guides/lora_based_methods.md/0
{ "file_path": "peft/docs/source/task_guides/lora_based_methods.md", "repo_id": "peft", "token_count": 4895 }
181
# 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. from dataclasses import dataclass from typing import Dict, List, Optional, Tuple, Union import torch from diffusers.configuration_utils import ConfigMixin, register_to_config from diffusers.models.attention_processor import AttentionProcessor, AttnProcessor from diffusers.models.modeling_utils import ModelMixin from diffusers.models.unet_2d_blocks import ( CrossAttnDownBlock2D, DownBlock2D, ) from diffusers.utils import BaseOutput, logging from torch import nn from torch.nn import functional as F logger = logging.get_logger(__name__) # pylint: disable=invalid-name @dataclass class ControlNetOutput(BaseOutput): down_block_res_samples: Tuple[torch.Tensor] mid_block_res_sample: torch.Tensor class ControlNetConditioningEmbedding(nn.Module): """ Quoting from https://arxiv.org/abs/2302.05543: "Stable Diffusion uses a pre-processing method similar to VQ-GAN [11] to convert the entire dataset of 512 × 512 images into smaller 64 × 64 “latent images” for stabilized training. This requires ControlNets to convert image-based conditions to 64 × 64 feature space to match the convolution size. We use a tiny network E(·) of four convolution layers with 4 × 4 kernels and 2 × 2 strides (activated by ReLU, channels are 16, 32, 64, 128, initialized with Gaussian weights, trained jointly with the full model) to encode image-space conditions ... into feature maps ..." """ def __init__( self, conditioning_embedding_channels: int, conditioning_channels: int = 3, block_out_channels: Tuple[int] = (16, 32, 96, 256), ): super().__init__() self.conv_in = nn.Conv2d(conditioning_channels, block_out_channels[0], kernel_size=3, padding=1) self.blocks = nn.ModuleList([]) for i in range(len(block_out_channels) - 1): channel_in = block_out_channels[i] channel_out = block_out_channels[i + 1] self.blocks.append(nn.Conv2d(channel_in, channel_in, kernel_size=3, padding=1)) self.blocks.append(nn.Conv2d(channel_in, channel_out, kernel_size=3, padding=1, stride=2)) self.conv_out = zero_module( nn.Conv2d(block_out_channels[-1], conditioning_embedding_channels, kernel_size=3, padding=1) ) def forward(self, conditioning): embedding = self.conv_in(conditioning) embedding = F.silu(embedding) for block in self.blocks: embedding = block(embedding) embedding = F.silu(embedding) embedding = self.conv_out(embedding) return embedding class ControlNetModel(ModelMixin, ConfigMixin): _supports_gradient_checkpointing = True @register_to_config def __init__( self, in_channels: int = 4, out_channels: int = 320, controlnet_conditioning_channel_order: str = "rgb", conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256), ): super().__init__() # for control image self.controlnet_cond_embedding = ControlNetConditioningEmbedding( conditioning_embedding_channels=out_channels, block_out_channels=conditioning_embedding_out_channels, ) @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def attn_processors(self) -> Dict[str, AttentionProcessor]: r""" Returns: `dict` of attention processors: A dictionary containing all attention processors used in the model with indexed by its weight name. """ # set recursively processors = {} def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]): if hasattr(module, "set_processor"): processors[f"{name}.processor"] = module.processor for sub_name, child in module.named_children(): fn_recursive_add_processors(f"{name}.{sub_name}", child, processors) return processors for name, module in self.named_children(): fn_recursive_add_processors(name, module, processors) return processors # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attn_processor def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]): r""" Parameters: `processor (`dict` of `AttentionProcessor` or `AttentionProcessor`): The instantiated processor class or a dictionary of processor classes that will be set as the processor of **all** `Attention` layers. In case `processor` is a dict, the key needs to define the path to the corresponding cross attention processor. This is strongly recommended when setting trainable attention processors.: """ count = len(self.attn_processors.keys()) if isinstance(processor, dict) and len(processor) != count: raise ValueError( f"A dict of processors was passed, but the number of processors {len(processor)} does not match the" f" number of attention layers: {count}. Please make sure to pass {count} processor classes." ) def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor): if hasattr(module, "set_processor"): if not isinstance(processor, dict): module.set_processor(processor) else: module.set_processor(processor.pop(f"{name}.processor")) for sub_name, child in module.named_children(): fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor) for name, module in self.named_children(): fn_recursive_attn_processor(name, module, processor) # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor def set_default_attn_processor(self): """ Disables custom attention processors and sets the default attention implementation. """ self.set_attn_processor(AttnProcessor()) # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attention_slice def set_attention_slice(self, slice_size): r""" Enable sliced attention computation. When this option is enabled, the attention module will split the input tensor in slices, to compute attention in several steps. This is useful to save some memory in exchange for a small speed decrease. Args: slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`): When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If `"max"`, maximum amount of memory will be saved by running only one slice at a time. If a number is provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim` must be a multiple of `slice_size`. """ sliceable_head_dims = [] def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module): if hasattr(module, "set_attention_slice"): sliceable_head_dims.append(module.sliceable_head_dim) for child in module.children(): fn_recursive_retrieve_sliceable_dims(child) # retrieve number of attention layers for module in self.children(): fn_recursive_retrieve_sliceable_dims(module) num_sliceable_layers = len(sliceable_head_dims) if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory slice_size = [dim // 2 for dim in sliceable_head_dims] elif slice_size == "max": # make smallest slice possible slice_size = num_sliceable_layers * [1] slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size if len(slice_size) != len(sliceable_head_dims): raise ValueError( f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different" f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}." ) for i in range(len(slice_size)): size = slice_size[i] dim = sliceable_head_dims[i] if size is not None and size > dim: raise ValueError(f"size {size} has to be smaller or equal to {dim}.") # Recursively walk through all the children. # Any children which exposes the set_attention_slice method # gets the message def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]): if hasattr(module, "set_attention_slice"): module.set_attention_slice(slice_size.pop()) for child in module.children(): fn_recursive_set_attention_slice(child, slice_size) reversed_slice_size = list(reversed(slice_size)) for module in self.children(): fn_recursive_set_attention_slice(module, reversed_slice_size) def _set_gradient_checkpointing(self, module, value=False): if isinstance(module, (CrossAttnDownBlock2D, DownBlock2D)): module.gradient_checkpointing = value def forward( self, controlnet_cond: torch.FloatTensor, ) -> Union[ControlNetOutput, Tuple]: # check channel order channel_order = self.config.controlnet_conditioning_channel_order if channel_order == "rgb": # in rgb order by default ... elif channel_order == "bgr": controlnet_cond = torch.flip(controlnet_cond, dims=[1]) else: raise ValueError(f"unknown `controlnet_conditioning_channel_order`: {channel_order}") # 2. pre-process controlnet_cond = self.controlnet_cond_embedding(controlnet_cond) return controlnet_cond def zero_module(module): for p in module.parameters(): nn.init.zeros_(p) return module
peft/examples/boft_controlnet/utils/light_controlnet.py/0
{ "file_path": "peft/examples/boft_controlnet/utils/light_controlnet.py", "repo_id": "peft", "token_count": 4318 }
182
<jupyter_start><jupyter_code>from transformers import AutoModelForCausalLM from peft import get_peft_config, get_peft_model, LNTuningConfig, TaskType, PeftType import torch from datasets import load_dataset import os from transformers import AutoTokenizer from torch.utils.data import DataLoader from transformers import default_data_collator, get_linear_schedule_with_warmup from tqdm import tqdm from datasets import load_dataset # Hyper-parameters device = "cuda" model_name_or_path = "bigscience/bloomz-560m" tokenizer_name_or_path = "bigscience/bloomz-560m" peft_config = LNTuningConfig( task_type=TaskType.CAUSAL_LM, ) dataset_name = "twitter_complaints" checkpoint_name = f"{dataset_name}_{model_name_or_path}_{peft_config.peft_type}_{peft_config.task_type}_v1.pt".replace( "/", "_" ) text_column = "Tweet text" label_column = "text_label" max_length = 64 lr = 5e-2 num_epochs = 50 batch_size = 8<jupyter_output><empty_output><jupyter_text>Load and Process Dataset for LM Training<jupyter_code>from datasets import load_dataset dataset = load_dataset("ought/raft", dataset_name) classes = [k.replace("_", " ") for k in dataset["train"].features["Label"].names] print(classes) dataset = dataset.map( lambda x: {"text_label": [classes[label] for label in x["Label"]]}, batched=True, num_proc=1, ) print(dataset) dataset["train"][0] # data preprocessing tokenizer = AutoTokenizer.from_pretrained(model_name_or_path) if tokenizer.pad_token_id is None: tokenizer.pad_token_id = tokenizer.eos_token_id target_max_length = max([len(tokenizer(class_label)["input_ids"]) for class_label in classes]) print(target_max_length) def preprocess_function(examples): batch_size = len(examples[text_column]) inputs = [f"{text_column} : {x} Label : " for x in examples[text_column]] targets = [str(x) for x in examples[label_column]] model_inputs = tokenizer(inputs) labels = tokenizer(targets, add_special_tokens=False) # don't add bos token because we concatenate with inputs for i in range(batch_size): sample_input_ids = model_inputs["input_ids"][i] label_input_ids = labels["input_ids"][i] + [tokenizer.eos_token_id] # print(i, sample_input_ids, label_input_ids) model_inputs["input_ids"][i] = sample_input_ids + label_input_ids labels["input_ids"][i] = [-100] * len(sample_input_ids) + label_input_ids model_inputs["attention_mask"][i] = [1] * len(model_inputs["input_ids"][i]) # print(model_inputs) for i in range(batch_size): sample_input_ids = model_inputs["input_ids"][i] label_input_ids = labels["input_ids"][i] model_inputs["input_ids"][i] = [tokenizer.pad_token_id] * ( max_length - len(sample_input_ids) ) + sample_input_ids model_inputs["attention_mask"][i] = [0] * (max_length - len(sample_input_ids)) + model_inputs[ "attention_mask" ][i] labels["input_ids"][i] = [-100] * (max_length - len(sample_input_ids)) + label_input_ids model_inputs["input_ids"][i] = torch.tensor(model_inputs["input_ids"][i][:max_length]) model_inputs["attention_mask"][i] = torch.tensor(model_inputs["attention_mask"][i][:max_length]) labels["input_ids"][i] = torch.tensor(labels["input_ids"][i][:max_length]) model_inputs["labels"] = labels["input_ids"] return model_inputs processed_datasets = dataset.map( preprocess_function, batched=True, num_proc=1, remove_columns=dataset["train"].column_names, load_from_cache_file=False, desc="Running tokenizer on dataset", ) train_dataset = processed_datasets["train"] eval_dataset = processed_datasets["train"] train_dataloader = DataLoader( train_dataset, shuffle=True, collate_fn=default_data_collator, batch_size=batch_size, pin_memory=True ) eval_dataloader = DataLoader(eval_dataset, collate_fn=default_data_collator, batch_size=batch_size, pin_memory=True) def test_preprocess_function(examples): batch_size = len(examples[text_column]) inputs = [f"{text_column} : {x} Label : " for x in examples[text_column]] model_inputs = tokenizer(inputs) # print(model_inputs) for i in range(batch_size): sample_input_ids = model_inputs["input_ids"][i] model_inputs["input_ids"][i] = [tokenizer.pad_token_id] * ( max_length - len(sample_input_ids) ) + sample_input_ids model_inputs["attention_mask"][i] = [0] * (max_length - len(sample_input_ids)) + model_inputs[ "attention_mask" ][i] model_inputs["input_ids"][i] = torch.tensor(model_inputs["input_ids"][i][:max_length]) model_inputs["attention_mask"][i] = torch.tensor(model_inputs["attention_mask"][i][:max_length]) return model_inputs test_dataset = dataset["test"].map( test_preprocess_function, batched=True, num_proc=1, remove_columns=dataset["train"].column_names, load_from_cache_file=False, desc="Running tokenizer on dataset", ) test_dataloader = DataLoader(test_dataset, collate_fn=default_data_collator, batch_size=batch_size, pin_memory=True) next(iter(test_dataloader)) # show dataset size len(test_dataloader)<jupyter_output><empty_output><jupyter_text>Train the LM with LNTuning1. Create the base LM.2. Only activate the LayerNorm layers in the LM for training.3. Train the LM on the training dataset.<jupyter_code># 1. creating the base LM model = AutoModelForCausalLM.from_pretrained(model_name_or_path) # 2. Only activate the LayerNorm layers in the Attention blocks in the LM for training model = get_peft_model(model, peft_config) model.print_trainable_parameters() # setup the optimizer and lr scheduler optimizer = torch.optim.AdamW(model.parameters(), lr=lr) lr_scheduler = get_linear_schedule_with_warmup( optimizer=optimizer, num_warmup_steps=0, num_training_steps=(len(train_dataloader) * num_epochs), ) # 3. train the LM on the training dataset model = model.to(device) for epoch in range(num_epochs): model.train() total_loss = 0 for step, batch in enumerate(tqdm(train_dataloader)): batch = {k: v.to(device) for k, v in batch.items()} # print(batch) # print(batch["input_ids"].shape) outputs = model(**batch) loss = outputs.loss total_loss += loss.detach().float() loss.backward() optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() eval_loss = 0 eval_preds = [] for step, batch in enumerate(tqdm(eval_dataloader)): batch = {k: v.to(device) for k, v in batch.items()} with torch.no_grad(): outputs = model(**batch) loss = outputs.loss eval_loss += loss.detach().float() eval_preds.extend( tokenizer.batch_decode(torch.argmax(outputs.logits, -1).detach().cpu().numpy(), skip_special_tokens=True) ) eval_epoch_loss = eval_loss / len(eval_dataloader) eval_ppl = torch.exp(eval_epoch_loss) train_epoch_loss = total_loss / len(train_dataloader) train_ppl = torch.exp(train_epoch_loss) print(f"{epoch=}: {train_ppl=} {train_epoch_loss=} {eval_ppl=} {eval_epoch_loss=}")<jupyter_output>100%|██████████| 7/7 [00:00<00:00, 7.09it/s] 100%|██████████| 7/7 [00:00<00:00, 23.05it/s]<jupyter_text>Test the LM<jupyter_code>model.eval() i = 33 inputs = tokenizer(f'{text_column} : {dataset["test"][i]["Tweet text"]} Label : ', return_tensors="pt") print(dataset["test"][i]["Tweet text"]) print(inputs) with torch.no_grad(): inputs = {k: v.to(device) for k, v in inputs.items()} outputs = model.generate( input_ids=inputs["input_ids"], attention_mask=inputs["attention_mask"], max_new_tokens=10, eos_token_id=3 ) print(outputs) print(tokenizer.batch_decode(outputs.detach().cpu().numpy(), skip_special_tokens=True))<jupyter_output>@TommyHilfiger Dramatic shopping exp. ordered 6 jeans same size (30/32) 2 fits / 2 too large / 2 too slim : same brand &gt; different sizing {'input_ids': tensor([[227985, 5484, 915, 2566, 226154, 126015, 5385, 259, 239364, 3396, 70823, 5853, 17, 57247, 1231, 191040, 5025, 7869, 375, 2324, 149349, 12, 415, 122321, 897, 415, 10136, 10021, 897, 415, 10136, 6497, 381, 915, 5025, 51950, 66869, 5955, 272, 20311, 77658, 915, 210]]), 'attention_mask': tensor([[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]])} tensor([[227985, 5484, 915, 2566, 226154, 126015, 5385, 259, 239364, 3396, 70823, 5853, 17, 57247, 1231, 191040, 5025, 7869, 375, 2324, 149349, 12, 415, 122321, 897, 415, 10136, 10021, 897, 415, 10136, [...]<jupyter_text>Save the trainable LM weights (LayerNorm layers)You can push model to hub or save model locally. - Option1: Push the model to Hugging Face Hub: ```python model.push_to_hub( f"{dataset_name}_{model_name_or_path}_{peft_config.peft_type}_{peft_config.task_type}".replace("/", "_"), token = "hf_..." ) ``` token (`bool` or `str`, *optional*): `token` is to be used for HTTP Bearer authorization when accessing remote files. If `True`, will use the token generated when running `huggingface-cli login` (stored in `~/.huggingface`). Will default to `True` if `repo_url` is not specified. Or you can get your token from https://huggingface.co/settings/token ```- Option2: Save model locally: ```python peft_model_id = f"{dataset_name}_{model_name_or_path}_{peft_config.peft_type}_{peft_config.task_type}".replace("/", "_") model.save_pretrained(peft_model_id) ```<jupyter_code># saving model peft_model_id = f"{dataset_name}_{model_name_or_path}_{peft_config.peft_type}_{peft_config.task_type}".replace( "/", "_" ) model.save_pretrained(peft_model_id)<jupyter_output><empty_output><jupyter_text>Test the LM using LNTuning loaded from saved weights1. load the LNTuning configuration2. load the base LM3. merge the LNTuning weights into the base LM using the PEFT config<jupyter_code>from peft import PeftModel, PeftConfig # load the LNTuning config config = PeftConfig.from_pretrained(peft_model_id) # load the base LM model = AutoModelForCausalLM.from_pretrained(config.base_model_name_or_path) # merge LNTuning weights into the base LM model = PeftModel.from_pretrained(model, peft_model_id) model.to(device) model.eval() i = 4 inputs = tokenizer(f'{text_column} : {dataset["test"][i]["Tweet text"]} Label : ', return_tensors="pt") print(dataset["test"][i]["Tweet text"]) print(inputs) with torch.no_grad(): inputs = {k: v.to(device) for k, v in inputs.items()} outputs = model.generate( input_ids=inputs["input_ids"], attention_mask=inputs["attention_mask"], max_new_tokens=10, eos_token_id=3 ) print(outputs) print(tokenizer.batch_decode(outputs.detach().cpu().numpy(), skip_special_tokens=True))<jupyter_output>@greateranglia Ok thanks... {'input_ids': tensor([[227985, 5484, 915, 2566, 14173, 2960, 29906, 387, 20706, 49337, 1369, 77658, 915, 210]]), 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])} tensor([[227985, 5484, 915, 2566, 14173, 2960, 29906, 387, 20706, 49337, 1369, 77658, 915, 210, 1936, 106863, 2, 1936, 106863, 2, 1936, 106863, 2, 1936]], device='cuda:0') ['Tweet text : @greateranglia Ok thanks... Label : no complaintno complaintno complaintno']
peft/examples/causal_language_modeling/peft_ln_tuning_clm.ipynb/0
{ "file_path": "peft/examples/causal_language_modeling/peft_ln_tuning_clm.ipynb", "repo_id": "peft", "token_count": 5005 }
183
# LoftQ: LoRA-fine-tuning-aware Quantization ## Introduction LoftQ finds quantized LoRA initialization: quantized backbone Q and LoRA adapters A and B, given a pre-trained weight W. ## Quick Start Steps: 1. Apply LoftQ to a full-precision pre-trained weight and save. 2. Load LoftQ initialization and train. For step 1, we have provided off-the-shelf LoftQ initializations (see [supported model list](#appendix-off-the-shelf-model-table)) in [Huggingface Hub LoftQ](https://huggingface.co/LoftQ). If you want to do it yourself, jump to [LoftQ DIY](#loftq-diy). For step 2, below is an example of loading 4bit Mistral-7B with 64rank LoRA adapters from Huggingface Hub. ```python import torch from transformers import AutoModelForCausalLM, BitsAndBytesConfig from peft import PeftModel MODEL_ID = "LoftQ/Mistral-7B-v0.1-4bit-64rank" base_model = AutoModelForCausalLM.from_pretrained( MODEL_ID, torch_dtype=torch.bfloat16, # you may change it with different models quantization_config=BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16, # bfloat16 is recommended bnb_4bit_use_double_quant=False, bnb_4bit_quant_type='nf4', ), ) peft_model = PeftModel.from_pretrained( base_model, MODEL_ID, subfolder="loftq_init", is_trainable=True, ) # Do training with peft_model ... ``` ## LoftQ DIY ### Apply LoftQ and save We provide [quantize_save_load.py](quantize_save_load.py) as an example to apply LoftQ with different bits(`--bits`), ranks(`--rank`), and alternating steps (`--iter`, a hyper-parameter in LoftQ, see Algorithm 1 in [LoftQ paper](https://arxiv.org/abs/2310.08659)). Currently, this example supports `llama-2`, `falcon`, `mistral`, `bart`, `t5`, `deberta`, `bert`, `roberta`. Below is an example of obtaining 4bit LLAMA-2-7b with 16-rank LoRA adapters by 5 alternating steps. ```sh SAVE_DIR="model_zoo/loftq/" python quantize_save_load.py \ --model_name_or_path meta-llama/Llama-2-7b-hf \ # high-precision model id in HF --token HF_TOKEN \ # your HF token if the model is private, e.g., llama-2 --bits 4 \ --iter 5 \ --rank 16 \ --save_dir $SAVE_DIR ``` The above commands end up with creating the model directory under `$SAVE_DIR`. Specifically, the model directory is named as `MODEL_DIR = SAVE_DIR + f"{args.model_name_or_path.split('/')[-1]}-{args.bits}bits-{args.rank}rank"` In this example, `MODEL_DIR="model_zoo/loftq/Llama-2-7b-hf-4bit-16rank"`, where the backbone is stored in `$MODEL_DIR` and the LoRA adapters are at the sub-folder `$MODEL_DIR/loftq_init`. ### Load and train Similar to loading from Huggingface Hub, we only need to change the `MODEL_ID` to the `MODEL_DIR`. ```python import torch from transformers import AutoModelForCausalLM, BitsAndBytesConfig from peft import PeftModel MODEL_DIR = "model_zoo/loftq/Llama-2-7b-hf-4bit-16rank" base_model = AutoModelForCausalLM.from_pretrained( MODEL_DIR, torch_dtype=torch.bfloat16, quantization_config=BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_use_double_quant=False, bnb_4bit_quant_type='nf4', ), ) peft_model = PeftModel.from_pretrained( base_model, MODEL_DIR, subfolder="loftq_init", is_trainable=True, ) # Do training with peft_model ... ``` ## LoftQ Fine-tuning We also provide an example to fine-tune LoftQ on GSM8K. We load the quantized backbone and LoRA adapters from the [LoftQ Huggingface hub](https://huggingface.co/LoftQ). ```sh python train_gsm8k_llama.py \ --model_name_or_path LoftQ/Llama-2-13b-hf-4bit-64rank \ --output_dir exp_results/gsm8k/llama-2-13b/bit4-rank64/lr1e-4 \ --learning_rate 1e-4 \ --weight_decay 0.1 \ --lr_scheduler_type cosine \ --num_warmup_steps 100 \ --seed 202 \ --dataset_name gsm8k \ --dataset_config main \ --pad_to_max_length \ --max_source_length 128 \ --max_target_length 256 \ --num_train_epochs 5 \ --per_device_train_batch_size 4 \ --per_device_eval_batch_size 4 \ --gradient_accumulation_steps 4 \ --with_tracking \ --report_to tensorboard ``` ## Appendix: Off-the-shelf Model List | Model Name | Bits | Ranks | | ----------- | ---- | ----- | | LLAMA-2-7b | 4 | 64 | | LLAMA-2-13b | 4 | 64 | | LLAMA-2-70b | 4 | 64 | | Mistral | 4 | 64 | | Mistral | 4 | 32 | | BART-large | 4 | 8 | | BART-large | 4 | 16 | | BART-large | 4 | 32 | | BART-large | 2 | 8 | ## In-place application of LoftQ initialization PEFT provides a convenience function `replace_lora_weights_loftq` to apply LoftQ initialization in-place to the quantized model. Check out [this notebook](https://github.com/huggingface/peft/blob/main/examples/loftq_finetuning/LoftQ_weight_replacement.ipynb) for an example.
peft/examples/loftq_finetuning/README.md/0
{ "file_path": "peft/examples/loftq_finetuning/README.md", "repo_id": "peft", "token_count": 1978 }
184
# OLoRA: Orthonormal Low Rank Adaptation of Large Language Models ## Introduction [OLoRA](https://arxiv.org/abs/2406.01775) is a novel approach that leverages orthonormal low rank adaptation through QR decomposition. Unlike the default LoRA implementation, OLoRA decomposes original weights into their $\mathbf{Q}$ and $\mathbf{R}$ parts, and then uses the first `rank` rows of $\mathbf{R}$ and the first `rank` columns of $\mathbf{Q}$ to initialize $\mathbf{A}$ and $\mathbf{B}$, respectively. This results in significantly faster convergence, more stable training, and superior performance. ## Quick start ```python import torch from peft import LoraConfig, get_peft_model from transformers import AutoTokenizer, AutoModelForCausalLM from trl import SFTTrainer from datasets import load_dataset model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m", torch_dtype=torch.bfloat16, device_map="auto") tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m") dataset = load_dataset("imdb", split="train[:1%]") lora_config = LoraConfig( init_lora_weights="olora" ) peft_model = get_peft_model(model, lora_config) trainer = SFTTrainer( model=peft_model, train_dataset=dataset, dataset_text_field="text", max_seq_length=512, tokenizer=tokenizer, ) trainer.train() peft_model.save_pretrained("olora-opt-350m") ``` There is no additional change needed to your standard LoRA procedure, except for specifying `init_lora_weights = "olora"` option in your lora configuration. Additionally you can refer to olora finetuning script. Run the script simply by running: ```bash python3 examples/olora_finetuning/olora_finetuning.py --base_model facebook/opt-350m ``` OLoRA also supports quantization. To use 4-bit quantization try: ```bash python3 examples/olora_finetuning/olora_finetuning.py --base_model facebook/opt-350m --quantize ``` ## Use the model You can load and use the model as any other 🤗 PEFT model ```python from peft import PeftModel model = AutoModelForCausalLM.from_pretrained("facebook/opt-350m") tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m") olora_model = PeftModel.from_pretrained(model, "olora-opt-350m") ``` ## OLoRA and LoRA OLoRA differs from LoRA in that it mutates the original weights. To utilize multiple adapters simultaneously, you can leverage the `path_initial_model_for_weight_conversion` option. Below is a simple template illustrating how to convert OLoRA to conventional LoRA: ```python base_model = AutoModel.from_pretrained("facebook/opt-350m") olora_config = LoraConfig( ... init_lora_weights = "olora" # Initialize the model with OLoRA ) olora_model = get_peft_model(base_model, olora_config) init_path = <path-to-untrained-olora-model> olora_model.save_pretrained(init_path) # Save the model *before* performing any training # Train the model train(olora_model) # Your training loop #Save the model after training olora_model.save_pretrained(output_dir, path_initial_model_for_weight_conversion=init_path) ``` After completing training, you can save and convert your OLoRA model to a conventional LoRA model by setting `path_initial_model_for_weight_conversion` to `init_path`, that is the path of your untrained OLoRA model. This conversion enables you to use multiple adapters with your LoRA model. Note that this conversion is not supported if `rslora` is used in combination with `rank_pattern` or `alpha_pattern`. ## Citation ``` @misc{büyükakyüz2024olora, title={OLoRA: Orthonormal Low-Rank Adaptation of Large Language Models}, author={Kerim Büyükakyüz}, year={2024}, eprint={2406.01775}, archivePrefix={arXiv}, primaryClass={cs.CL} } ```
peft/examples/olora_finetuning/README.md/0
{ "file_path": "peft/examples/olora_finetuning/README.md", "repo_id": "peft", "token_count": 1198 }
185
import os from enum import Enum import torch from datasets import DatasetDict, load_dataset, load_from_disk from datasets.builder import DatasetGenerationError from transformers import ( AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, ) from peft import LoraConfig DEFAULT_CHATML_CHAT_TEMPLATE = "{% for message in messages %}\n{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% if loop.last and add_generation_prompt %}{{'<|im_start|>assistant\n' }}{% endif %}{% endfor %}" DEFAULT_ZEPHYR_CHAT_TEMPLATE = "{% for message in messages %}\n{% if message['role'] == 'user' %}\n{{ '<|user|>\n' + message['content'] + eos_token }}\n{% elif message['role'] == 'system' %}\n{{ '<|system|>\n' + message['content'] + eos_token }}\n{% elif message['role'] == 'assistant' %}\n{{ '<|assistant|>\n' + message['content'] + eos_token }}\n{% endif %}\n{% if loop.last and add_generation_prompt %}\n{{ '<|assistant|>' }}\n{% endif %}\n{% endfor %}" class ZephyrSpecialTokens(str, Enum): user = "<|user|>" assistant = "<|assistant|>" system = "<|system|>" eos_token = "</s>" bos_token = "<s>" pad_token = "<pad>" @classmethod def list(cls): return [c.value for c in cls] class ChatmlSpecialTokens(str, Enum): user = "<|im_start|>user" assistant = "<|im_start|>assistant" system = "<|im_start|>system" eos_token = "<|im_end|>" bos_token = "<s>" pad_token = "<pad>" @classmethod def list(cls): return [c.value for c in cls] def create_datasets(tokenizer, data_args, training_args, apply_chat_template=False): def preprocess(samples): batch = [] for conversation in samples["messages"]: batch.append(tokenizer.apply_chat_template(conversation, tokenize=False)) return {"content": batch} raw_datasets = DatasetDict() for split in data_args.splits.split(","): try: # Try first if dataset on a Hub repo dataset = load_dataset(data_args.dataset_name, split=split) except DatasetGenerationError: # If not, check local dataset dataset = load_from_disk(os.path.join(data_args.dataset_name, split)) if "train" in split: raw_datasets["train"] = dataset elif "test" in split: raw_datasets["test"] = dataset else: raise ValueError(f"Split type {split} not recognized as one of test or train.") if apply_chat_template: raw_datasets = raw_datasets.map( preprocess, batched=True, remove_columns=raw_datasets["train"].column_names, ) train_data = raw_datasets["train"] valid_data = raw_datasets["test"] print(f"Size of the train set: {len(train_data)}. Size of the validation set: {len(valid_data)}") print(f"A sample of train dataset: {train_data[0]}") return train_data, valid_data def create_and_prepare_model(args, data_args, training_args): if args.use_unsloth: from unsloth import FastLanguageModel bnb_config = None quant_storage_dtype = None if ( torch.distributed.is_available() and torch.distributed.is_initialized() and torch.distributed.get_world_size() > 1 and args.use_unsloth ): raise NotImplementedError("Unsloth is not supported in distributed training") if args.use_4bit_quantization: compute_dtype = getattr(torch, args.bnb_4bit_compute_dtype) quant_storage_dtype = getattr(torch, args.bnb_4bit_quant_storage_dtype) bnb_config = BitsAndBytesConfig( load_in_4bit=args.use_4bit_quantization, bnb_4bit_quant_type=args.bnb_4bit_quant_type, bnb_4bit_compute_dtype=compute_dtype, bnb_4bit_use_double_quant=args.use_nested_quant, bnb_4bit_quant_storage=quant_storage_dtype, ) if compute_dtype == torch.float16 and args.use_4bit_quantization: major, _ = torch.cuda.get_device_capability() if major >= 8: print("=" * 80) print("Your GPU supports bfloat16, you can accelerate training with the argument --bf16") print("=" * 80) elif args.use_8bit_quantization: bnb_config = BitsAndBytesConfig(load_in_8bit=args.use_8bit_quantization) if args.use_unsloth: # Load model model, _ = FastLanguageModel.from_pretrained( model_name=args.model_name_or_path, max_seq_length=data_args.max_seq_length, dtype=None, load_in_4bit=args.use_4bit_quantization, ) else: torch_dtype = ( quant_storage_dtype if quant_storage_dtype and quant_storage_dtype.is_floating_point else torch.float32 ) model = AutoModelForCausalLM.from_pretrained( args.model_name_or_path, quantization_config=bnb_config, trust_remote_code=True, attn_implementation="flash_attention_2" if args.use_flash_attn else "eager", torch_dtype=torch_dtype, ) peft_config = None chat_template = None if args.use_peft_lora and not args.use_unsloth: peft_config = LoraConfig( lora_alpha=args.lora_alpha, lora_dropout=args.lora_dropout, r=args.lora_r, bias="none", task_type="CAUSAL_LM", target_modules=args.lora_target_modules.split(",") if args.lora_target_modules != "all-linear" else args.lora_target_modules, ) special_tokens = None chat_template = None if args.chat_template_format == "chatml": special_tokens = ChatmlSpecialTokens chat_template = DEFAULT_CHATML_CHAT_TEMPLATE elif args.chat_template_format == "zephyr": special_tokens = ZephyrSpecialTokens chat_template = DEFAULT_ZEPHYR_CHAT_TEMPLATE if special_tokens is not None: tokenizer = AutoTokenizer.from_pretrained( args.model_name_or_path, pad_token=special_tokens.pad_token.value, bos_token=special_tokens.bos_token.value, eos_token=special_tokens.eos_token.value, additional_special_tokens=special_tokens.list(), trust_remote_code=True, ) tokenizer.chat_template = chat_template # make embedding resizing configurable? model.resize_token_embeddings(len(tokenizer), pad_to_multiple_of=8) else: tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, trust_remote_code=True) tokenizer.pad_token = tokenizer.eos_token if args.use_unsloth: # Do model patching and add fast LoRA weights model = FastLanguageModel.get_peft_model( model, lora_alpha=args.lora_alpha, lora_dropout=args.lora_dropout, r=args.lora_r, target_modules=args.lora_target_modules.split(",") if args.lora_target_modules != "all-linear" else args.lora_target_modules, use_gradient_checkpointing=training_args.gradient_checkpointing, random_state=training_args.seed, max_seq_length=data_args.max_seq_length, ) return model, peft_config, tokenizer
peft/examples/sft/utils.py/0
{ "file_path": "peft/examples/sft/utils.py", "repo_id": "peft", "token_count": 3338 }
186
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import inspect from contextlib import contextmanager from copy import deepcopy from functools import update_wrapper from types import MethodType from .peft_model import PeftConfig, PeftModel from .tuners.lora.layer import LoraLayer def update_forward_signature(model: PeftModel) -> None: """ Updates the forward signature of the PeftModel to include parents class signature model (`PeftModel`): Peft model to update the forward signature Example: ```python >>> from transformers import WhisperForConditionalGeneration >>> from peft import get_peft_model, LoraConfig, update_forward_signature >>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en") >>> peft_config = LoraConfig(r=8, lora_alpha=32, lora_dropout=0.1, target_modules=["q_proj", "v_proj"]) >>> peft_model = get_peft_model(model, peft_config) >>> update_forward_signature(peft_model) ``` """ # Only update signature when the current forward signature only has *args and **kwargs current_signature = inspect.signature(model.forward) if ( len(current_signature.parameters) == 2 and "args" in current_signature.parameters and "kwargs" in current_signature.parameters ): forward = deepcopy(model.forward.__func__) update_wrapper( forward, type(model.get_base_model()).forward, assigned=("__doc__", "__name__", "__annotations__") ) model.forward = MethodType(forward, model) def update_generate_signature(model: PeftModel) -> None: """ Updates the generate signature of a PeftModel with overriding generate to include parents class signature model (`PeftModel`): Peft model to update the generate signature Example: ```python >>> from transformers import AutoModelForSeq2SeqLM, AutoTokenizer >>> from peft import get_peft_model, LoraConfig, TaskType, update_generate_signature >>> model_name_or_path = "bigscience/mt0-large" >>> tokenizer = AutoTokenizer.from_pretrained(model_name_or_path) >>> model = AutoModelForSeq2SeqLM.from_pretrained(model_name_or_path) >>> peft_config = LoraConfig( ... task_type=TaskType.SEQ_2_SEQ_LM, inference_mode=False, r=8, lora_alpha=32, lora_dropout=0.1 ... ) >>> peft_model = get_peft_model(model, peft_config) >>> update_generate_signature(peft_model) >>> help(peft_model.generate) ``` """ if not hasattr(model, "generate"): return current_signature = inspect.signature(model.generate) if ( len(current_signature.parameters) == 2 and "args" in current_signature.parameters and "kwargs" in current_signature.parameters ) or (len(current_signature.parameters) == 1 and "kwargs" in current_signature.parameters): generate = deepcopy(model.generate.__func__) update_wrapper( generate, type(model.get_base_model()).generate, assigned=("__doc__", "__name__", "__annotations__"), ) model.generate = MethodType(generate, model) def update_signature(model: PeftModel, method: str = "all") -> None: """ Updates the signature of a PeftModel include parents class signature for forward or generate method model (`PeftModel`): Peft model to update generate or forward signature method (`str`): method to update signature choose one of "forward", "generate", "all" Example: ```python >>> from transformers import AutoModelForSeq2SeqLM, AutoTokenizer >>> from peft import get_peft_model, LoraConfig, TaskType, update_signature >>> model_name_or_path = "bigscience/mt0-large" >>> tokenizer = AutoTokenizer.from_pretrained(model_name_or_path) >>> model = AutoModelForSeq2SeqLM.from_pretrained(model_name_or_path) >>> peft_config = LoraConfig( ... task_type=TaskType.SEQ_2_SEQ_LM, inference_mode=False, r=8, lora_alpha=32, lora_dropout=0.1 ... ) >>> peft_model = get_peft_model(model, peft_config) >>> update_signature(peft_model) >>> help(peft_model.generate) ``` """ if method == "forward": update_forward_signature(model) elif method == "generate": update_generate_signature(model) elif method == "all": update_forward_signature(model) update_generate_signature(model) else: raise ValueError(f"method {method} is not supported please choose one of ['forward', 'generate', 'all']") def check_if_peft_model(model_name_or_path: str) -> bool: """ Check if the model is a PEFT model. Args: model_name_or_path (`str`): Model id to check, can be local or on the Hugging Face Hub. Returns: `bool`: True if the model is a PEFT model, False otherwise. """ is_peft_model = True try: PeftConfig.from_pretrained(model_name_or_path) except Exception: # allow broad exceptions so that this works even if new exceptions are added on HF Hub side is_peft_model = False return is_peft_model @contextmanager def rescale_adapter_scale(model, multiplier): """ Context manager to temporarily rescale the scaling of the LoRA adapter in a model. The original scaling values are restored when the context manager exits. This context manager works with the transformers and diffusers models that have directly loaded LoRA adapters. For LoRA, applying this context manager with multiplier in [0, 1] is strictly equivalent to applying [wise-ft](https://arxiv.org/abs/2109.01903) (see [#1940](https://github.com/huggingface/peft/issues/1940) for details). It can improve the performances of the model if there is a distribution shiftbetween the training data used for fine-tuning, and the test data used during inference. Warning: It has been reported that when using Apple's MPS backend for PyTorch, it is necessary to add a short sleep time after exiting the context before the scales are fully restored. Args: model: The model containing `LoraLayer` modules whose scaling is to be adjusted. multiplier (float or int): The multiplier that rescales the `scaling` attribute. Must be of type float or int. Raises: ValueError: If the model does not contain any `LoraLayer` instances, indicating that the model does not support scaling. Example: ```python >>> model = ModelWithLoraLayer() >>> multiplier = 0.5 >>> with rescale_adapter_scale(model, multiplier): ... outputs = model(**inputs) # Perform operations with the scaled model >>> outputs = model(**inputs) # The original scaling values are restored here ``` """ # check if multiplier has a valid data type if not isinstance(multiplier, (float, int)): raise TypeError(f"Argument multiplier should be of type float, got {type(multiplier)}") # iterate on the model's modules and grab the original scaling attribute # from the lora layers if present original_scaling = {} for module in model.modules(): if isinstance(module, LoraLayer): original_scaling[module] = module.scaling.copy() module.scaling = {k: v * multiplier for k, v in module.scaling.items()} # check whether scaling is prohibited on model # the original scaling dictionary should be empty # if there were no lora layers if not original_scaling: raise ValueError("scaling is only supported for models with `LoraLayer`s") try: yield finally: # restore original scaling values after exiting the context for module, scaling in original_scaling.items(): module.scaling = scaling
peft/src/peft/helpers.py/0
{ "file_path": "peft/src/peft/helpers.py", "repo_id": "peft", "token_count": 2921 }
187
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import re from itertools import chain from typing import Dict, Type, Union import torch from torch import nn from peft.tuners.lycoris_utils import LycorisConfig, LycorisTuner from .layer import Conv2d, Linear, LoHaLayer class LoHaModel(LycorisTuner): """ Creates Low-Rank Hadamard Product model from a pretrained model. The method is partially described in https://arxiv.org/abs/2108.06098 Current implementation heavily borrows from https://github.com/KohakuBlueleaf/LyCORIS/blob/eb460098187f752a5d66406d3affade6f0a07ece/lycoris/modules/loha.py Args: model (`torch.nn.Module`): The model to which the adapter tuner layers will be attached. config ([`LoHaConfig`]): The configuration of the LoHa model. adapter_name (`str`): The name of the adapter, defaults to `"default"`. Returns: `torch.nn.Module`: The LoHa model. Example: ```py >>> from diffusers import StableDiffusionPipeline >>> from peft import LoHaModel, LoHaConfig >>> config_te = LoHaConfig( ... r=8, ... lora_alpha=32, ... target_modules=["k_proj", "q_proj", "v_proj", "out_proj", "fc1", "fc2"], ... rank_dropout=0.0, ... module_dropout=0.0, ... init_weights=True, ... ) >>> config_unet = LoHaConfig( ... r=8, ... lora_alpha=32, ... target_modules=[ ... "proj_in", ... "proj_out", ... "to_k", ... "to_q", ... "to_v", ... "to_out.0", ... "ff.net.0.proj", ... "ff.net.2", ... ], ... rank_dropout=0.0, ... module_dropout=0.0, ... init_weights=True, ... use_effective_conv2d=True, ... ) >>> model = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5") >>> model.text_encoder = LoHaModel(model.text_encoder, config_te, "default") >>> model.unet = LoHaModel(model.unet, config_unet, "default") ``` **Attributes**: - **model** ([`~torch.nn.Module`]) -- The model to be adapted. - **peft_config** ([`LoHaConfig`]): The configuration of the LoHa model. """ prefix: str = "hada_" layers_mapping: Dict[Type[torch.nn.Module], Type[LoHaLayer]] = { torch.nn.Conv2d: Conv2d, torch.nn.Linear: Linear, } def _create_and_replace( self, config: LycorisConfig, adapter_name: str, target: Union[LoHaLayer, nn.Module], target_name: str, parent: nn.Module, current_key: str, ) -> None: """ A private method to create and replace the target module with the adapter module. """ # Regexp matching - Find key which matches current target_name in patterns provided pattern_keys = list(chain(config.rank_pattern.keys(), config.alpha_pattern.keys())) target_name_key = next(filter(lambda key: re.match(rf"(.*\.)?{key}$", current_key), pattern_keys), target_name) kwargs = config.to_dict() kwargs["r"] = config.rank_pattern.get(target_name_key, config.r) kwargs["alpha"] = config.alpha_pattern.get(target_name_key, config.alpha) if isinstance(target, LoHaLayer): target.update_layer(adapter_name, **kwargs) else: new_module = self._create_new_module(config, adapter_name, target, **kwargs) self._replace_module(parent, target_name, new_module, target)
peft/src/peft/tuners/loha/model.py/0
{ "file_path": "peft/src/peft/tuners/loha/model.py", "repo_id": "peft", "token_count": 1824 }
188
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import importlib import math import warnings from typing import Any, Optional, Union import torch import torch.nn as nn import torch.nn.init as init from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge from peft.utils import transpose from peft.utils.integrations import gather_params_ctx from .layer import LoraLayer class LoraParallelLinear(nn.Module, LoraLayer): """ When the target layer parallel_linear is RowParallelLinear, in order to keep the input and output shapes consistent, we need to split the lora matrix A into rows, and the lora_B at this time should be a complete linear layer; In the same way, when the target layer is ColumnParallelLinear, we perform column segmentation on lora_B, while lora_A is still a complete linear layer. """ def __init__( self, base_layer, adapter_name: str, backend, r: int = 0, lora_alpha: int = 1, lora_dropout: float = 0.0, fan_in_fan_out: bool = False, is_target_conv_1d_layer: bool = False, init_lora_weights: Union[bool, str] = True, use_rslora: bool = False, use_dora: bool = False, **kwargs, ): super().__init__() LoraLayer.__init__(self, base_layer=base_layer, **kwargs) if use_dora: raise ValueError(f"{self.__class__.__name__} does not support DoRA yet, please set it to False") self.backend = backend self.is_parallel_a = isinstance(base_layer, backend.RowParallelLinear) self.fan_in_fan_out = fan_in_fan_out self._active_adapter = adapter_name megatron_config = kwargs["megatron_config"] parallel_linear_kwargs = {"megatron_config": megatron_config} init_method = init.xavier_normal_ if hasattr(megatron_config, "init_method"): init_method = megatron_config.init_method input_is_parallel = True gather_output = False if isinstance(base_layer, self.backend.RowParallelLinear): input_is_parallel = base_layer.input_is_parallel else: gather_output = base_layer.gather_output self.update_layer( adapter_name, r, lora_alpha=lora_alpha, lora_dropout=lora_dropout, init_lora_weights=init_lora_weights, use_rslora=use_rslora, use_dora=use_dora, init_method=init_method, input_is_parallel=input_is_parallel, gather_output=gather_output, **parallel_linear_kwargs, ) if is_target_conv_1d_layer: raise ValueError( f"{self.__class__.__name__} does not support target_conv_1d_layer yet, please set it to False" ) self.is_target_conv_1d_layer = False def update_layer( self, adapter_name, r, lora_alpha, lora_dropout, init_lora_weights, use_rslora, use_dora=False, init_method=init.xavier_normal_, input_is_parallel=True, gather_output=False, **parallel_linear_kwargs, ): if r <= 0: raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") self.r[adapter_name] = r self.lora_alpha[adapter_name] = lora_alpha if lora_dropout > 0.0: lora_dropout_layer = nn.Dropout(p=lora_dropout) else: lora_dropout_layer = nn.Identity() self.lora_dropout[adapter_name] = lora_dropout_layer megatron_config = parallel_linear_kwargs["megatron_config"] # lora needs to be forced to upgrade to 32-bit precision, otherwise it will overflow megatron_config.params_dtype = torch.float32 if self.is_parallel_a: lora_a = self.backend.RowParallelLinear( input_size=self.in_features, output_size=r, bias=False, input_is_parallel=input_is_parallel, skip_bias_add=True, init_method=init_method, config=megatron_config, ) lora_b = nn.Linear(in_features=r, out_features=self.out_features, bias=False, dtype=torch.float32) else: lora_a = nn.Linear(in_features=self.in_features, out_features=r, bias=False, dtype=torch.float32) lora_b = self.backend.ColumnParallelLinear( input_size=r, output_size=self.out_features, bias=False, gather_output=gather_output, init_method=init_method, config=megatron_config, ) self.lora_A[adapter_name] = lora_a self.lora_B[adapter_name] = lora_b if use_rslora: self.scaling[adapter_name] = lora_alpha / math.sqrt(r) else: self.scaling[adapter_name] = lora_alpha / r # for inits that require access to the base weight, use gather_param_ctx so that the weight is gathered when using DeepSpeed if isinstance(init_lora_weights, str) and init_lora_weights.startswith("pissa"): with gather_params_ctx(self.get_base_layer().weight): self.pissa_init(adapter_name, init_lora_weights) elif isinstance(init_lora_weights, str) and init_lora_weights.lower() == "olora": with gather_params_ctx(self.get_base_layer().weight): self.olora_init(adapter_name) elif init_lora_weights == "loftq": with gather_params_ctx(self.get_base_layer().weight): self.loftq_init(adapter_name) elif init_lora_weights: self.reset_lora_parameters(adapter_name, init_lora_weights) # call this before dora_init self._move_adapter_to_device_of_base_layer(adapter_name) if use_dora: self.dora_init(adapter_name) self.use_dora[adapter_name] = True else: self.use_dora[adapter_name] = False self.set_adapter(self.active_adapters) def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any): self._check_forward_args(x, *args, **kwargs) adapter_names = kwargs.pop("adapter_names", None) # If weight is used for matrix multiplication here, the final aggregation operation of the original # parallel_linear layer will be missing, so we need to directly call its forward function to obtain the # output of the original parallel_linear layer. if self.disable_adapters: if self.merged: self.unmerge() result, bias = self.base_layer(x, *args, **kwargs) elif adapter_names is not None: raise ValueError(f"{self.__class__.__name__} does not support mixed_batch_forward yet.") elif self.merged: result, bias = self.base_layer(x, *args, **kwargs) else: result, bias = self.base_layer(x, *args, **kwargs) torch_result_dtype = result.dtype for active_adapter in self.active_adapters: if active_adapter not in self.lora_A.keys(): continue lora_A = self.lora_A[active_adapter] lora_B = self.lora_B[active_adapter] dropout = self.lora_dropout[active_adapter] scaling = self.scaling[active_adapter] x = x.to(lora_A.weight.dtype) if not self.use_dora[active_adapter]: lora_result = lora_A(dropout(x)) if isinstance(lora_result, tuple): lora_result = lora_result[0] lora_result = lora_B(lora_result) if isinstance(lora_result, tuple): lora_result = lora_result[0] lora_result = lora_result * scaling result = result + lora_result else: x = dropout(x) result = result + self.lora_magnitude_vector[active_adapter]( x, lora_A=lora_A, lora_B=lora_B, scaling=scaling, base_layer=self.get_base_layer(), ) result = result.to(torch_result_dtype) return result, bias def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: """ Merge the active adapter weights into the base weights Args: safe_merge (`bool`, *optional*): If True, the merge operation will be performed in a copy of the original weights and check for NaNs before merging the weights. This is useful if you want to check if the merge operation will produce NaNs. Defaults to `False`. adapter_names (`list[str]`, *optional*): The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults to `None`. """ adapter_names = check_adapters_to_merge(self, adapter_names) if not adapter_names: # no adapter to merge return for active_adapter in adapter_names: if active_adapter in self.lora_A.keys(): base_layer = self.get_base_layer() if safe_merge: # Note that safe_merge will be slower than the normal merge # because of the copy operation. orig_weights = base_layer.weight.data.clone() delta_weight = self.get_delta_weight(active_adapter) if not self.use_dora[active_adapter]: orig_weights = orig_weights + delta_weight else: # handle dora # since delta_weight already includes scaling, set it to 1 here weight_norm = ( self.lora_magnitude_vector[active_adapter] .get_weight_norm(orig_weights, transpose(delta_weight, self.fan_in_fan_out), scaling=1) .detach() ) # We need to cache weight_norm because it has to be based on the original weights. We # cannot calculate it on the fly based on the merged weights when unmerging because its a # different value self._cache_store(f"{active_adapter}-weight_norm", weight_norm) dora_factor = self.lora_magnitude_vector[active_adapter].weight / weight_norm dora_factor = transpose(dora_factor.view(-1, 1), self.fan_in_fan_out) orig_weights = dora_factor * (orig_weights + delta_weight) if not torch.isfinite(orig_weights).all(): raise ValueError( f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" ) base_layer.weight.data = orig_weights else: delta_weight = self.get_delta_weight(active_adapter) if not self.use_dora[active_adapter]: base_layer.weight.data = base_layer.weight.data + delta_weight else: # handle dora # since delta_weight already includes scaling, set it to 1 here weight_norm = ( self.lora_magnitude_vector[active_adapter] .get_weight_norm( base_layer.weight, transpose(delta_weight, self.fan_in_fan_out), scaling=1 ) .detach() ) # We need to cache weight_norm because it has to be based on the original weights. We # cannot calculate it on the fly based on the merged weights when unmerging because its a # different value self._cache_store(f"{active_adapter}-weight_norm", weight_norm) dora_factor = self.lora_magnitude_vector[active_adapter].weight / weight_norm dora_factor = transpose(dora_factor.view(-1, 1), self.fan_in_fan_out) new_weight = dora_factor * (base_layer.weight.data + delta_weight) base_layer.weight.data = new_weight self.merged_adapters.append(active_adapter) def unmerge(self) -> None: """ This method unmerges all merged adapter layers from the base weights. """ if not self.merged: warnings.warn("Already unmerged. Nothing to do.") return while len(self.merged_adapters) > 0: active_adapter = self.merged_adapters.pop() if active_adapter in self.lora_A.keys(): weight = self.get_base_layer().weight delta_weight = self.get_delta_weight(active_adapter) if not self.use_dora[active_adapter]: weight.data -= delta_weight else: weight_norm = self._cache_pop(f"{active_adapter}-weight_norm") dora_factor = self.lora_magnitude_vector[active_adapter].weight / weight_norm weight_orig = weight.data / dora_factor.view(-1, 1) - delta_weight weight.data = weight_orig def get_delta_weight(self, adapter) -> torch.Tensor: """ Compute the delta weight for the given adapter. Args: adapter (str): The name of the adapter for which the delta weight should be computed. """ device = self.lora_B[adapter].weight.device dtype = self.lora_B[adapter].weight.dtype # In case users wants to merge the adapter weights that are in # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to # (b)float16 because some CPUs have slow bf16/fp16 matmuls. cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) weight_A = self.lora_A[adapter].weight weight_B = self.lora_B[adapter].weight if cast_to_fp32: weight_A = weight_A.float() weight_B = weight_B.float() output_tensor = transpose(weight_B @ weight_A, self.fan_in_fan_out) * self.scaling[adapter] if cast_to_fp32: output_tensor = output_tensor.to(dtype=dtype) # cast back the weights self.lora_A[adapter].weight.data = weight_A.to(dtype) self.lora_B[adapter].weight.data = weight_B.to(dtype) return output_tensor def __repr__(self) -> str: rep = super().__repr__() return "lora." + rep def dispatch_megatron( target: torch.nn.Module, adapter_name: str, lora_config, **kwargs: Any, ) -> Optional[torch.nn.Module]: new_module = None if isinstance(target, BaseTunerLayer): target_base_layer = target.get_base_layer() else: target_base_layer = target if lora_config.megatron_config: megatron_core = importlib.import_module(lora_config.megatron_core) else: megatron_core = None if megatron_core and isinstance( target_base_layer, (megatron_core.tensor_parallel.ColumnParallelLinear, megatron_core.tensor_parallel.RowParallelLinear), ): megatron_kwargs = kwargs.copy() megatron_config = lora_config.megatron_config if isinstance(megatron_config, dict): transformer_config_class = megatron_core.transformer.transformer_config.TransformerConfig megatron_config = transformer_config_class(**lora_config.megatron_config) megatron_kwargs["megatron_config"] = megatron_config if megatron_kwargs["fan_in_fan_out"]: warnings.warn( "fan_in_fan_out is set to True but the target module is `ColumnParallelLinear` " "or `RowParallelLinear`. " "Setting fan_in_fan_out to False." ) megatron_kwargs["fan_in_fan_out"] = lora_config.fan_in_fan_out = False new_module = LoraParallelLinear( base_layer=target, adapter_name=adapter_name, backend=megatron_core.tensor_parallel, **megatron_kwargs ) return new_module
peft/src/peft/tuners/lora/tp_layer.py/0
{ "file_path": "peft/src/peft/tuners/lora/tp_layer.py", "repo_id": "peft", "token_count": 8384 }
189
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import math from typing import Any import torch import torch.nn as nn from peft.tuners.tuners_utils import BaseTunerLayer from .config import PolyConfig from .router import get_router class PolyLayer(BaseTunerLayer): # All names of layers that may contain (trainable) adapter weights adapter_layer_names = ("poly_lora_A", "poly_lora_B", "poly_router") # All names of other parameters that may contain adapter-related parameters other_param_names = ("r", "n_tasks", "n_skills", "n_splits") def __init__(self, base_layer: nn.Module, **kwargs): self.base_layer = base_layer self.r = {} self.n_tasks = {} self.n_skills = {} self.n_splits = {} self.poly_type = {} self.poly_router = nn.ModuleDict() self.poly_lora_A = nn.ParameterDict() self.poly_lora_B = nn.ParameterDict() self.kwargs = kwargs base_layer = self.get_base_layer() if isinstance(base_layer, nn.Linear): in_features, out_features = base_layer.in_features, base_layer.out_features else: raise ValueError(f"Unsupported layer type {type(base_layer)}") self.in_features = in_features self.out_features = out_features def update_layer(self, adapter_name, poly_config): if poly_config.r <= 0: raise ValueError(f"`r` should be a positive integer value but the value passed is {poly_config.r}") self.r[adapter_name] = poly_config.r self.n_tasks[adapter_name] = poly_config.n_tasks self.n_skills[adapter_name] = poly_config.n_skills self.n_splits[adapter_name] = poly_config.n_splits self.poly_type[adapter_name] = poly_config.poly_type self.poly_lora_A[adapter_name] = nn.Parameter( torch.empty( poly_config.n_splits, poly_config.n_skills, self.in_features // poly_config.n_splits, poly_config.r, ) ) self.poly_lora_B[adapter_name] = nn.Parameter( torch.empty( poly_config.n_splits, poly_config.n_skills, poly_config.r, self.out_features // poly_config.n_splits, ) ) self.poly_router[adapter_name] = get_router(poly_config) self.reset_poly_parameters(adapter_name, init_weights=poly_config.init_weights) self._move_adapter_to_device_of_base_layer(adapter_name) self.set_adapter(self.active_adapters) def reset_poly_parameters(self, adapter_name, init_weights): if adapter_name in self.poly_lora_A.keys(): # initialize A the same way as the default for nn.Linear # https://github.com/microsoft/mttl/blob/ce4ca51dbca73be656feb9b3e5233633e3c5dec7/mttl/models/poly.py#L269 n_splits, n_skills, d, r = self.poly_lora_A[adapter_name].shape for skill in range(n_skills): for split in range(n_splits): param = torch.empty((r, d)) torch.nn.init.kaiming_uniform_(param, a=math.sqrt(5)) self.poly_lora_A[adapter_name].data[split, skill, :, :] = param.T if init_weights: # initialize B to zero torch.nn.init.zeros_(self.poly_lora_B[adapter_name]) else: # initialize B the same way as the default for nn.Linear n_splits, n_skills, r, d = self.poly_lora_B[adapter_name].shape for skill in range(n_skills): for split in range(n_splits): param = torch.empty((d, r)) torch.nn.init.kaiming_uniform_(param, a=math.sqrt(5)) self.poly_lora_B[adapter_name].data[split, skill, :, :] = param.T # initialized router self.poly_router[adapter_name].reset() class Linear(nn.Module, PolyLayer): # Lora implemented in a dense layer def __init__( self, base_layer, adapter_name: str, poly_config: PolyConfig, **kwargs, ) -> None: super().__init__() PolyLayer.__init__(self, base_layer, **kwargs) self._active_adapter = adapter_name self.update_layer(adapter_name, poly_config) def forward(self, x: torch.Tensor, *args: Any, task_ids: torch.Tensor = None, **kwargs: Any) -> torch.Tensor: previous_dtype = x.dtype if self.disable_adapters: result = self.base_layer(x, *args, **kwargs) else: result = self.base_layer(x, *args, **kwargs) for active_adapter in self.active_adapters: if active_adapter not in self.poly_lora_A.keys(): continue r = self.r[active_adapter] poly_router = self.poly_router[active_adapter] poly_lora_A = self.poly_lora_A[active_adapter] poly_lora_B = self.poly_lora_B[active_adapter] # Combine the output of LoRAs # https://github.com/microsoft/mttl/blob/ce4ca51dbca73be656feb9b3e5233633e3c5dec7/mttl/models/poly.py#L293 mixing_weights = poly_router(task_ids=task_ids, input_ids=x) bs, n_splits, n_skills = mixing_weights.size() # A is n_splits, n_skills, D // n_splits, rank # we want bs, n_splits, D // n_splits, rank A = torch.einsum("bqs,qsdr->bqdr", (mixing_weights, poly_lora_A)) B = torch.einsum("bqs,qsrd->bqrd", (mixing_weights, poly_lora_B)) A = A.reshape(bs, self.in_features, r) B = B.transpose(1, 2).reshape(bs, r, self.out_features) x = x.to(A.dtype) result += x.bmm(A).bmm(B) / r result = result.to(previous_dtype) return result def __repr__(self) -> str: rep = super().__repr__() return "poly." + rep
peft/src/peft/tuners/poly/layer.py/0
{ "file_path": "peft/src/peft/tuners/poly/layer.py", "repo_id": "peft", "token_count": 3184 }
190
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import annotations import warnings from dataclasses import dataclass from typing import Optional from peft.config import PeftConfig from peft.utils.peft_types import PeftType @dataclass class XLoraConfig(PeftConfig): r""" This is the configuration class to store the configuration of a `XLoraModel`. When the config is reloaded, the paths of the `adapters` field is disregarded in favor of the saved adapters. As such, only the keys matter during loading. Args: hidden_size (`int`): Hidden size of the base model. adapters (`dict`): Mapping of adapter names to the LoRA adapter id, as per PeftModel.load_adapter. *They will be automatically loaded*, to use as LoRA experts. When using from_pretrained, pass the new adapters dict as a keyword argument. enable_softmax (`bool`, *optional*, defaults to `True`): Enable softmax application for the X-LoRA classifier. enable_softmax_topk (`bool`, *optional*, defaults to `False`): Enable softmax application for the top-k LoRA adapters. Mutually exclusive to `enable_softmax` and must only be set if `top_k_lora` is. softmax_temperature (`float`, *optional*, defaults to 1.0): Softmax temperature, lower yields sharper predictions layerwise_scalings (`bool`, *optional*, defaults to `False`): If True, generate scalings for each LoRA adapter (each layer). If this is False, then scalings will be broadcasted, the same, to each layer. top_k_lora (`int`, *optional*, defaults to None): Sparsely select the top_k LoRA experts instead of the default dense method. xlora_depth (`int`, *optional*, defaults to 1): Depth of the X-LoRA classifier. xlora_size (`int`, *optional*, defaults to 2048): Hidden size of the X-LoRA classifier, irrelevant if `xlora_depth=1`. xlora_dropout_p (`float`, *optional*, defaults to 0.2): Dropout probability of the X-LoRA classifier, irrelevant if `xlora_depth=1`. use_trainable_adapters (`bool`, *optional*, defaults to False): Make the adapters trainable. scaling_pass_value (`float`, *optional*, defaults to 0): Scaling pass value. global_scaling_weight (`float`, *optional*, defaults to 1): Weight to multiply output of each LoRA adapter by. """ hidden_size: int = None # type: ignore adapters: dict[str, str] = None # type: ignore enable_softmax: bool = True enable_softmax_topk: bool = False layerwise_scalings: bool = False xlora_depth: int = 1 xlora_size: int = 2048 xlora_dropout_p: float = 0.2 use_trainable_adapters: bool = False softmax_temperature: float = 1.0 top_k_lora: Optional[int] = None scaling_pass_value: float = 0.0 global_scaling_weight: float = 1.0 def __post_init__(self): self.peft_type = PeftType.XLORA if self.hidden_size is None: warnings.warn( "No value was provided for `hidden_size`. This will be set to 4096 by default, please ensure that this is correct." ) self.hidden_size = 4096 if self.adapters is None: warnings.warn( "No value was provided for for `adapters`. This will be set to empty, please ensure that this is correct." ) self.adapters = {} if self.enable_softmax_topk and self.top_k_lora is None: warnings.warn("`enable_softmax_topk` enabled `top_k_lora` is not set") if self.enable_softmax_topk and self.enable_softmax: warnings.warn( "`enable_softmax_topk` and `enable_softmax` are both enabled. This will result in worse performance." ) if self.top_k_lora is not None and self.top_k_lora < 1: warnings.warn("`top_k_lora` value must be at least 1.")
peft/src/peft/tuners/xlora/config.py/0
{ "file_path": "peft/src/peft/tuners/xlora/config.py", "repo_id": "peft", "token_count": 1749 }
191
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import tempfile import unittest import torch from peft import ( AutoPeftModel, AutoPeftModelForCausalLM, AutoPeftModelForFeatureExtraction, AutoPeftModelForQuestionAnswering, AutoPeftModelForSeq2SeqLM, AutoPeftModelForSequenceClassification, AutoPeftModelForTokenClassification, PeftModel, PeftModelForCausalLM, PeftModelForFeatureExtraction, PeftModelForQuestionAnswering, PeftModelForSeq2SeqLM, PeftModelForSequenceClassification, PeftModelForTokenClassification, ) from peft.utils import infer_device class PeftAutoModelTester(unittest.TestCase): dtype = torch.float16 if infer_device() == "mps" else torch.bfloat16 def test_peft_causal_lm(self): model_id = "peft-internal-testing/tiny-OPTForCausalLM-lora" model = AutoPeftModelForCausalLM.from_pretrained(model_id) assert isinstance(model, PeftModelForCausalLM) with tempfile.TemporaryDirectory() as tmp_dirname: model.save_pretrained(tmp_dirname) model = AutoPeftModelForCausalLM.from_pretrained(tmp_dirname) assert isinstance(model, PeftModelForCausalLM) # check if kwargs are passed correctly model = AutoPeftModelForCausalLM.from_pretrained(model_id, torch_dtype=self.dtype) assert isinstance(model, PeftModelForCausalLM) assert model.base_model.lm_head.weight.dtype == self.dtype adapter_name = "default" is_trainable = False # This should work _ = AutoPeftModelForCausalLM.from_pretrained(model_id, adapter_name, is_trainable, torch_dtype=self.dtype) def test_peft_causal_lm_extended_vocab(self): model_id = "peft-internal-testing/tiny-random-OPTForCausalLM-extended-vocab" model = AutoPeftModelForCausalLM.from_pretrained(model_id) assert isinstance(model, PeftModelForCausalLM) # check if kwargs are passed correctly model = AutoPeftModelForCausalLM.from_pretrained(model_id, torch_dtype=self.dtype) assert isinstance(model, PeftModelForCausalLM) assert model.base_model.lm_head.weight.dtype == self.dtype adapter_name = "default" is_trainable = False # This should work _ = AutoPeftModelForCausalLM.from_pretrained(model_id, adapter_name, is_trainable, torch_dtype=self.dtype) def test_peft_seq2seq_lm(self): model_id = "peft-internal-testing/tiny_T5ForSeq2SeqLM-lora" model = AutoPeftModelForSeq2SeqLM.from_pretrained(model_id) assert isinstance(model, PeftModelForSeq2SeqLM) with tempfile.TemporaryDirectory() as tmp_dirname: model.save_pretrained(tmp_dirname) model = AutoPeftModelForSeq2SeqLM.from_pretrained(tmp_dirname) assert isinstance(model, PeftModelForSeq2SeqLM) # check if kwargs are passed correctly model = AutoPeftModelForSeq2SeqLM.from_pretrained(model_id, torch_dtype=self.dtype) assert isinstance(model, PeftModelForSeq2SeqLM) assert model.base_model.lm_head.weight.dtype == self.dtype adapter_name = "default" is_trainable = False # This should work _ = AutoPeftModelForSeq2SeqLM.from_pretrained(model_id, adapter_name, is_trainable, torch_dtype=self.dtype) def test_peft_sequence_cls(self): model_id = "peft-internal-testing/tiny_OPTForSequenceClassification-lora" model = AutoPeftModelForSequenceClassification.from_pretrained(model_id) assert isinstance(model, PeftModelForSequenceClassification) with tempfile.TemporaryDirectory() as tmp_dirname: model.save_pretrained(tmp_dirname) model = AutoPeftModelForSequenceClassification.from_pretrained(tmp_dirname) assert isinstance(model, PeftModelForSequenceClassification) # check if kwargs are passed correctly model = AutoPeftModelForSequenceClassification.from_pretrained(model_id, torch_dtype=self.dtype) assert isinstance(model, PeftModelForSequenceClassification) assert model.score.original_module.weight.dtype == self.dtype adapter_name = "default" is_trainable = False # This should work _ = AutoPeftModelForSequenceClassification.from_pretrained( model_id, adapter_name, is_trainable, torch_dtype=self.dtype ) def test_peft_token_classification(self): model_id = "peft-internal-testing/tiny_GPT2ForTokenClassification-lora" model = AutoPeftModelForTokenClassification.from_pretrained(model_id) assert isinstance(model, PeftModelForTokenClassification) with tempfile.TemporaryDirectory() as tmp_dirname: model.save_pretrained(tmp_dirname) model = AutoPeftModelForTokenClassification.from_pretrained(tmp_dirname) assert isinstance(model, PeftModelForTokenClassification) # check if kwargs are passed correctly model = AutoPeftModelForTokenClassification.from_pretrained(model_id, torch_dtype=self.dtype) assert isinstance(model, PeftModelForTokenClassification) assert model.base_model.classifier.original_module.weight.dtype == self.dtype adapter_name = "default" is_trainable = False # This should work _ = AutoPeftModelForTokenClassification.from_pretrained( model_id, adapter_name, is_trainable, torch_dtype=self.dtype ) def test_peft_question_answering(self): model_id = "peft-internal-testing/tiny_OPTForQuestionAnswering-lora" model = AutoPeftModelForQuestionAnswering.from_pretrained(model_id) assert isinstance(model, PeftModelForQuestionAnswering) with tempfile.TemporaryDirectory() as tmp_dirname: model.save_pretrained(tmp_dirname) model = AutoPeftModelForQuestionAnswering.from_pretrained(tmp_dirname) assert isinstance(model, PeftModelForQuestionAnswering) # check if kwargs are passed correctly model = AutoPeftModelForQuestionAnswering.from_pretrained(model_id, torch_dtype=self.dtype) assert isinstance(model, PeftModelForQuestionAnswering) assert model.base_model.qa_outputs.original_module.weight.dtype == self.dtype adapter_name = "default" is_trainable = False # This should work _ = AutoPeftModelForQuestionAnswering.from_pretrained( model_id, adapter_name, is_trainable, torch_dtype=self.dtype ) def test_peft_feature_extraction(self): model_id = "peft-internal-testing/tiny_OPTForFeatureExtraction-lora" model = AutoPeftModelForFeatureExtraction.from_pretrained(model_id) assert isinstance(model, PeftModelForFeatureExtraction) with tempfile.TemporaryDirectory() as tmp_dirname: model.save_pretrained(tmp_dirname) model = AutoPeftModelForFeatureExtraction.from_pretrained(tmp_dirname) assert isinstance(model, PeftModelForFeatureExtraction) # check if kwargs are passed correctly model = AutoPeftModelForFeatureExtraction.from_pretrained(model_id, torch_dtype=self.dtype) assert isinstance(model, PeftModelForFeatureExtraction) assert model.base_model.model.decoder.embed_tokens.weight.dtype == self.dtype adapter_name = "default" is_trainable = False # This should work _ = AutoPeftModelForFeatureExtraction.from_pretrained( model_id, adapter_name, is_trainable, torch_dtype=self.dtype ) def test_peft_whisper(self): model_id = "peft-internal-testing/tiny_WhisperForConditionalGeneration-lora" model = AutoPeftModel.from_pretrained(model_id) assert isinstance(model, PeftModel) with tempfile.TemporaryDirectory() as tmp_dirname: model.save_pretrained(tmp_dirname) model = AutoPeftModel.from_pretrained(tmp_dirname) assert isinstance(model, PeftModel) # check if kwargs are passed correctly model = AutoPeftModel.from_pretrained(model_id, torch_dtype=self.dtype) assert isinstance(model, PeftModel) assert model.base_model.model.model.encoder.embed_positions.weight.dtype == self.dtype adapter_name = "default" is_trainable = False # This should work _ = AutoPeftModel.from_pretrained(model_id, adapter_name, is_trainable, torch_dtype=self.dtype)
peft/tests/test_auto.py/0
{ "file_path": "peft/tests/test_auto.py", "repo_id": "peft", "token_count": 3615 }
192
# Copyright 2023-present the HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pytest import torch from torch import nn from transformers import AutoModelForCausalLM, AutoModelForSequenceClassification from peft import LoraConfig, get_peft_model class ModelWithModuleDict(nn.Module): def __init__(self): super().__init__() self.other_layer = nn.Linear(10, 10) self.module = nn.ModuleDict({"foo": nn.Linear(10, 10)}) def forward(self): return self.module["foo"](torch.rand(1, 10)) class ModelWithModuleList(nn.Module): def __init__(self): super().__init__() self.other_layer = nn.Linear(10, 10) self.module = nn.ModuleList([nn.Linear(10, 10)]) def forward(self): return self.module[0](torch.rand(1, 10)) class ModelWithParameterDict(nn.Module): def __init__(self): super().__init__() self.other_layer = nn.Linear(10, 10) self.module = nn.ParameterDict({"foo": nn.Parameter(torch.rand(10, 10))}) def forward(self): return self.module["foo"] class ModelWithParameterList(nn.Module): def __init__(self): super().__init__() self.other_layer = nn.Linear(10, 10) self.module = nn.ParameterList([nn.Parameter(torch.rand(10, 10))]) def forward(self): return self.module[0] @pytest.mark.parametrize( "cls", [ModelWithModuleDict, ModelWithModuleList, ModelWithParameterDict, ModelWithParameterList] ) def test_modules_to_save_targets_module_dict_raises(cls): model = cls() peft_config = LoraConfig( target_modules=["other_layer"], modules_to_save=["module"], ) model() # sanity check that the model would normally work msg = "modules_to_save cannot be applied to modules of type" with pytest.raises(TypeError, match=msg): get_peft_model(model=model, peft_config=peft_config) def test_modules_to_save_targets_tuner_layer_raises(): # See e.g. issue 2027 # Prevent users from (accidentally) targeting the same layer both with a tuner and modules_to_save. Normally, PEFT # will not target the same layer with both a tuner and ModulesToSaveWrapper. However, if modules_to_save is # automatically inferred, e.g. when using AutoModelForSequenceClassification, the ModulesToSaveWrapper is applied ex # post, which can lead to the double wrapping. model_id = "hf-internal-testing/tiny-random-OPTForCausalLM" model = AutoModelForSequenceClassification.from_pretrained(model_id) # Note: target_modules="all-linear" would also work and is closer to the original issue, but let's explicitly target # "score" here in case that "all-linear" will be fixed to no longer target the score layer. peft_config = LoraConfig(target_modules=["score"], task_type="SEQ_CLS") msg = "modules_to_save cannot be applied to modules of type" with pytest.raises(TypeError, match=msg): get_peft_model(model, peft_config) def test_get_peft_model_revision_warning(tmp_path): base_model_id = "peft-internal-testing/tiny-random-BertModel" base_revision = "v2.0.0" base_model = AutoModelForCausalLM.from_pretrained(base_model_id, revision=base_revision).eval() lora_config = LoraConfig(revision=base_revision) overwrite_revision = "main" overwrite_warning = f"peft config has already set base model revision to {base_revision}, overwriting with revision {overwrite_revision}" with pytest.warns(UserWarning, match=overwrite_warning): _ = get_peft_model(base_model, lora_config, revision=overwrite_revision)
peft/tests/test_other.py/0
{ "file_path": "peft/tests/test_other.py", "repo_id": "peft", "token_count": 1483 }
193
# timm <img class="float-left !m-0 !border-0 !dark:border-0 !shadow-none !max-w-lg w-[150px]" src="https://huggingface.co/front/thumbnails/docs/timm.png"/> `timm` is a library containing SOTA computer vision models, layers, utilities, optimizers, schedulers, data-loaders, augmentations, and training/evaluation scripts. It comes packaged with >700 pretrained models, and is designed to be flexible and easy to use. Read the [quick start guide](quickstart) to get up and running with the `timm` library. You will learn how to load, discover, and use pretrained models included in the library. <div class="mt-10"> <div class="w-full flex flex-col space-y-4 md:space-y-0 md:grid md:grid-cols-2 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="./feature_extraction" ><div class="w-full text-center bg-gradient-to-br from-blue-400 to-blue-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Tutorials</div> <p class="text-gray-700">Learn the basics and become familiar with timm. Start here if you are using timm for the first time!</p> </a> <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./reference/models" ><div class="w-full text-center bg-gradient-to-br from-purple-400 to-purple-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">Reference</div> <p class="text-gray-700">Technical descriptions of how timm classes and methods work.</p> </a> </div> </div>
pytorch-image-models/hfdocs/source/index.mdx/0
{ "file_path": "pytorch-image-models/hfdocs/source/index.mdx", "repo_id": "pytorch-image-models", "token_count": 560 }
194
# ESE-VoVNet **VoVNet** is a convolutional neural network that seeks to make [DenseNet](https://paperswithcode.com/method/densenet) more efficient by concatenating all features only once in the last feature map, which makes input size constant and enables enlarging new output channel. Read about [one-shot aggregation here](https://paperswithcode.com/method/one-shot-aggregation). ## How do I use this model on an image? To load a pretrained model: ```py >>> import timm >>> model = timm.create_model('ese_vovnet19b_dw', pretrained=True) >>> model.eval() ``` To load and preprocess the image: ```py >>> import urllib >>> from PIL import Image >>> from timm.data import resolve_data_config >>> from timm.data.transforms_factory import create_transform >>> config = resolve_data_config({}, model=model) >>> transform = create_transform(**config) >>> url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") >>> urllib.request.urlretrieve(url, filename) >>> img = Image.open(filename).convert('RGB') >>> tensor = transform(img).unsqueeze(0) # transform and add batch dimension ``` To get the model predictions: ```py >>> import torch >>> with torch.no_grad(): ... out = model(tensor) >>> probabilities = torch.nn.functional.softmax(out[0], dim=0) >>> print(probabilities.shape) >>> # prints: torch.Size([1000]) ``` To get the top-5 predictions class names: ```py >>> # Get imagenet class mappings >>> url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") >>> urllib.request.urlretrieve(url, filename) >>> with open("imagenet_classes.txt", "r") as f: ... categories = [s.strip() for s in f.readlines()] >>> # Print top categories per image >>> top5_prob, top5_catid = torch.topk(probabilities, 5) >>> for i in range(top5_prob.size(0)): ... print(categories[top5_catid[i]], top5_prob[i].item()) >>> # prints class names and probabilities like: >>> # [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] ``` Replace the model name with the variant you want to use, e.g. `ese_vovnet19b_dw`. You can find the IDs in the model summaries at the top of this page. To extract image features with this model, follow the [timm feature extraction examples](../feature_extraction), just change the name of the model you want to use. ## How do I finetune this model? You can finetune any of the pre-trained models just by changing the classifier (the last layer). ```py >>> model = timm.create_model('ese_vovnet19b_dw', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) ``` To finetune on your own dataset, you have to write a training loop or adapt [timm's training script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. ## How do I train this model? You can follow the [timm recipe scripts](../scripts) for training a new model afresh. ## Citation ```BibTeX @misc{lee2019energy, title={An Energy and GPU-Computation Efficient Backbone Network for Real-Time Object Detection}, author={Youngwan Lee and Joong-won Hwang and Sangrok Lee and Yuseok Bae and Jongyoul Park}, year={2019}, eprint={1904.09730}, archivePrefix={arXiv}, primaryClass={cs.CV} } ``` <!-- Type: model-index Collections: - Name: ESE VovNet Paper: Title: 'CenterMask : Real-Time Anchor-Free Instance Segmentation' URL: https://paperswithcode.com/paper/centermask-real-time-anchor-free-instance-1 Models: - Name: ese_vovnet19b_dw In Collection: ESE VovNet Metadata: FLOPs: 1711959904 Parameters: 6540000 File Size: 26243175 Architecture: - Batch Normalization - Convolution - Max Pooling - One-Shot Aggregation - ReLU Tasks: - Image Classification Training Data: - ImageNet ID: ese_vovnet19b_dw Layers: 19 Crop Pct: '0.875' Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/vovnet.py#L361 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/ese_vovnet19b_dw-a8741004.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 76.82% Top 5 Accuracy: 93.28% - Name: ese_vovnet39b In Collection: ESE VovNet Metadata: FLOPs: 9089259008 Parameters: 24570000 File Size: 98397138 Architecture: - Batch Normalization - Convolution - Max Pooling - One-Shot Aggregation - ReLU Tasks: - Image Classification Training Data: - ImageNet ID: ese_vovnet39b Layers: 39 Crop Pct: '0.875' Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/d8e69206be253892b2956341fea09fdebfaae4e3/timm/models/vovnet.py#L371 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/ese_vovnet39b-f912fe73.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 79.31% Top 5 Accuracy: 94.72% -->
pytorch-image-models/hfdocs/source/models/ese-vovnet.mdx/0
{ "file_path": "pytorch-image-models/hfdocs/source/models/ese-vovnet.mdx", "repo_id": "pytorch-image-models", "token_count": 1951 }
195
# MixNet **MixNet** is a type of convolutional neural network discovered via AutoML that utilises [MixConvs](https://paperswithcode.com/method/mixconv) instead of regular [depthwise convolutions](https://paperswithcode.com/method/depthwise-convolution). ## How do I use this model on an image? To load a pretrained model: ```py >>> import timm >>> model = timm.create_model('mixnet_l', pretrained=True) >>> model.eval() ``` To load and preprocess the image: ```py >>> import urllib >>> from PIL import Image >>> from timm.data import resolve_data_config >>> from timm.data.transforms_factory import create_transform >>> config = resolve_data_config({}, model=model) >>> transform = create_transform(**config) >>> url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg") >>> urllib.request.urlretrieve(url, filename) >>> img = Image.open(filename).convert('RGB') >>> tensor = transform(img).unsqueeze(0) # transform and add batch dimension ``` To get the model predictions: ```py >>> import torch >>> with torch.no_grad(): ... out = model(tensor) >>> probabilities = torch.nn.functional.softmax(out[0], dim=0) >>> print(probabilities.shape) >>> # prints: torch.Size([1000]) ``` To get the top-5 predictions class names: ```py >>> # Get imagenet class mappings >>> url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt", "imagenet_classes.txt") >>> urllib.request.urlretrieve(url, filename) >>> with open("imagenet_classes.txt", "r") as f: ... categories = [s.strip() for s in f.readlines()] >>> # Print top categories per image >>> top5_prob, top5_catid = torch.topk(probabilities, 5) >>> for i in range(top5_prob.size(0)): ... print(categories[top5_catid[i]], top5_prob[i].item()) >>> # prints class names and probabilities like: >>> # [('Samoyed', 0.6425196528434753), ('Pomeranian', 0.04062102362513542), ('keeshond', 0.03186424449086189), ('white wolf', 0.01739676296710968), ('Eskimo dog', 0.011717947199940681)] ``` Replace the model name with the variant you want to use, e.g. `mixnet_l`. You can find the IDs in the model summaries at the top of this page. To extract image features with this model, follow the [timm feature extraction examples](../feature_extraction), just change the name of the model you want to use. ## How do I finetune this model? You can finetune any of the pre-trained models just by changing the classifier (the last layer). ```py >>> model = timm.create_model('mixnet_l', pretrained=True, num_classes=NUM_FINETUNE_CLASSES) ``` To finetune on your own dataset, you have to write a training loop or adapt [timm's training script](https://github.com/rwightman/pytorch-image-models/blob/master/train.py) to use your dataset. ## How do I train this model? You can follow the [timm recipe scripts](../scripts) for training a new model afresh. ## Citation ```BibTeX @misc{tan2019mixconv, title={MixConv: Mixed Depthwise Convolutional Kernels}, author={Mingxing Tan and Quoc V. Le}, year={2019}, eprint={1907.09595}, archivePrefix={arXiv}, primaryClass={cs.CV} } ``` <!-- Type: model-index Collections: - Name: MixNet Paper: Title: 'MixConv: Mixed Depthwise Convolutional Kernels' URL: https://paperswithcode.com/paper/mixnet-mixed-depthwise-convolutional-kernels Models: - Name: mixnet_l In Collection: MixNet Metadata: FLOPs: 738671316 Parameters: 7330000 File Size: 29608232 Architecture: - Batch Normalization - Dense Connections - Dropout - Global Average Pooling - Grouped Convolution - MixConv - Squeeze-and-Excitation Block - Swish Tasks: - Image Classification Training Techniques: - MNAS Training Data: - ImageNet ID: mixnet_l Crop Pct: '0.875' Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/efficientnet.py#L1669 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/mixnet_l-5a9a2ed8.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 78.98% Top 5 Accuracy: 94.18% - Name: mixnet_m In Collection: MixNet Metadata: FLOPs: 454543374 Parameters: 5010000 File Size: 20298347 Architecture: - Batch Normalization - Dense Connections - Dropout - Global Average Pooling - Grouped Convolution - MixConv - Squeeze-and-Excitation Block - Swish Tasks: - Image Classification Training Techniques: - MNAS Training Data: - ImageNet ID: mixnet_m Crop Pct: '0.875' Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/efficientnet.py#L1660 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/mixnet_m-4647fc68.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 77.27% Top 5 Accuracy: 93.42% - Name: mixnet_s In Collection: MixNet Metadata: FLOPs: 321264910 Parameters: 4130000 File Size: 16727982 Architecture: - Batch Normalization - Dense Connections - Dropout - Global Average Pooling - Grouped Convolution - MixConv - Squeeze-and-Excitation Block - Swish Tasks: - Image Classification Training Techniques: - MNAS Training Data: - ImageNet ID: mixnet_s Crop Pct: '0.875' Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/efficientnet.py#L1651 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/mixnet_s-a907afbc.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 75.99% Top 5 Accuracy: 92.79% - Name: mixnet_xl In Collection: MixNet Metadata: FLOPs: 1195880424 Parameters: 11900000 File Size: 48001170 Architecture: - Batch Normalization - Dense Connections - Dropout - Global Average Pooling - Grouped Convolution - MixConv - Squeeze-and-Excitation Block - Swish Tasks: - Image Classification Training Techniques: - MNAS Training Data: - ImageNet ID: mixnet_xl Crop Pct: '0.875' Image Size: '224' Interpolation: bicubic Code: https://github.com/rwightman/pytorch-image-models/blob/9a25fdf3ad0414b4d66da443fe60ae0aa14edc84/timm/models/efficientnet.py#L1678 Weights: https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/mixnet_xl_ra-aac3c00c.pth Results: - Task: Image Classification Dataset: ImageNet Metrics: Top 1 Accuracy: 80.47% Top 5 Accuracy: 94.93% -->
pytorch-image-models/hfdocs/source/models/mixnet.mdx/0
{ "file_path": "pytorch-image-models/hfdocs/source/models/mixnet.mdx", "repo_id": "pytorch-image-models", "token_count": 2684 }
196
# Validation and Benchmark Results This folder contains validation and benchmark results for the models in this collection. Validation scores are currently only run for models with pretrained weights and ImageNet-1k heads, benchmark numbers are run for all. ## Datasets There are currently results for the ImageNet validation set and 5 additional test / label sets. The test set results include rank and top-1/top-5 differences from clean validation. For the "Real Labels", ImageNetV2, and Sketch test sets, the differences were calculated against the full 1000 class ImageNet-1k validation set. For both the Adversarial and Rendition sets, the differences were calculated against 'clean' runs on the ImageNet-1k validation set with the same 200 classes used in each test set respectively. ### ImageNet Validation - [`results-imagenet.csv`](results-imagenet.csv) The standard 50,000 image ImageNet-1k validation set. Model selection during training utilizes this validation set, so it is not a true test set. Question: Does anyone have the official ImageNet-1k test set classification labels now that challenges are done? * Source: http://image-net.org/challenges/LSVRC/2012/index * Paper: "ImageNet Large Scale Visual Recognition Challenge" - https://arxiv.org/abs/1409.0575 ### ImageNet-"Real Labels" - [`results-imagenet-real.csv`](results-imagenet-real.csv) The usual ImageNet-1k validation set with a fresh new set of labels intended to improve on mistakes in the original annotation process. * Source: https://github.com/google-research/reassessed-imagenet * Paper: "Are we done with ImageNet?" - https://arxiv.org/abs/2006.07159 ### ImageNetV2 Matched Frequency - [`results-imagenetv2-matched-frequency.csv`](results-imagenetv2-matched-frequency.csv) An ImageNet test set of 10,000 images sampled from new images roughly 10 years after the original. Care was taken to replicate the original ImageNet curation/sampling process. * Source: https://github.com/modestyachts/ImageNetV2 * Paper: "Do ImageNet Classifiers Generalize to ImageNet?" - https://arxiv.org/abs/1902.10811 ### ImageNet-Sketch - [`results-sketch.csv`](results-sketch.csv) 50,000 non photographic (or photos of such) images (sketches, doodles, mostly monochromatic) covering all 1000 ImageNet classes. * Source: https://github.com/HaohanWang/ImageNet-Sketch * Paper: "Learning Robust Global Representations by Penalizing Local Predictive Power" - https://arxiv.org/abs/1905.13549 ### ImageNet-Adversarial - [`results-imagenet-a.csv`](results-imagenet-a.csv) A collection of 7500 images covering 200 of the 1000 ImageNet classes. Images are naturally occurring adversarial examples that confuse typical ImageNet classifiers. This is a challenging dataset, your typical ResNet-50 will score 0% top-1. For clean validation with same 200 classes, see [`results-imagenet-a-clean.csv`](results-imagenet-a-clean.csv) * Source: https://github.com/hendrycks/natural-adv-examples * Paper: "Natural Adversarial Examples" - https://arxiv.org/abs/1907.07174 ### ImageNet-Rendition - [`results-imagenet-r.csv`](results-imagenet-r.csv) Renditions of 200 ImageNet classes resulting in 30,000 images for testing robustness. For clean validation with same 200 classes, see [`results-imagenet-r-clean.csv`](results-imagenet-r-clean.csv) * Source: https://github.com/hendrycks/imagenet-r * Paper: "The Many Faces of Robustness" - https://arxiv.org/abs/2006.16241 ### TODO * Explore adding a reduced version of ImageNet-C (Corruptions) and ImageNet-P (Perturbations) from https://github.com/hendrycks/robustness. The originals are huge and image size specific. ## Benchmark CSV files with a `model_benchmark` prefix include benchmark numbers for models on various accelerators with different precision. Currently only run on RTX 3090 w/ AMP for inference, I intend to add more in the future. ## Metadata CSV files with `model_metadata` prefix contain extra information about the source training, currently the pretraining dataset and technique (ie distillation, SSL, WSL, etc). Eventually I'd like to have metadata about augmentation, regularization, etc. but that will be a challenge to source consistently.
pytorch-image-models/results/README.md/0
{ "file_path": "pytorch-image-models/results/README.md", "repo_id": "pytorch-image-models", "token_count": 1173 }
197
from .auto_augment import RandAugment, AutoAugment, rand_augment_ops, auto_augment_policy,\ rand_augment_transform, auto_augment_transform from .config import resolve_data_config, resolve_model_data_config from .constants import * from .dataset import ImageDataset, IterableImageDataset, AugMixDataset from .dataset_factory import create_dataset from .dataset_info import DatasetInfo, CustomDatasetInfo from .imagenet_info import ImageNetInfo, infer_imagenet_subset from .loader import create_loader from .mixup import Mixup, FastCollateMixup from .readers import create_reader from .readers import get_img_extensions, is_img_extension, set_img_extensions, add_img_extensions, del_img_extensions from .real_labels import RealLabelsImagenet from .transforms import * from .transforms_factory import create_transform
pytorch-image-models/timm/data/__init__.py/0
{ "file_path": "pytorch-image-models/timm/data/__init__.py", "repo_id": "pytorch-image-models", "token_count": 256 }
198
import os import pickle def load_class_map(map_or_filename, root=''): if isinstance(map_or_filename, dict): assert dict, 'class_map dict must be non-empty' return map_or_filename class_map_path = map_or_filename if not os.path.exists(class_map_path): class_map_path = os.path.join(root, class_map_path) assert os.path.exists(class_map_path), 'Cannot locate specified class map file (%s)' % map_or_filename class_map_ext = os.path.splitext(map_or_filename)[-1].lower() if class_map_ext == '.txt': with open(class_map_path) as f: class_to_idx = {v.strip(): k for k, v in enumerate(f)} elif class_map_ext == '.pkl': with open(class_map_path, 'rb') as f: class_to_idx = pickle.load(f) else: assert False, f'Unsupported class map file extension ({class_map_ext}).' return class_to_idx
pytorch-image-models/timm/data/readers/class_map.py/0
{ "file_path": "pytorch-image-models/timm/data/readers/class_map.py", "repo_id": "pytorch-image-models", "token_count": 387 }
199
from .activations import * from .adaptive_avgmax_pool import \ adaptive_avgmax_pool2d, select_adaptive_pool2d, AdaptiveAvgMaxPool2d, SelectAdaptivePool2d from .attention2d import MultiQueryAttention2d, Attention2d, MultiQueryAttentionV2 from .attention_pool import AttentionPoolLatent from .attention_pool2d import AttentionPool2d, RotAttentionPool2d, RotaryEmbedding from .blur_pool import BlurPool2d, create_aa from .classifier import create_classifier, ClassifierHead, NormMlpClassifierHead, ClNormMlpClassifierHead from .cond_conv2d import CondConv2d, get_condconv_initializer from .config import is_exportable, is_scriptable, is_no_jit, use_fused_attn, \ set_exportable, set_scriptable, set_no_jit, set_layer_config, set_fused_attn from .conv2d_same import Conv2dSame, conv2d_same from .conv_bn_act import ConvNormAct, ConvNormActAa, ConvBnAct from .create_act import create_act_layer, get_act_layer, get_act_fn from .create_attn import get_attn, create_attn from .create_conv2d import create_conv2d from .create_norm import get_norm_layer, create_norm_layer from .create_norm_act import get_norm_act_layer, create_norm_act_layer, get_norm_act_layer from .drop import DropBlock2d, DropPath, drop_block_2d, drop_path from .eca import EcaModule, CecaModule, EfficientChannelAttn, CircularEfficientChannelAttn from .evo_norm import EvoNorm2dB0, EvoNorm2dB1, EvoNorm2dB2,\ EvoNorm2dS0, EvoNorm2dS0a, EvoNorm2dS1, EvoNorm2dS1a, EvoNorm2dS2, EvoNorm2dS2a from .fast_norm import is_fast_norm, set_fast_norm, fast_group_norm, fast_layer_norm from .filter_response_norm import FilterResponseNormTlu2d, FilterResponseNormAct2d from .format import Format, get_channel_dim, get_spatial_dim, nchw_to, nhwc_to from .gather_excite import GatherExcite from .global_context import GlobalContext from .grid import ndgrid, meshgrid from .helpers import to_ntuple, to_2tuple, to_3tuple, to_4tuple, make_divisible, extend_tuple from .hybrid_embed import HybridEmbed, HybridEmbedWithSize from .inplace_abn import InplaceAbn from .layer_scale import LayerScale, LayerScale2d from .linear import Linear from .mixed_conv2d import MixedConv2d from .mlp import Mlp, GluMlp, GatedMlp, SwiGLU, SwiGLUPacked, ConvMlp, GlobalResponseNormMlp from .non_local_attn import NonLocalAttn, BatNonLocalAttn from .norm import GroupNorm, GroupNorm1, LayerNorm, LayerNorm2d, RmsNorm from .norm_act import BatchNormAct2d, GroupNormAct, GroupNorm1Act, LayerNormAct, LayerNormAct2d,\ SyncBatchNormAct, convert_sync_batchnorm, FrozenBatchNormAct2d, freeze_batch_norm_2d, unfreeze_batch_norm_2d from .padding import get_padding, get_same_padding, pad_same from .patch_dropout import PatchDropout from .patch_embed import PatchEmbed, PatchEmbedWithSize, resample_patch_embed from .pool2d_same import AvgPool2dSame, create_pool2d from .pos_embed import resample_abs_pos_embed, resample_abs_pos_embed_nhwc from .pos_embed_rel import RelPosMlp, RelPosBias, RelPosBiasTf, gen_relative_position_index, gen_relative_log_coords, \ resize_rel_pos_bias_table, resize_rel_pos_bias_table_simple, resize_rel_pos_bias_table_levit from .pos_embed_sincos import pixel_freq_bands, freq_bands, build_sincos2d_pos_embed, build_fourier_pos_embed, \ build_rotary_pos_embed, apply_rot_embed, apply_rot_embed_cat, apply_rot_embed_list, apply_keep_indices_nlc, \ FourierEmbed, RotaryEmbedding, RotaryEmbeddingCat from .squeeze_excite import SEModule, SqueezeExcite, EffectiveSEModule, EffectiveSqueezeExcite from .selective_kernel import SelectiveKernel from .separable_conv import SeparableConv2d, SeparableConvNormAct from .space_to_depth import SpaceToDepth, DepthToSpace from .split_attn import SplitAttn from .split_batchnorm import SplitBatchNorm2d, convert_splitbn_model from .std_conv import StdConv2d, StdConv2dSame, ScaledStdConv2d, ScaledStdConv2dSame from .test_time_pool import TestTimePoolHead, apply_test_time_pool from .trace_utils import _assert, _float_to_int from .typing import LayerType, PadType from .weight_init import trunc_normal_, trunc_normal_tf_, variance_scaling_, lecun_normal_, \ init_weight_jax, init_weight_vit
pytorch-image-models/timm/layers/__init__.py/0
{ "file_path": "pytorch-image-models/timm/layers/__init__.py", "repo_id": "pytorch-image-models", "token_count": 1463 }
200
""" Attention Factory Hacked together by / Copyright 2021 Ross Wightman """ import torch from functools import partial from .bottleneck_attn import BottleneckAttn from .cbam import CbamModule, LightCbamModule from .eca import EcaModule, CecaModule from .gather_excite import GatherExcite from .global_context import GlobalContext from .halo_attn import HaloAttn from .lambda_layer import LambdaLayer from .non_local_attn import NonLocalAttn, BatNonLocalAttn from .selective_kernel import SelectiveKernel from .split_attn import SplitAttn from .squeeze_excite import SEModule, EffectiveSEModule def get_attn(attn_type): if isinstance(attn_type, torch.nn.Module): return attn_type module_cls = None if attn_type: if isinstance(attn_type, str): attn_type = attn_type.lower() # Lightweight attention modules (channel and/or coarse spatial). # Typically added to existing network architecture blocks in addition to existing convolutions. if attn_type == 'se': module_cls = SEModule elif attn_type == 'ese': module_cls = EffectiveSEModule elif attn_type == 'eca': module_cls = EcaModule elif attn_type == 'ecam': module_cls = partial(EcaModule, use_mlp=True) elif attn_type == 'ceca': module_cls = CecaModule elif attn_type == 'ge': module_cls = GatherExcite elif attn_type == 'gc': module_cls = GlobalContext elif attn_type == 'gca': module_cls = partial(GlobalContext, fuse_add=True, fuse_scale=False) elif attn_type == 'cbam': module_cls = CbamModule elif attn_type == 'lcbam': module_cls = LightCbamModule # Attention / attention-like modules w/ significant params # Typically replace some of the existing workhorse convs in a network architecture. # All of these accept a stride argument and can spatially downsample the input. elif attn_type == 'sk': module_cls = SelectiveKernel elif attn_type == 'splat': module_cls = SplitAttn # Self-attention / attention-like modules w/ significant compute and/or params # Typically replace some of the existing workhorse convs in a network architecture. # All of these accept a stride argument and can spatially downsample the input. elif attn_type == 'lambda': return LambdaLayer elif attn_type == 'bottleneck': return BottleneckAttn elif attn_type == 'halo': return HaloAttn elif attn_type == 'nl': module_cls = NonLocalAttn elif attn_type == 'bat': module_cls = BatNonLocalAttn # Woops! else: assert False, "Invalid attn module (%s)" % attn_type elif isinstance(attn_type, bool): if attn_type: module_cls = SEModule else: module_cls = attn_type return module_cls def create_attn(attn_type, channels, **kwargs): module_cls = get_attn(attn_type) if module_cls is not None: # NOTE: it's expected the first (positional) argument of all attention layers is the # input channels return module_cls(channels, **kwargs) return None
pytorch-image-models/timm/layers/create_attn.py/0
{ "file_path": "pytorch-image-models/timm/layers/create_attn.py", "repo_id": "pytorch-image-models", "token_count": 1588 }
201
""" Image to Patch Hybird Embedding Layer Hacked together by / Copyright 2020 Ross Wightman """ import logging import math from typing import List, Optional, Tuple, Union import torch from torch import nn as nn import torch.nn.functional as F from .format import Format, nchw_to from .helpers import to_2tuple from .patch_embed import resample_patch_embed _logger = logging.getLogger(__name__) class HybridEmbed(nn.Module): """ CNN Feature Map Embedding Extract feature map from CNN, flatten, project to embedding dim. """ output_fmt: Format dynamic_img_pad: torch.jit.Final[bool] def __init__( self, backbone: nn.Module, img_size: Union[int, Tuple[int, int]] = 224, patch_size: Union[int, Tuple[int, int]] = 1, feature_size: Optional[Union[int, Tuple[int, int]]] = None, feature_ratio: Optional[Union[int, Tuple[int, int]]] = None, in_chans: int = 3, embed_dim: int = 768, bias: bool = True, proj: bool = True, flatten: bool = True, output_fmt: Optional[str] = None, strict_img_size: bool = True, dynamic_img_pad: bool = False, ): super().__init__() assert isinstance(backbone, nn.Module) self.backbone = backbone self.in_chans = in_chans ( self.img_size, self.patch_size, self.feature_size, self.feature_ratio, self.feature_dim, self.grid_size, self.num_patches, ) = self._init_backbone( img_size=img_size, patch_size=patch_size, feature_size=feature_size, feature_ratio=feature_ratio, ) if output_fmt is not None: self.flatten = False self.output_fmt = Format(output_fmt) else: # flatten spatial dim and transpose to channels last, kept for bwd compat self.flatten = flatten self.output_fmt = Format.NCHW self.strict_img_size = strict_img_size self.dynamic_img_pad = dynamic_img_pad if not dynamic_img_pad: assert self.feature_size[0] % self.patch_size[0] == 0 and self.feature_size[1] % self.patch_size[1] == 0 if proj: self.proj = nn.Conv2d( self.feature_dim, embed_dim, kernel_size=patch_size, stride=patch_size, bias=bias, ) else: assert self.feature_dim == embed_dim, \ f'The feature dim ({self.feature_dim} must match embed dim ({embed_dim}) when projection disabled.' self.proj = nn.Identity() def _init_backbone( self, img_size: Union[int, Tuple[int, int]] = 224, patch_size: Union[int, Tuple[int, int]] = 1, feature_size: Optional[Union[int, Tuple[int, int]]] = None, feature_ratio: Optional[Union[int, Tuple[int, int]]] = None, feature_dim: Optional[int] = None, ): img_size = to_2tuple(img_size) patch_size = to_2tuple(patch_size) if feature_size is None: with torch.no_grad(): # NOTE Most reliable way of determining output dims is to run forward pass training = self.backbone.training if training: self.backbone.eval() o = self.backbone(torch.zeros(1, self.in_chans, img_size[0], img_size[1])) if isinstance(o, (list, tuple)): o = o[-1] # last feature if backbone outputs list/tuple of features feature_size = o.shape[-2:] feature_dim = o.shape[1] self.backbone.train(training) feature_ratio = tuple([s // f for s, f in zip(img_size, feature_size)]) else: feature_size = to_2tuple(feature_size) feature_ratio = to_2tuple(feature_ratio or 16) if feature_dim is None: if hasattr(self.backbone, 'feature_info'): feature_dim = self.backbone.feature_info.channels()[-1] else: feature_dim = self.backbone.num_features grid_size = tuple([f // p for f, p in zip(feature_size, patch_size)]) num_patches = grid_size[0] * grid_size[1] return img_size, patch_size, feature_size, feature_ratio, feature_dim, grid_size, num_patches def set_input_size( self, img_size: Optional[Union[int, Tuple[int, int]]] = None, patch_size: Optional[Union[int, Tuple[int, int]]] = None, feature_size: Optional[Union[int, Tuple[int, int]]] = None, feature_ratio: Optional[Union[int, Tuple[int, int]]] = None, feature_dim: Optional[int] = None, ): assert img_size is not None or patch_size is not None img_size = img_size or self.img_size new_patch_size = None if patch_size is not None: new_patch_size = to_2tuple(patch_size) if new_patch_size is not None and new_patch_size != self.patch_size: assert isinstance(self.proj, nn.Conv2d), 'HybridEmbed must have a projection layer to change patch size.' with torch.no_grad(): new_proj = nn.Conv2d( self.proj.in_channels, self.proj.out_channels, kernel_size=new_patch_size, stride=new_patch_size, bias=self.proj.bias is not None, ) new_proj.weight.copy_(resample_patch_embed(self.proj.weight, new_patch_size, verbose=True)) if self.proj.bias is not None: new_proj.bias.copy_(self.proj.bias) self.proj = new_proj patch_size = new_patch_size patch_size = patch_size or self.patch_size if img_size != self.img_size or patch_size != self.patch_size: ( self.img_size, self.patch_size, self.feature_size, self.feature_ratio, self.feature_dim, self.grid_size, self.num_patches, ) = self._init_backbone( img_size=img_size, patch_size=patch_size, feature_size=feature_size, feature_ratio=feature_ratio, feature_dim=feature_dim, ) def feat_ratio(self, as_scalar=True) -> Union[Tuple[int, int], int]: total_reduction = ( self.feature_ratio[0] * self.patch_size[0], self.feature_ratio[1] * self.patch_size[1] ) if as_scalar: return max(total_reduction) else: return total_reduction def dynamic_feat_size(self, img_size: Tuple[int, int]) -> Tuple[int, int]: """ Get feature grid size taking account dynamic padding and backbone network feat reduction """ feat_size = (img_size[0] // self.feature_ratio[0], img_size[1] // self.feature_ratio[1]) if self.dynamic_img_pad: return math.ceil(feat_size[0] / self.patch_size[0]), math.ceil(feat_size[1] / self.patch_size[1]) else: return feat_size[0] // self.patch_size[0], feat_size[1] // self.patch_size[1] @torch.jit.ignore def set_grad_checkpointing(self, enable: bool = True): if hasattr(self.backbone, 'set_grad_checkpointing'): self.backbone.set_grad_checkpointing(enable=enable) elif hasattr(self.backbone, 'grad_checkpointing'): self.backbone.grad_checkpointing = enable def forward(self, x): x = self.backbone(x) if isinstance(x, (list, tuple)): x = x[-1] # last feature if backbone outputs list/tuple of features _, _, H, W = x.shape if self.dynamic_img_pad: pad_h = (self.patch_size[0] - H % self.patch_size[0]) % self.patch_size[0] pad_w = (self.patch_size[1] - W % self.patch_size[1]) % self.patch_size[1] x = F.pad(x, (0, pad_w, 0, pad_h)) x = self.proj(x) if self.flatten: x = x.flatten(2).transpose(1, 2) # NCHW -> NLC elif self.output_fmt != Format.NCHW: x = nchw_to(x, self.output_fmt) return x class HybridEmbedWithSize(HybridEmbed): """ CNN Feature Map Embedding Extract feature map from CNN, flatten, project to embedding dim. """ def __init__( self, backbone: nn.Module, img_size: Union[int, Tuple[int, int]] = 224, patch_size: Union[int, Tuple[int, int]] = 1, feature_size: Optional[Union[int, Tuple[int, int]]] = None, feature_ratio: Optional[Union[int, Tuple[int, int]]] = None, in_chans: int = 3, embed_dim: int = 768, bias=True, proj=True, ): super().__init__( backbone=backbone, img_size=img_size, patch_size=patch_size, feature_size=feature_size, feature_ratio=feature_ratio, in_chans=in_chans, embed_dim=embed_dim, bias=bias, proj=proj, ) @torch.jit.ignore def set_grad_checkpointing(self, enable: bool = True): if hasattr(self.backbone, 'set_grad_checkpointing'): self.backbone.set_grad_checkpointing(enable=enable) elif hasattr(self.backbone, 'grad_checkpointing'): self.backbone.grad_checkpointing = enable def forward(self, x) -> Tuple[torch.Tensor, List[int]]: x = self.backbone(x) if isinstance(x, (list, tuple)): x = x[-1] # last feature if backbone outputs list/tuple of features x = self.proj(x) return x.flatten(2).transpose(1, 2), x.shape[-2:]
pytorch-image-models/timm/layers/hybrid_embed.py/0
{ "file_path": "pytorch-image-models/timm/layers/hybrid_embed.py", "repo_id": "pytorch-image-models", "token_count": 5059 }
202
""" AvgPool2d w/ Same Padding Hacked together by / Copyright 2020 Ross Wightman """ import torch import torch.nn as nn import torch.nn.functional as F from typing import List, Tuple, Optional from .helpers import to_2tuple from .padding import pad_same, get_padding_value def avg_pool2d_same(x, kernel_size: List[int], stride: List[int], padding: List[int] = (0, 0), ceil_mode: bool = False, count_include_pad: bool = True): # FIXME how to deal with count_include_pad vs not for external padding? x = pad_same(x, kernel_size, stride) return F.avg_pool2d(x, kernel_size, stride, (0, 0), ceil_mode, count_include_pad) class AvgPool2dSame(nn.AvgPool2d): """ Tensorflow like 'SAME' wrapper for 2D average pooling """ def __init__(self, kernel_size: int, stride=None, padding=0, ceil_mode=False, count_include_pad=True): kernel_size = to_2tuple(kernel_size) stride = to_2tuple(stride) super(AvgPool2dSame, self).__init__(kernel_size, stride, (0, 0), ceil_mode, count_include_pad) def forward(self, x): x = pad_same(x, self.kernel_size, self.stride) return F.avg_pool2d( x, self.kernel_size, self.stride, self.padding, self.ceil_mode, self.count_include_pad) def max_pool2d_same( x, kernel_size: List[int], stride: List[int], padding: List[int] = (0, 0), dilation: List[int] = (1, 1), ceil_mode: bool = False): x = pad_same(x, kernel_size, stride, value=-float('inf')) return F.max_pool2d(x, kernel_size, stride, (0, 0), dilation, ceil_mode) class MaxPool2dSame(nn.MaxPool2d): """ Tensorflow like 'SAME' wrapper for 2D max pooling """ def __init__(self, kernel_size: int, stride=None, padding=0, dilation=1, ceil_mode=False): kernel_size = to_2tuple(kernel_size) stride = to_2tuple(stride) dilation = to_2tuple(dilation) super(MaxPool2dSame, self).__init__(kernel_size, stride, (0, 0), dilation, ceil_mode) def forward(self, x): x = pad_same(x, self.kernel_size, self.stride, value=-float('inf')) return F.max_pool2d(x, self.kernel_size, self.stride, (0, 0), self.dilation, self.ceil_mode) def create_pool2d(pool_type, kernel_size, stride=None, **kwargs): stride = stride or kernel_size padding = kwargs.pop('padding', '') padding, is_dynamic = get_padding_value(padding, kernel_size, stride=stride, **kwargs) if is_dynamic: if pool_type == 'avg': return AvgPool2dSame(kernel_size, stride=stride, **kwargs) elif pool_type == 'max': return MaxPool2dSame(kernel_size, stride=stride, **kwargs) else: assert False, f'Unsupported pool type {pool_type}' else: if pool_type == 'avg': return nn.AvgPool2d(kernel_size, stride=stride, padding=padding, **kwargs) elif pool_type == 'max': return nn.MaxPool2d(kernel_size, stride=stride, padding=padding, **kwargs) else: assert False, f'Unsupported pool type {pool_type}'
pytorch-image-models/timm/layers/pool2d_same.py/0
{ "file_path": "pytorch-image-models/timm/layers/pool2d_same.py", "repo_id": "pytorch-image-models", "token_count": 1294 }
203
import torch import torch.nn as nn class AsymmetricLossMultiLabel(nn.Module): def __init__(self, gamma_neg=4, gamma_pos=1, clip=0.05, eps=1e-8, disable_torch_grad_focal_loss=False): super(AsymmetricLossMultiLabel, self).__init__() self.gamma_neg = gamma_neg self.gamma_pos = gamma_pos self.clip = clip self.disable_torch_grad_focal_loss = disable_torch_grad_focal_loss self.eps = eps def forward(self, x, y): """" Parameters ---------- x: input logits y: targets (multi-label binarized vector) """ # Calculating Probabilities x_sigmoid = torch.sigmoid(x) xs_pos = x_sigmoid xs_neg = 1 - x_sigmoid # Asymmetric Clipping if self.clip is not None and self.clip > 0: xs_neg = (xs_neg + self.clip).clamp(max=1) # Basic CE calculation los_pos = y * torch.log(xs_pos.clamp(min=self.eps)) los_neg = (1 - y) * torch.log(xs_neg.clamp(min=self.eps)) loss = los_pos + los_neg # Asymmetric Focusing if self.gamma_neg > 0 or self.gamma_pos > 0: if self.disable_torch_grad_focal_loss: torch.set_grad_enabled(False) pt0 = xs_pos * y pt1 = xs_neg * (1 - y) # pt = p if t > 0 else 1-p pt = pt0 + pt1 one_sided_gamma = self.gamma_pos * y + self.gamma_neg * (1 - y) one_sided_w = torch.pow(1 - pt, one_sided_gamma) if self.disable_torch_grad_focal_loss: torch.set_grad_enabled(True) loss *= one_sided_w return -loss.sum() class AsymmetricLossSingleLabel(nn.Module): def __init__(self, gamma_pos=1, gamma_neg=4, eps: float = 0.1, reduction='mean'): super(AsymmetricLossSingleLabel, self).__init__() self.eps = eps self.logsoftmax = nn.LogSoftmax(dim=-1) self.targets_classes = [] # prevent gpu repeated memory allocation self.gamma_pos = gamma_pos self.gamma_neg = gamma_neg self.reduction = reduction def forward(self, inputs, target, reduction=None): """" Parameters ---------- x: input logits y: targets (1-hot vector) """ num_classes = inputs.size()[-1] log_preds = self.logsoftmax(inputs) self.targets_classes = torch.zeros_like(inputs).scatter_(1, target.long().unsqueeze(1), 1) # ASL weights targets = self.targets_classes anti_targets = 1 - targets xs_pos = torch.exp(log_preds) xs_neg = 1 - xs_pos xs_pos = xs_pos * targets xs_neg = xs_neg * anti_targets asymmetric_w = torch.pow(1 - xs_pos - xs_neg, self.gamma_pos * targets + self.gamma_neg * anti_targets) log_preds = log_preds * asymmetric_w if self.eps > 0: # label smoothing self.targets_classes = self.targets_classes.mul(1 - self.eps).add(self.eps / num_classes) # loss calculation loss = - self.targets_classes.mul(log_preds) loss = loss.sum(dim=-1) if self.reduction == 'mean': loss = loss.mean() return loss
pytorch-image-models/timm/loss/asymmetric_loss.py/0
{ "file_path": "pytorch-image-models/timm/loss/asymmetric_loss.py", "repo_id": "pytorch-image-models", "token_count": 1616 }
204
""" DaViT: Dual Attention Vision Transformers As described in https://arxiv.org/abs/2204.03645 Input size invariant transformer architecture that combines channel and spacial attention in each block. The attention mechanisms used are linear in complexity. DaViT model defs and weights adapted from https://github.com/dingmyu/davit, original copyright below """ # Copyright (c) 2022 Mingyu Ding # All rights reserved. # This source code is licensed under the MIT license from functools import partial from typing import Optional, Tuple import torch import torch.nn as nn import torch.nn.functional as F from torch import Tensor from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import DropPath, to_2tuple, trunc_normal_, Mlp, LayerNorm2d, get_norm_layer, use_fused_attn from timm.layers import NormMlpClassifierHead, ClassifierHead from ._builder import build_model_with_cfg from ._features_fx import register_notrace_function from ._manipulate import checkpoint_seq from ._registry import generate_default_cfgs, register_model __all__ = ['DaVit'] class ConvPosEnc(nn.Module): def __init__(self, dim: int, k: int = 3, act: bool = False): super(ConvPosEnc, self).__init__() self.proj = nn.Conv2d( dim, dim, kernel_size=k, stride=1, padding=k // 2, groups=dim, ) self.act = nn.GELU() if act else nn.Identity() def forward(self, x: Tensor): feat = self.proj(x) x = x + self.act(feat) return x class Stem(nn.Module): """ Size-agnostic implementation of 2D image to patch embedding, allowing input size to be adjusted during model forward operation """ def __init__( self, in_chs=3, out_chs=96, stride=4, norm_layer=LayerNorm2d, ): super().__init__() stride = to_2tuple(stride) self.stride = stride self.in_chs = in_chs self.out_chs = out_chs assert stride[0] == 4 # only setup for stride==4 self.conv = nn.Conv2d( in_chs, out_chs, kernel_size=7, stride=stride, padding=3, ) self.norm = norm_layer(out_chs) def forward(self, x: Tensor): B, C, H, W = x.shape pad_r = (self.stride[1] - W % self.stride[1]) % self.stride[1] pad_b = (self.stride[0] - H % self.stride[0]) % self.stride[0] x = F.pad(x, (0, pad_r, 0, pad_b)) x = self.conv(x) x = self.norm(x) return x class Downsample(nn.Module): def __init__( self, in_chs, out_chs, kernel_size=3, norm_layer=LayerNorm2d, ): super().__init__() self.in_chs = in_chs self.out_chs = out_chs self.norm = norm_layer(in_chs) self.even_k = kernel_size % 2 == 0 self.conv = nn.Conv2d( in_chs, out_chs, kernel_size=kernel_size, stride=2, padding=0 if self.even_k else kernel_size // 2, ) def forward(self, x: Tensor): B, C, H, W = x.shape x = self.norm(x) if self.even_k: k_h, k_w = self.conv.kernel_size pad_r = (k_w - W % k_w) % k_w pad_b = (k_h - H % k_h) % k_h x = F.pad(x, (0, pad_r , 0, pad_b)) x = self.conv(x) return x class ChannelAttentionV2(nn.Module): def __init__(self, dim, num_heads=8, qkv_bias=True, dynamic_scale=True): super().__init__() self.groups = num_heads self.head_dim = dim // num_heads self.dynamic_scale = dynamic_scale self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.proj = nn.Linear(dim, dim) def forward(self, x): B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.groups, C // self.groups).permute(2, 0, 3, 1, 4) q, k, v = qkv.unbind(0) if self.dynamic_scale: q = q * N ** -0.5 else: q = q * self.head_dim ** -0.5 attn = q.transpose(-1, -2) @ k attn = attn.softmax(dim=-1) x = (attn @ v.transpose(-1, -2)).transpose(-1, -2) x = x.transpose(1, 2).reshape(B, N, C) x = self.proj(x) return x class ChannelAttention(nn.Module): def __init__(self, dim, num_heads=8, qkv_bias=False): super().__init__() self.num_heads = num_heads head_dim = dim // num_heads self.scale = head_dim ** -0.5 self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.proj = nn.Linear(dim, dim) def forward(self, x: Tensor): B, N, C = x.shape qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv.unbind(0) k = k * self.scale attn = k.transpose(-1, -2) @ v attn = attn.softmax(dim=-1) x = (attn @ q.transpose(-1, -2)).transpose(-1, -2) x = x.transpose(1, 2).reshape(B, N, C) x = self.proj(x) return x class ChannelBlock(nn.Module): def __init__( self, dim, num_heads, mlp_ratio=4., qkv_bias=False, drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, ffn=True, cpe_act=False, v2=False, ): super().__init__() self.cpe1 = ConvPosEnc(dim=dim, k=3, act=cpe_act) self.ffn = ffn self.norm1 = norm_layer(dim) attn_layer = ChannelAttentionV2 if v2 else ChannelAttention self.attn = attn_layer( dim, num_heads=num_heads, qkv_bias=qkv_bias, ) self.drop_path1 = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.cpe2 = ConvPosEnc(dim=dim, k=3, act=cpe_act) if self.ffn: self.norm2 = norm_layer(dim) self.mlp = Mlp( in_features=dim, hidden_features=int(dim * mlp_ratio), act_layer=act_layer, ) self.drop_path2 = DropPath(drop_path) if drop_path > 0. else nn.Identity() else: self.norm2 = None self.mlp = None self.drop_path2 = None def forward(self, x: Tensor): B, C, H, W = x.shape x = self.cpe1(x).flatten(2).transpose(1, 2) cur = self.norm1(x) cur = self.attn(cur) x = x + self.drop_path1(cur) x = self.cpe2(x.transpose(1, 2).view(B, C, H, W)) if self.mlp is not None: x = x.flatten(2).transpose(1, 2) x = x + self.drop_path2(self.mlp(self.norm2(x))) x = x.transpose(1, 2).view(B, C, H, W) return x def window_partition(x: Tensor, window_size: Tuple[int, int]): """ Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (num_windows*B, window_size, window_size, C) """ B, H, W, C = x.shape x = x.view(B, H // window_size[0], window_size[0], W // window_size[1], window_size[1], C) windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size[0], window_size[1], C) return windows @register_notrace_function # reason: int argument is a Proxy def window_reverse(windows: Tensor, window_size: Tuple[int, int], H: int, W: int): """ Args: windows: (num_windows*B, window_size, window_size, C) window_size (int): Window size H (int): Height of image W (int): Width of image Returns: x: (B, H, W, C) """ C = windows.shape[-1] x = windows.view(-1, H // window_size[0], W // window_size[1], window_size[0], window_size[1], C) x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, H, W, C) return x class WindowAttention(nn.Module): r""" Window based multi-head self attention (W-MSA) module with relative position bias. It supports both of shifted and non-shifted window. Args: dim (int): Number of input channels. window_size (tuple[int]): The height and width of the window. num_heads (int): Number of attention heads. qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True """ fused_attn: torch.jit.Final[bool] def __init__(self, dim, window_size, num_heads, qkv_bias=True): super().__init__() self.dim = dim self.window_size = window_size self.num_heads = num_heads head_dim = dim // num_heads self.scale = head_dim ** -0.5 self.fused_attn = use_fused_attn() self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) self.proj = nn.Linear(dim, dim) self.softmax = nn.Softmax(dim=-1) def forward(self, x: Tensor): B_, N, C = x.shape qkv = self.qkv(x).reshape(B_, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) q, k, v = qkv.unbind(0) if self.fused_attn: x = F.scaled_dot_product_attention(q, k, v) else: q = q * self.scale attn = (q @ k.transpose(-2, -1)) attn = self.softmax(attn) x = attn @ v x = x.transpose(1, 2).reshape(B_, N, C) x = self.proj(x) return x class SpatialBlock(nn.Module): r""" Windows Block. Args: dim (int): Number of input channels. num_heads (int): Number of attention heads. window_size (int): Window size. mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True drop_path (float, optional): Stochastic depth rate. Default: 0.0 act_layer (nn.Module, optional): Activation layer. Default: nn.GELU norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm """ def __init__( self, dim, num_heads, window_size=7, mlp_ratio=4., qkv_bias=True, drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, ffn=True, cpe_act=False, ): super().__init__() self.dim = dim self.ffn = ffn self.num_heads = num_heads self.window_size = to_2tuple(window_size) self.mlp_ratio = mlp_ratio self.cpe1 = ConvPosEnc(dim=dim, k=3, act=cpe_act) self.norm1 = norm_layer(dim) self.attn = WindowAttention( dim, self.window_size, num_heads=num_heads, qkv_bias=qkv_bias, ) self.drop_path1 = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.cpe2 = ConvPosEnc(dim=dim, k=3, act=cpe_act) if self.ffn: self.norm2 = norm_layer(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.mlp = Mlp( in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, ) self.drop_path2 = DropPath(drop_path) if drop_path > 0. else nn.Identity() else: self.norm2 = None self.mlp = None self.drop_path1 = None def forward(self, x: Tensor): B, C, H, W = x.shape shortcut = self.cpe1(x).flatten(2).transpose(1, 2) x = self.norm1(shortcut) x = x.view(B, H, W, C) pad_l = pad_t = 0 pad_r = (self.window_size[1] - W % self.window_size[1]) % self.window_size[1] pad_b = (self.window_size[0] - H % self.window_size[0]) % self.window_size[0] x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b)) _, Hp, Wp, _ = x.shape x_windows = window_partition(x, self.window_size) x_windows = x_windows.view(-1, self.window_size[0] * self.window_size[1], C) # W-MSA/SW-MSA attn_windows = self.attn(x_windows) # merge windows attn_windows = attn_windows.view(-1, self.window_size[0], self.window_size[1], C) x = window_reverse(attn_windows, self.window_size, Hp, Wp) # if pad_r > 0 or pad_b > 0: x = x[:, :H, :W, :].contiguous() x = x.view(B, H * W, C) x = shortcut + self.drop_path1(x) x = self.cpe2(x.transpose(1, 2).view(B, C, H, W)) if self.mlp is not None: x = x.flatten(2).transpose(1, 2) x = x + self.drop_path2(self.mlp(self.norm2(x))) x = x.transpose(1, 2).view(B, C, H, W) return x class DaVitStage(nn.Module): def __init__( self, in_chs, out_chs, depth=1, downsample=True, attn_types=('spatial', 'channel'), num_heads=3, window_size=7, mlp_ratio=4., qkv_bias=True, drop_path_rates=(0, 0), norm_layer=LayerNorm2d, norm_layer_cl=nn.LayerNorm, ffn=True, cpe_act=False, down_kernel_size=2, named_blocks=False, channel_attn_v2=False, ): super().__init__() self.grad_checkpointing = False # downsample embedding layer at the beginning of each stage if downsample: self.downsample = Downsample(in_chs, out_chs, kernel_size=down_kernel_size, norm_layer=norm_layer) else: self.downsample = nn.Identity() ''' repeating alternating attention blocks in each stage default: (spatial -> channel) x depth potential opportunity to integrate with a more general version of ByobNet/ByoaNet since the logic is similar ''' stage_blocks = [] for block_idx in range(depth): from collections import OrderedDict dual_attention_block = [] for attn_idx, attn_type in enumerate(attn_types): if attn_type == 'spatial': dual_attention_block.append(('spatial_block', SpatialBlock( dim=out_chs, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, drop_path=drop_path_rates[block_idx], norm_layer=norm_layer_cl, ffn=ffn, cpe_act=cpe_act, window_size=window_size, ))) elif attn_type == 'channel': dual_attention_block.append(('channel_block', ChannelBlock( dim=out_chs, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, drop_path=drop_path_rates[block_idx], norm_layer=norm_layer_cl, ffn=ffn, cpe_act=cpe_act, v2=channel_attn_v2, ))) if named_blocks: stage_blocks.append(nn.Sequential(OrderedDict(dual_attention_block))) else: stage_blocks.append(nn.Sequential(*[b[1] for b in dual_attention_block])) self.blocks = nn.Sequential(*stage_blocks) @torch.jit.ignore def set_grad_checkpointing(self, enable=True): self.grad_checkpointing = enable def forward(self, x: Tensor): x = self.downsample(x) if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint_seq(self.blocks, x) else: x = self.blocks(x) return x class DaVit(nn.Module): r""" DaViT A PyTorch implementation of `DaViT: Dual Attention Vision Transformers` - https://arxiv.org/abs/2204.03645 Supports arbitrary input sizes and pyramid feature extraction Args: in_chans (int): Number of input image channels. Default: 3 num_classes (int): Number of classes for classification head. Default: 1000 depths (tuple(int)): Number of blocks in each stage. Default: (1, 1, 3, 1) embed_dims (tuple(int)): Patch embedding dimension. Default: (96, 192, 384, 768) num_heads (tuple(int)): Number of attention heads in different layers. Default: (3, 6, 12, 24) window_size (int): Window size. Default: 7 mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4 qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True drop_path_rate (float): Stochastic depth rate. Default: 0.1 norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm. """ def __init__( self, in_chans=3, depths=(1, 1, 3, 1), embed_dims=(96, 192, 384, 768), num_heads=(3, 6, 12, 24), window_size=7, mlp_ratio=4, qkv_bias=True, norm_layer='layernorm2d', norm_layer_cl='layernorm', norm_eps=1e-5, attn_types=('spatial', 'channel'), ffn=True, cpe_act=False, down_kernel_size=2, channel_attn_v2=False, named_blocks=False, drop_rate=0., drop_path_rate=0., num_classes=1000, global_pool='avg', head_norm_first=False, ): super().__init__() num_stages = len(embed_dims) assert num_stages == len(num_heads) == len(depths) norm_layer = partial(get_norm_layer(norm_layer), eps=norm_eps) norm_layer_cl = partial(get_norm_layer(norm_layer_cl), eps=norm_eps) self.num_classes = num_classes self.num_features = self.head_hidden_size = embed_dims[-1] self.drop_rate = drop_rate self.grad_checkpointing = False self.feature_info = [] self.stem = Stem(in_chans, embed_dims[0], norm_layer=norm_layer) in_chs = embed_dims[0] dpr = [x.tolist() for x in torch.linspace(0, drop_path_rate, sum(depths)).split(depths)] stages = [] for stage_idx in range(num_stages): out_chs = embed_dims[stage_idx] stage = DaVitStage( in_chs, out_chs, depth=depths[stage_idx], downsample=stage_idx > 0, attn_types=attn_types, num_heads=num_heads[stage_idx], window_size=window_size, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, drop_path_rates=dpr[stage_idx], norm_layer=norm_layer, norm_layer_cl=norm_layer_cl, ffn=ffn, cpe_act=cpe_act, down_kernel_size=down_kernel_size, channel_attn_v2=channel_attn_v2, named_blocks=named_blocks, ) in_chs = out_chs stages.append(stage) self.feature_info += [dict(num_chs=out_chs, reduction=2, module=f'stages.{stage_idx}')] self.stages = nn.Sequential(*stages) # if head_norm_first == true, norm -> global pool -> fc ordering, like most other nets # otherwise pool -> norm -> fc, the default DaViT order, similar to ConvNeXt # FIXME generalize this structure to ClassifierHead if head_norm_first: self.norm_pre = norm_layer(self.num_features) self.head = ClassifierHead( self.num_features, num_classes, pool_type=global_pool, drop_rate=self.drop_rate, ) else: self.norm_pre = nn.Identity() self.head = NormMlpClassifierHead( self.num_features, num_classes, pool_type=global_pool, drop_rate=self.drop_rate, norm_layer=norm_layer, ) self.apply(self._init_weights) def _init_weights(self, m): if isinstance(m, nn.Linear): trunc_normal_(m.weight, std=.02) if isinstance(m, nn.Linear) and m.bias is not None: nn.init.constant_(m.bias, 0) @torch.jit.ignore def group_matcher(self, coarse=False): return dict( stem=r'^stem', # stem and embed blocks=r'^stages\.(\d+)' if coarse else [ (r'^stages\.(\d+).downsample', (0,)), (r'^stages\.(\d+)\.blocks\.(\d+)', None), (r'^norm_pre', (99999,)), ] ) @torch.jit.ignore def set_grad_checkpointing(self, enable=True): self.grad_checkpointing = enable for stage in self.stages: stage.set_grad_checkpointing(enable=enable) @torch.jit.ignore def get_classifier(self) -> nn.Module: return self.head.fc def reset_classifier(self, num_classes: int, global_pool: Optional[str] = None): self.head.reset(num_classes, global_pool) def forward_features(self, x): x = self.stem(x) if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint_seq(self.stages, x) else: x = self.stages(x) x = self.norm_pre(x) return x def forward_head(self, x, pre_logits: bool = False): return self.head(x, pre_logits=True) if pre_logits else self.head(x) def forward(self, x): x = self.forward_features(x) x = self.forward_head(x) return x def _convert_florence2(state_dict, model, prefix='vision_tower.'): import re out_dict = {} for k, v in state_dict.items(): if k.startswith(prefix): k = k.replace(prefix, '') else: continue k = re.sub(r'convs.([0-9]+)', r'stages.\1.downsample', k) k = re.sub(r'blocks.([0-9]+)', r'stages.\1.blocks', k) k = k.replace('downsample.proj', 'downsample.conv') k = k.replace('stages.0.downsample', 'stem') #k = k.replace('head.', 'head.fc.') #k = k.replace('norms.', 'head.norm.') k = k.replace('window_attn.norm.', 'norm1.') k = k.replace('window_attn.fn.', 'attn.') k = k.replace('channel_attn.norm.', 'norm1.') k = k.replace('channel_attn.fn.', 'attn.') k = k.replace('ffn.norm.', 'norm2.') k = k.replace('ffn.fn.net.', 'mlp.') k = k.replace('conv1.fn.dw', 'cpe1.proj') k = k.replace('conv2.fn.dw', 'cpe2.proj') out_dict[k] = v return out_dict def checkpoint_filter_fn(state_dict, model): """ Remap MSFT checkpoints -> timm """ if 'head.fc.weight' in state_dict: return state_dict # non-MSFT checkpoint if 'state_dict' in state_dict: state_dict = state_dict['state_dict'] if 'vision_tower.convs.0.proj.weight' in state_dict: return _convert_florence2(state_dict, model) import re out_dict = {} for k, v in state_dict.items(): k = re.sub(r'patch_embeds.([0-9]+)', r'stages.\1.downsample', k) k = re.sub(r'main_blocks.([0-9]+)', r'stages.\1.blocks', k) k = k.replace('downsample.proj', 'downsample.conv') k = k.replace('stages.0.downsample', 'stem') k = k.replace('head.', 'head.fc.') k = k.replace('norms.', 'head.norm.') k = k.replace('cpe.0', 'cpe1') k = k.replace('cpe.1', 'cpe2') out_dict[k] = v return out_dict def _create_davit(variant, pretrained=False, **kwargs): default_out_indices = tuple(i for i, _ in enumerate(kwargs.get('depths', (1, 1, 3, 1)))) out_indices = kwargs.pop('out_indices', default_out_indices) strict = True if variant.endswith('_fl'): # FIXME cleaner approach to missing head norm? strict = False model = build_model_with_cfg( DaVit, variant, pretrained, pretrained_filter_fn=checkpoint_filter_fn, feature_cfg=dict(flatten_sequential=True, out_indices=out_indices), pretrained_strict=strict, **kwargs) return model def _cfg(url='', **kwargs): return { 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': (7, 7), 'crop_pct': 0.95, 'interpolation': 'bicubic', 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD, 'first_conv': 'stem.conv', 'classifier': 'head.fc', **kwargs } # TODO contact authors to get larger pretrained models default_cfgs = generate_default_cfgs({ # official microsoft weights from https://github.com/dingmyu/davit 'davit_tiny.msft_in1k': _cfg( hf_hub_id='timm/'), 'davit_small.msft_in1k': _cfg( hf_hub_id='timm/'), 'davit_base.msft_in1k': _cfg( hf_hub_id='timm/'), 'davit_large': _cfg(), 'davit_huge': _cfg(), 'davit_giant': _cfg(), 'davit_base_fl.msft_florence2': _cfg( hf_hub_id='microsoft/Florence-2-base', num_classes=0, input_size=(3, 768, 768)), 'davit_huge_fl.msft_florence2': _cfg( hf_hub_id='microsoft/Florence-2-large', num_classes=0, input_size=(3, 768, 768)), }) @register_model def davit_tiny(pretrained=False, **kwargs) -> DaVit: model_args = dict(depths=(1, 1, 3, 1), embed_dims=(96, 192, 384, 768), num_heads=(3, 6, 12, 24)) return _create_davit('davit_tiny', pretrained=pretrained, **dict(model_args, **kwargs)) @register_model def davit_small(pretrained=False, **kwargs) -> DaVit: model_args = dict(depths=(1, 1, 9, 1), embed_dims=(96, 192, 384, 768), num_heads=(3, 6, 12, 24)) return _create_davit('davit_small', pretrained=pretrained, **dict(model_args, **kwargs)) @register_model def davit_base(pretrained=False, **kwargs) -> DaVit: model_args = dict(depths=(1, 1, 9, 1), embed_dims=(128, 256, 512, 1024), num_heads=(4, 8, 16, 32)) return _create_davit('davit_base', pretrained=pretrained, **dict(model_args, **kwargs)) @register_model def davit_large(pretrained=False, **kwargs) -> DaVit: model_args = dict(depths=(1, 1, 9, 1), embed_dims=(192, 384, 768, 1536), num_heads=(6, 12, 24, 48)) return _create_davit('davit_large', pretrained=pretrained, **dict(model_args, **kwargs)) @register_model def davit_huge(pretrained=False, **kwargs) -> DaVit: model_args = dict(depths=(1, 1, 9, 1), embed_dims=(256, 512, 1024, 2048), num_heads=(8, 16, 32, 64)) return _create_davit('davit_huge', pretrained=pretrained, **dict(model_args, **kwargs)) @register_model def davit_giant(pretrained=False, **kwargs) -> DaVit: model_args = dict(depths=(1, 1, 12, 3), embed_dims=(384, 768, 1536, 3072), num_heads=(12, 24, 48, 96)) return _create_davit('davit_giant', pretrained=pretrained, **dict(model_args, **kwargs)) @register_model def davit_base_fl(pretrained=False, **kwargs) -> DaVit: model_args = dict( depths=(1, 1, 9, 1), embed_dims=(128, 256, 512, 1024), num_heads=(4, 8, 16, 32), window_size=12, down_kernel_size=3, channel_attn_v2=True, named_blocks=True, ) return _create_davit('davit_base_fl', pretrained=pretrained, **dict(model_args, **kwargs)) @register_model def davit_huge_fl(pretrained=False, **kwargs) -> DaVit: # NOTE: huge image tower used in 'large' Florence2 model model_args = dict( depths=(1, 1, 9, 1), embed_dims=(256, 512, 1024, 2048), num_heads=(8, 16, 32, 64), window_size=12, down_kernel_size=3, channel_attn_v2=True, named_blocks=True, ) return _create_davit('davit_huge_fl', pretrained=pretrained, **dict(model_args, **kwargs))
pytorch-image-models/timm/models/davit.py/0
{ "file_path": "pytorch-image-models/timm/models/davit.py", "repo_id": "pytorch-image-models", "token_count": 14210 }
205
""" MaxVit and CoAtNet Vision Transformer - CNN Hybrids in PyTorch This is a from-scratch implementation of both CoAtNet and MaxVit in PyTorch. 99% of the implementation was done from papers, however last minute some adjustments were made based on the (as yet unfinished?) public code release https://github.com/google-research/maxvit There are multiple sets of models defined for both architectures. Typically, names with a `_rw` suffix are my own original configs prior to referencing https://github.com/google-research/maxvit. These configs work well and appear to be a bit faster / lower resource than the paper. The models without extra prefix / suffix' (coatnet_0_224, maxvit_tiny_224, etc), are intended to match paper, BUT, without any official pretrained weights it's difficult to confirm a 100% match. Papers: MaxViT: Multi-Axis Vision Transformer - https://arxiv.org/abs/2204.01697 @article{tu2022maxvit, title={MaxViT: Multi-Axis Vision Transformer}, author={Tu, Zhengzhong and Talebi, Hossein and Zhang, Han and Yang, Feng and Milanfar, Peyman and Bovik, Alan and Li, Yinxiao}, journal={ECCV}, year={2022}, } CoAtNet: Marrying Convolution and Attention for All Data Sizes - https://arxiv.org/abs/2106.04803 @article{DBLP:journals/corr/abs-2106-04803, author = {Zihang Dai and Hanxiao Liu and Quoc V. Le and Mingxing Tan}, title = {CoAtNet: Marrying Convolution and Attention for All Data Sizes}, journal = {CoRR}, volume = {abs/2106.04803}, year = {2021} } Hacked together by / Copyright 2022, Ross Wightman """ import math from collections import OrderedDict from dataclasses import dataclass, replace, field from functools import partial from typing import Callable, Optional, Union, Tuple, List import torch from torch import nn from torch.jit import Final from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import Mlp, ConvMlp, DropPath, LayerNorm, ClassifierHead, NormMlpClassifierHead from timm.layers import create_attn, get_act_layer, get_norm_layer, get_norm_act_layer, create_conv2d, create_pool2d from timm.layers import trunc_normal_tf_, to_2tuple, extend_tuple, make_divisible, _assert from timm.layers import RelPosMlp, RelPosBias, RelPosBiasTf, use_fused_attn, resize_rel_pos_bias_table from ._builder import build_model_with_cfg from ._features import feature_take_indices from ._features_fx import register_notrace_function from ._manipulate import named_apply, checkpoint_seq from ._registry import generate_default_cfgs, register_model __all__ = ['MaxxVitCfg', 'MaxxVitConvCfg', 'MaxxVitTransformerCfg', 'MaxxVit'] @dataclass class MaxxVitTransformerCfg: dim_head: int = 32 head_first: bool = True # head ordering in qkv channel dim expand_ratio: float = 4.0 expand_first: bool = True shortcut_bias: bool = True attn_bias: bool = True attn_drop: float = 0. proj_drop: float = 0. pool_type: str = 'avg2' rel_pos_type: str = 'bias' rel_pos_dim: int = 512 # for relative position types w/ MLP partition_ratio: int = 32 window_size: Optional[Tuple[int, int]] = None grid_size: Optional[Tuple[int, int]] = None no_block_attn: bool = False # disable window block attention for maxvit (ie only grid) use_nchw_attn: bool = False # for MaxViT variants (not used for CoAt), keep tensors in NCHW order init_values: Optional[float] = None act_layer: str = 'gelu' norm_layer: str = 'layernorm2d' norm_layer_cl: str = 'layernorm' norm_eps: float = 1e-6 def __post_init__(self): if self.grid_size is not None: self.grid_size = to_2tuple(self.grid_size) if self.window_size is not None: self.window_size = to_2tuple(self.window_size) if self.grid_size is None: self.grid_size = self.window_size @dataclass class MaxxVitConvCfg: block_type: str = 'mbconv' expand_ratio: float = 4.0 expand_output: bool = True # calculate expansion channels from output (vs input chs) kernel_size: int = 3 group_size: int = 1 # 1 == depthwise pre_norm_act: bool = False # activation after pre-norm output_bias: bool = True # bias for shortcut + final 1x1 projection conv stride_mode: str = 'dw' # stride done via one of 'pool', '1x1', 'dw' pool_type: str = 'avg2' downsample_pool_type: str = 'avg2' padding: str = '' attn_early: bool = False # apply attn between conv2 and norm2, instead of after norm2 attn_layer: str = 'se' attn_act_layer: str = 'silu' attn_ratio: float = 0.25 init_values: Optional[float] = 1e-6 # for ConvNeXt block, ignored by MBConv act_layer: str = 'gelu' norm_layer: str = '' norm_layer_cl: str = '' norm_eps: Optional[float] = None def __post_init__(self): # mbconv vs convnext blocks have different defaults, set in post_init to avoid explicit config args assert self.block_type in ('mbconv', 'convnext') use_mbconv = self.block_type == 'mbconv' if not self.norm_layer: self.norm_layer = 'batchnorm2d' if use_mbconv else 'layernorm2d' if not self.norm_layer_cl and not use_mbconv: self.norm_layer_cl = 'layernorm' if self.norm_eps is None: self.norm_eps = 1e-5 if use_mbconv else 1e-6 self.downsample_pool_type = self.downsample_pool_type or self.pool_type @dataclass class MaxxVitCfg: embed_dim: Tuple[int, ...] = (96, 192, 384, 768) depths: Tuple[int, ...] = (2, 3, 5, 2) block_type: Tuple[Union[str, Tuple[str, ...]], ...] = ('C', 'C', 'T', 'T') stem_width: Union[int, Tuple[int, int]] = 64 stem_bias: bool = False conv_cfg: MaxxVitConvCfg = field(default_factory=MaxxVitConvCfg) transformer_cfg: MaxxVitTransformerCfg = field(default_factory=MaxxVitTransformerCfg) head_hidden_size: int = None weight_init: str = 'vit_eff' class Attention2d(nn.Module): fused_attn: Final[bool] """ multi-head attention for 2D NCHW tensors""" def __init__( self, dim: int, dim_out: Optional[int] = None, dim_head: int = 32, bias: bool = True, expand_first: bool = True, head_first: bool = True, rel_pos_cls: Callable = None, attn_drop: float = 0., proj_drop: float = 0. ): super().__init__() dim_out = dim_out or dim dim_attn = dim_out if expand_first else dim self.num_heads = dim_attn // dim_head self.dim_head = dim_head self.head_first = head_first self.scale = dim_head ** -0.5 self.fused_attn = use_fused_attn() self.qkv = nn.Conv2d(dim, dim_attn * 3, 1, bias=bias) self.rel_pos = rel_pos_cls(num_heads=self.num_heads) if rel_pos_cls else None self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Conv2d(dim_attn, dim_out, 1, bias=bias) self.proj_drop = nn.Dropout(proj_drop) def forward(self, x, shared_rel_pos: Optional[torch.Tensor] = None): B, C, H, W = x.shape if self.head_first: q, k, v = self.qkv(x).view(B, self.num_heads, self.dim_head * 3, -1).chunk(3, dim=2) else: q, k, v = self.qkv(x).reshape(B, 3, self.num_heads, self.dim_head, -1).unbind(1) if self.fused_attn: attn_bias = None if self.rel_pos is not None: attn_bias = self.rel_pos.get_bias() elif shared_rel_pos is not None: attn_bias = shared_rel_pos x = torch.nn.functional.scaled_dot_product_attention( q.transpose(-1, -2).contiguous(), k.transpose(-1, -2).contiguous(), v.transpose(-1, -2).contiguous(), attn_mask=attn_bias, dropout_p=self.attn_drop.p if self.training else 0., ).transpose(-1, -2).reshape(B, -1, H, W) else: q = q * self.scale attn = q.transpose(-2, -1) @ k if self.rel_pos is not None: attn = self.rel_pos(attn) elif shared_rel_pos is not None: attn = attn + shared_rel_pos attn = attn.softmax(dim=-1) attn = self.attn_drop(attn) x = (v @ attn.transpose(-2, -1)).view(B, -1, H, W) x = self.proj(x) x = self.proj_drop(x) return x class AttentionCl(nn.Module): """ Channels-last multi-head attention (B, ..., C) """ fused_attn: Final[bool] def __init__( self, dim: int, dim_out: Optional[int] = None, dim_head: int = 32, bias: bool = True, expand_first: bool = True, head_first: bool = True, rel_pos_cls: Callable = None, attn_drop: float = 0., proj_drop: float = 0. ): super().__init__() dim_out = dim_out or dim dim_attn = dim_out if expand_first and dim_out > dim else dim assert dim_attn % dim_head == 0, 'attn dim should be divisible by head_dim' self.num_heads = dim_attn // dim_head self.dim_head = dim_head self.head_first = head_first self.scale = dim_head ** -0.5 self.fused_attn = use_fused_attn() self.qkv = nn.Linear(dim, dim_attn * 3, bias=bias) self.rel_pos = rel_pos_cls(num_heads=self.num_heads) if rel_pos_cls else None self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim_attn, dim_out, bias=bias) self.proj_drop = nn.Dropout(proj_drop) def forward(self, x, shared_rel_pos: Optional[torch.Tensor] = None): B = x.shape[0] restore_shape = x.shape[:-1] if self.head_first: q, k, v = self.qkv(x).view(B, -1, self.num_heads, self.dim_head * 3).transpose(1, 2).chunk(3, dim=3) else: q, k, v = self.qkv(x).reshape(B, -1, 3, self.num_heads, self.dim_head).transpose(1, 3).unbind(2) if self.fused_attn: attn_bias = None if self.rel_pos is not None: attn_bias = self.rel_pos.get_bias() elif shared_rel_pos is not None: attn_bias = shared_rel_pos x = torch.nn.functional.scaled_dot_product_attention( q, k, v, attn_mask=attn_bias, dropout_p=self.attn_drop.p if self.training else 0., ) else: q = q * self.scale attn = q @ k.transpose(-2, -1) if self.rel_pos is not None: attn = self.rel_pos(attn, shared_rel_pos=shared_rel_pos) elif shared_rel_pos is not None: attn = attn + shared_rel_pos attn = attn.softmax(dim=-1) attn = self.attn_drop(attn) x = attn @ v x = x.transpose(1, 2).reshape(restore_shape + (-1,)) x = self.proj(x) x = self.proj_drop(x) return x class LayerScale(nn.Module): def __init__(self, dim, init_values=1e-5, inplace=False): super().__init__() self.inplace = inplace self.gamma = nn.Parameter(init_values * torch.ones(dim)) def forward(self, x): gamma = self.gamma return x.mul_(gamma) if self.inplace else x * gamma class LayerScale2d(nn.Module): def __init__(self, dim, init_values=1e-5, inplace=False): super().__init__() self.inplace = inplace self.gamma = nn.Parameter(init_values * torch.ones(dim)) def forward(self, x): gamma = self.gamma.view(1, -1, 1, 1) return x.mul_(gamma) if self.inplace else x * gamma class Downsample2d(nn.Module): """ A downsample pooling module supporting several maxpool and avgpool modes * 'max' - MaxPool2d w/ kernel_size 3, stride 2, padding 1 * 'max2' - MaxPool2d w/ kernel_size = stride = 2 * 'avg' - AvgPool2d w/ kernel_size 3, stride 2, padding 1 * 'avg2' - AvgPool2d w/ kernel_size = stride = 2 """ def __init__( self, dim: int, dim_out: int, pool_type: str = 'avg2', padding: str = '', bias: bool = True, ): super().__init__() assert pool_type in ('max', 'max2', 'avg', 'avg2') if pool_type == 'max': self.pool = create_pool2d('max', kernel_size=3, stride=2, padding=padding or 1) elif pool_type == 'max2': self.pool = create_pool2d('max', 2, padding=padding or 0) # kernel_size == stride == 2 elif pool_type == 'avg': self.pool = create_pool2d( 'avg', kernel_size=3, stride=2, count_include_pad=False, padding=padding or 1) else: self.pool = create_pool2d('avg', 2, padding=padding or 0) if dim != dim_out: self.expand = nn.Conv2d(dim, dim_out, 1, bias=bias) else: self.expand = nn.Identity() def forward(self, x): x = self.pool(x) # spatial downsample x = self.expand(x) # expand chs return x def _init_transformer(module, name, scheme=''): if isinstance(module, (nn.Conv2d, nn.Linear)): if scheme == 'normal': nn.init.normal_(module.weight, std=.02) if module.bias is not None: nn.init.zeros_(module.bias) elif scheme == 'trunc_normal': trunc_normal_tf_(module.weight, std=.02) if module.bias is not None: nn.init.zeros_(module.bias) elif scheme == 'xavier_normal': nn.init.xavier_normal_(module.weight) if module.bias is not None: nn.init.zeros_(module.bias) else: # vit like nn.init.xavier_uniform_(module.weight) if module.bias is not None: if 'mlp' in name: nn.init.normal_(module.bias, std=1e-6) else: nn.init.zeros_(module.bias) class TransformerBlock2d(nn.Module): """ Transformer block with 2D downsampling '2D' NCHW tensor layout Some gains can be seen on GPU using a 1D / CL block, BUT w/ the need to switch back/forth to NCHW for spatial pooling, the benefit is minimal so ended up using just this variant for CoAt configs. This impl was faster on TPU w/ PT XLA than the 1D experiment. """ def __init__( self, dim: int, dim_out: int, stride: int = 1, rel_pos_cls: Callable = None, cfg: MaxxVitTransformerCfg = MaxxVitTransformerCfg(), drop_path: float = 0., ): super().__init__() norm_layer = partial(get_norm_layer(cfg.norm_layer), eps=cfg.norm_eps) act_layer = get_act_layer(cfg.act_layer) if stride == 2: self.shortcut = Downsample2d(dim, dim_out, pool_type=cfg.pool_type, bias=cfg.shortcut_bias) self.norm1 = nn.Sequential(OrderedDict([ ('norm', norm_layer(dim)), ('down', Downsample2d(dim, dim, pool_type=cfg.pool_type)), ])) else: assert dim == dim_out self.shortcut = nn.Identity() self.norm1 = norm_layer(dim) self.attn = Attention2d( dim, dim_out, dim_head=cfg.dim_head, expand_first=cfg.expand_first, bias=cfg.attn_bias, rel_pos_cls=rel_pos_cls, attn_drop=cfg.attn_drop, proj_drop=cfg.proj_drop ) self.ls1 = LayerScale2d(dim_out, init_values=cfg.init_values) if cfg.init_values else nn.Identity() self.drop_path1 = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.norm2 = norm_layer(dim_out) self.mlp = ConvMlp( in_features=dim_out, hidden_features=int(dim_out * cfg.expand_ratio), act_layer=act_layer, drop=cfg.proj_drop) self.ls2 = LayerScale2d(dim_out, init_values=cfg.init_values) if cfg.init_values else nn.Identity() self.drop_path2 = DropPath(drop_path) if drop_path > 0. else nn.Identity() def init_weights(self, scheme=''): named_apply(partial(_init_transformer, scheme=scheme), self) def forward(self, x, shared_rel_pos: Optional[torch.Tensor] = None): x = self.shortcut(x) + self.drop_path1(self.ls1(self.attn(self.norm1(x), shared_rel_pos=shared_rel_pos))) x = x + self.drop_path2(self.ls2(self.mlp(self.norm2(x)))) return x def _init_conv(module, name, scheme=''): if isinstance(module, nn.Conv2d): if scheme == 'normal': nn.init.normal_(module.weight, std=.02) if module.bias is not None: nn.init.zeros_(module.bias) elif scheme == 'trunc_normal': trunc_normal_tf_(module.weight, std=.02) if module.bias is not None: nn.init.zeros_(module.bias) elif scheme == 'xavier_normal': nn.init.xavier_normal_(module.weight) if module.bias is not None: nn.init.zeros_(module.bias) else: # efficientnet like fan_out = module.kernel_size[0] * module.kernel_size[1] * module.out_channels fan_out //= module.groups nn.init.normal_(module.weight, 0, math.sqrt(2.0 / fan_out)) if module.bias is not None: nn.init.zeros_(module.bias) def num_groups(group_size, channels): if not group_size: # 0 or None return 1 # normal conv with 1 group else: # NOTE group_size == 1 -> depthwise conv assert channels % group_size == 0 return channels // group_size class MbConvBlock(nn.Module): """ Pre-Norm Conv Block - 1x1 - kxk - 1x1, w/ inverted bottleneck (expand) """ def __init__( self, in_chs: int, out_chs: int, stride: int = 1, dilation: Tuple[int, int] = (1, 1), cfg: MaxxVitConvCfg = MaxxVitConvCfg(), drop_path: float = 0. ): super(MbConvBlock, self).__init__() norm_act_layer = partial(get_norm_act_layer(cfg.norm_layer, cfg.act_layer), eps=cfg.norm_eps) mid_chs = make_divisible((out_chs if cfg.expand_output else in_chs) * cfg.expand_ratio) groups = num_groups(cfg.group_size, mid_chs) if stride == 2: self.shortcut = Downsample2d( in_chs, out_chs, pool_type=cfg.pool_type, bias=cfg.output_bias, padding=cfg.padding) else: self.shortcut = nn.Identity() assert cfg.stride_mode in ('pool', '1x1', 'dw') stride_pool, stride_1, stride_2 = 1, 1, 1 if cfg.stride_mode == 'pool': # NOTE this is not described in paper, experiment to find faster option that doesn't stride in 1x1 stride_pool, dilation_2 = stride, dilation[1] # FIXME handle dilation of avg pool elif cfg.stride_mode == '1x1': # NOTE I don't like this option described in paper, 1x1 w/ stride throws info away stride_1, dilation_2 = stride, dilation[1] else: stride_2, dilation_2 = stride, dilation[0] self.pre_norm = norm_act_layer(in_chs, apply_act=cfg.pre_norm_act) if stride_pool > 1: self.down = Downsample2d(in_chs, in_chs, pool_type=cfg.downsample_pool_type, padding=cfg.padding) else: self.down = nn.Identity() self.conv1_1x1 = create_conv2d(in_chs, mid_chs, 1, stride=stride_1) self.norm1 = norm_act_layer(mid_chs) self.conv2_kxk = create_conv2d( mid_chs, mid_chs, cfg.kernel_size, stride=stride_2, dilation=dilation_2, groups=groups, padding=cfg.padding) attn_kwargs = {} if isinstance(cfg.attn_layer, str): if cfg.attn_layer == 'se' or cfg.attn_layer == 'eca': attn_kwargs['act_layer'] = cfg.attn_act_layer attn_kwargs['rd_channels'] = int(cfg.attn_ratio * (out_chs if cfg.expand_output else mid_chs)) # two different orderings for SE and norm2 (due to some weights and trials using SE before norm2) if cfg.attn_early: self.se_early = create_attn(cfg.attn_layer, mid_chs, **attn_kwargs) self.norm2 = norm_act_layer(mid_chs) self.se = None else: self.se_early = None self.norm2 = norm_act_layer(mid_chs) self.se = create_attn(cfg.attn_layer, mid_chs, **attn_kwargs) self.conv3_1x1 = create_conv2d(mid_chs, out_chs, 1, bias=cfg.output_bias) self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() def init_weights(self, scheme=''): named_apply(partial(_init_conv, scheme=scheme), self) def forward(self, x): shortcut = self.shortcut(x) x = self.pre_norm(x) x = self.down(x) # 1x1 expansion conv & norm-act x = self.conv1_1x1(x) x = self.norm1(x) # depthwise / grouped 3x3 conv w/ SE (or other) channel attention & norm-act x = self.conv2_kxk(x) if self.se_early is not None: x = self.se_early(x) x = self.norm2(x) if self.se is not None: x = self.se(x) # 1x1 linear projection to output width x = self.conv3_1x1(x) x = self.drop_path(x) + shortcut return x class ConvNeXtBlock(nn.Module): """ ConvNeXt Block """ def __init__( self, in_chs: int, out_chs: Optional[int] = None, kernel_size: int = 7, stride: int = 1, dilation: Tuple[int, int] = (1, 1), cfg: MaxxVitConvCfg = MaxxVitConvCfg(), conv_mlp: bool = True, drop_path: float = 0. ): super().__init__() out_chs = out_chs or in_chs act_layer = get_act_layer(cfg.act_layer) if conv_mlp: norm_layer = partial(get_norm_layer(cfg.norm_layer), eps=cfg.norm_eps) mlp_layer = ConvMlp else: assert 'layernorm' in cfg.norm_layer norm_layer = LayerNorm mlp_layer = Mlp self.use_conv_mlp = conv_mlp if stride == 2: self.shortcut = Downsample2d(in_chs, out_chs) elif in_chs != out_chs: self.shortcut = nn.Conv2d(in_chs, out_chs, kernel_size=1, bias=cfg.output_bias) else: self.shortcut = nn.Identity() assert cfg.stride_mode in ('pool', 'dw') stride_pool, stride_dw = 1, 1 # FIXME handle dilation? if cfg.stride_mode == 'pool': stride_pool = stride else: stride_dw = stride if stride_pool == 2: self.down = Downsample2d(in_chs, in_chs, pool_type=cfg.downsample_pool_type) else: self.down = nn.Identity() self.conv_dw = create_conv2d( in_chs, out_chs, kernel_size=kernel_size, stride=stride_dw, dilation=dilation[1], depthwise=True, bias=cfg.output_bias) self.norm = norm_layer(out_chs) self.mlp = mlp_layer(out_chs, int(cfg.expand_ratio * out_chs), bias=cfg.output_bias, act_layer=act_layer) if conv_mlp: self.ls = LayerScale2d(out_chs, cfg.init_values) if cfg.init_values else nn.Identity() else: self.ls = LayerScale(out_chs, cfg.init_values) if cfg.init_values else nn.Identity() self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() def forward(self, x): shortcut = self.shortcut(x) x = self.down(x) x = self.conv_dw(x) if self.use_conv_mlp: x = self.norm(x) x = self.mlp(x) x = self.ls(x) else: x = x.permute(0, 2, 3, 1) x = self.norm(x) x = self.mlp(x) x = self.ls(x) x = x.permute(0, 3, 1, 2) x = self.drop_path(x) + shortcut return x def window_partition(x, window_size: List[int]): B, H, W, C = x.shape _assert(H % window_size[0] == 0, f'height ({H}) must be divisible by window ({window_size[0]})') _assert(W % window_size[1] == 0, f'width ({W}) must be divisible by window ({window_size[1]})') x = x.view(B, H // window_size[0], window_size[0], W // window_size[1], window_size[1], C) windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size[0], window_size[1], C) return windows @register_notrace_function # reason: int argument is a Proxy def window_reverse(windows, window_size: List[int], img_size: List[int]): H, W = img_size C = windows.shape[-1] x = windows.view(-1, H // window_size[0], W // window_size[1], window_size[0], window_size[1], C) x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, H, W, C) return x def grid_partition(x, grid_size: List[int]): B, H, W, C = x.shape _assert(H % grid_size[0] == 0, f'height {H} must be divisible by grid {grid_size[0]}') _assert(W % grid_size[1] == 0, f'width {W} must be divisible by grid {grid_size[1]}') x = x.view(B, grid_size[0], H // grid_size[0], grid_size[1], W // grid_size[1], C) windows = x.permute(0, 2, 4, 1, 3, 5).contiguous().view(-1, grid_size[0], grid_size[1], C) return windows @register_notrace_function # reason: int argument is a Proxy def grid_reverse(windows, grid_size: List[int], img_size: List[int]): H, W = img_size C = windows.shape[-1] x = windows.view(-1, H // grid_size[0], W // grid_size[1], grid_size[0], grid_size[1], C) x = x.permute(0, 3, 1, 4, 2, 5).contiguous().view(-1, H, W, C) return x def get_rel_pos_cls(cfg: MaxxVitTransformerCfg, window_size): rel_pos_cls = None if cfg.rel_pos_type == 'mlp': rel_pos_cls = partial(RelPosMlp, window_size=window_size, hidden_dim=cfg.rel_pos_dim) elif cfg.rel_pos_type == 'bias': rel_pos_cls = partial(RelPosBias, window_size=window_size) elif cfg.rel_pos_type == 'bias_tf': rel_pos_cls = partial(RelPosBiasTf, window_size=window_size) return rel_pos_cls class PartitionAttentionCl(nn.Module): """ Grid or Block partition + Attn + FFN. NxC 'channels last' tensor layout. """ def __init__( self, dim: int, partition_type: str = 'block', cfg: MaxxVitTransformerCfg = MaxxVitTransformerCfg(), drop_path: float = 0., ): super().__init__() norm_layer = partial(get_norm_layer(cfg.norm_layer_cl), eps=cfg.norm_eps) # NOTE this block is channels-last act_layer = get_act_layer(cfg.act_layer) self.partition_block = partition_type == 'block' self.partition_size = to_2tuple(cfg.window_size if self.partition_block else cfg.grid_size) rel_pos_cls = get_rel_pos_cls(cfg, self.partition_size) self.norm1 = norm_layer(dim) self.attn = AttentionCl( dim, dim, dim_head=cfg.dim_head, bias=cfg.attn_bias, head_first=cfg.head_first, rel_pos_cls=rel_pos_cls, attn_drop=cfg.attn_drop, proj_drop=cfg.proj_drop, ) self.ls1 = LayerScale(dim, init_values=cfg.init_values) if cfg.init_values else nn.Identity() self.drop_path1 = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.norm2 = norm_layer(dim) self.mlp = Mlp( in_features=dim, hidden_features=int(dim * cfg.expand_ratio), act_layer=act_layer, drop=cfg.proj_drop) self.ls2 = LayerScale(dim, init_values=cfg.init_values) if cfg.init_values else nn.Identity() self.drop_path2 = DropPath(drop_path) if drop_path > 0. else nn.Identity() def _partition_attn(self, x): img_size = x.shape[1:3] if self.partition_block: partitioned = window_partition(x, self.partition_size) else: partitioned = grid_partition(x, self.partition_size) partitioned = self.attn(partitioned) if self.partition_block: x = window_reverse(partitioned, self.partition_size, img_size) else: x = grid_reverse(partitioned, self.partition_size, img_size) return x def forward(self, x): x = x + self.drop_path1(self.ls1(self._partition_attn(self.norm1(x)))) x = x + self.drop_path2(self.ls2(self.mlp(self.norm2(x)))) return x class ParallelPartitionAttention(nn.Module): """ Experimental. Grid and Block partition + single FFN NxC tensor layout. """ def __init__( self, dim: int, cfg: MaxxVitTransformerCfg = MaxxVitTransformerCfg(), drop_path: float = 0., ): super().__init__() assert dim % 2 == 0 norm_layer = partial(get_norm_layer(cfg.norm_layer_cl), eps=cfg.norm_eps) # NOTE this block is channels-last act_layer = get_act_layer(cfg.act_layer) assert cfg.window_size == cfg.grid_size self.partition_size = to_2tuple(cfg.window_size) rel_pos_cls = get_rel_pos_cls(cfg, self.partition_size) self.norm1 = norm_layer(dim) self.attn_block = AttentionCl( dim, dim // 2, dim_head=cfg.dim_head, bias=cfg.attn_bias, head_first=cfg.head_first, rel_pos_cls=rel_pos_cls, attn_drop=cfg.attn_drop, proj_drop=cfg.proj_drop, ) self.attn_grid = AttentionCl( dim, dim // 2, dim_head=cfg.dim_head, bias=cfg.attn_bias, head_first=cfg.head_first, rel_pos_cls=rel_pos_cls, attn_drop=cfg.attn_drop, proj_drop=cfg.proj_drop, ) self.ls1 = LayerScale(dim, init_values=cfg.init_values) if cfg.init_values else nn.Identity() self.drop_path1 = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.norm2 = norm_layer(dim) self.mlp = Mlp( in_features=dim, hidden_features=int(dim * cfg.expand_ratio), out_features=dim, act_layer=act_layer, drop=cfg.proj_drop) self.ls2 = LayerScale(dim, init_values=cfg.init_values) if cfg.init_values else nn.Identity() self.drop_path2 = DropPath(drop_path) if drop_path > 0. else nn.Identity() def _partition_attn(self, x): img_size = x.shape[1:3] partitioned_block = window_partition(x, self.partition_size) partitioned_block = self.attn_block(partitioned_block) x_window = window_reverse(partitioned_block, self.partition_size, img_size) partitioned_grid = grid_partition(x, self.partition_size) partitioned_grid = self.attn_grid(partitioned_grid) x_grid = grid_reverse(partitioned_grid, self.partition_size, img_size) return torch.cat([x_window, x_grid], dim=-1) def forward(self, x): x = x + self.drop_path1(self.ls1(self._partition_attn(self.norm1(x)))) x = x + self.drop_path2(self.ls2(self.mlp(self.norm2(x)))) return x def window_partition_nchw(x, window_size: List[int]): B, C, H, W = x.shape _assert(H % window_size[0] == 0, f'height ({H}) must be divisible by window ({window_size[0]})') _assert(W % window_size[1] == 0, f'width ({W}) must be divisible by window ({window_size[1]})') x = x.view(B, C, H // window_size[0], window_size[0], W // window_size[1], window_size[1]) windows = x.permute(0, 2, 4, 1, 3, 5).contiguous().view(-1, C, window_size[0], window_size[1]) return windows @register_notrace_function # reason: int argument is a Proxy def window_reverse_nchw(windows, window_size: List[int], img_size: List[int]): H, W = img_size C = windows.shape[1] x = windows.view(-1, H // window_size[0], W // window_size[1], C, window_size[0], window_size[1]) x = x.permute(0, 3, 1, 4, 2, 5).contiguous().view(-1, C, H, W) return x def grid_partition_nchw(x, grid_size: List[int]): B, C, H, W = x.shape _assert(H % grid_size[0] == 0, f'height {H} must be divisible by grid {grid_size[0]}') _assert(W % grid_size[1] == 0, f'width {W} must be divisible by grid {grid_size[1]}') x = x.view(B, C, grid_size[0], H // grid_size[0], grid_size[1], W // grid_size[1]) windows = x.permute(0, 3, 5, 1, 2, 4).contiguous().view(-1, C, grid_size[0], grid_size[1]) return windows @register_notrace_function # reason: int argument is a Proxy def grid_reverse_nchw(windows, grid_size: List[int], img_size: List[int]): H, W = img_size C = windows.shape[1] x = windows.view(-1, H // grid_size[0], W // grid_size[1], C, grid_size[0], grid_size[1]) x = x.permute(0, 3, 4, 1, 5, 2).contiguous().view(-1, C, H, W) return x class PartitionAttention2d(nn.Module): """ Grid or Block partition + Attn + FFN '2D' NCHW tensor layout. """ def __init__( self, dim: int, partition_type: str = 'block', cfg: MaxxVitTransformerCfg = MaxxVitTransformerCfg(), drop_path: float = 0., ): super().__init__() norm_layer = partial(get_norm_layer(cfg.norm_layer), eps=cfg.norm_eps) # NOTE this block is channels-last act_layer = get_act_layer(cfg.act_layer) self.partition_block = partition_type == 'block' self.partition_size = to_2tuple(cfg.window_size if self.partition_block else cfg.grid_size) rel_pos_cls = get_rel_pos_cls(cfg, self.partition_size) self.norm1 = norm_layer(dim) self.attn = Attention2d( dim, dim, dim_head=cfg.dim_head, bias=cfg.attn_bias, head_first=cfg.head_first, rel_pos_cls=rel_pos_cls, attn_drop=cfg.attn_drop, proj_drop=cfg.proj_drop, ) self.ls1 = LayerScale2d(dim, init_values=cfg.init_values) if cfg.init_values else nn.Identity() self.drop_path1 = DropPath(drop_path) if drop_path > 0. else nn.Identity() self.norm2 = norm_layer(dim) self.mlp = ConvMlp( in_features=dim, hidden_features=int(dim * cfg.expand_ratio), act_layer=act_layer, drop=cfg.proj_drop) self.ls2 = LayerScale2d(dim, init_values=cfg.init_values) if cfg.init_values else nn.Identity() self.drop_path2 = DropPath(drop_path) if drop_path > 0. else nn.Identity() def _partition_attn(self, x): img_size = x.shape[-2:] if self.partition_block: partitioned = window_partition_nchw(x, self.partition_size) else: partitioned = grid_partition_nchw(x, self.partition_size) partitioned = self.attn(partitioned) if self.partition_block: x = window_reverse_nchw(partitioned, self.partition_size, img_size) else: x = grid_reverse_nchw(partitioned, self.partition_size, img_size) return x def forward(self, x): x = x + self.drop_path1(self.ls1(self._partition_attn(self.norm1(x)))) x = x + self.drop_path2(self.ls2(self.mlp(self.norm2(x)))) return x class MaxxVitBlock(nn.Module): """ MaxVit conv, window partition + FFN , grid partition + FFN """ def __init__( self, dim: int, dim_out: int, stride: int = 1, conv_cfg: MaxxVitConvCfg = MaxxVitConvCfg(), transformer_cfg: MaxxVitTransformerCfg = MaxxVitTransformerCfg(), drop_path: float = 0., ): super().__init__() self.nchw_attn = transformer_cfg.use_nchw_attn conv_cls = ConvNeXtBlock if conv_cfg.block_type == 'convnext' else MbConvBlock self.conv = conv_cls(dim, dim_out, stride=stride, cfg=conv_cfg, drop_path=drop_path) attn_kwargs = dict(dim=dim_out, cfg=transformer_cfg, drop_path=drop_path) partition_layer = PartitionAttention2d if self.nchw_attn else PartitionAttentionCl self.attn_block = None if transformer_cfg.no_block_attn else partition_layer(**attn_kwargs) self.attn_grid = partition_layer(partition_type='grid', **attn_kwargs) def init_weights(self, scheme=''): if self.attn_block is not None: named_apply(partial(_init_transformer, scheme=scheme), self.attn_block) named_apply(partial(_init_transformer, scheme=scheme), self.attn_grid) named_apply(partial(_init_conv, scheme=scheme), self.conv) def forward(self, x): # NCHW format x = self.conv(x) if not self.nchw_attn: x = x.permute(0, 2, 3, 1) # to NHWC (channels-last) if self.attn_block is not None: x = self.attn_block(x) x = self.attn_grid(x) if not self.nchw_attn: x = x.permute(0, 3, 1, 2) # back to NCHW return x class ParallelMaxxVitBlock(nn.Module): """ MaxVit block with parallel cat(window + grid), one FF Experimental timm block. """ def __init__( self, dim, dim_out, stride=1, num_conv=2, conv_cfg: MaxxVitConvCfg = MaxxVitConvCfg(), transformer_cfg: MaxxVitTransformerCfg = MaxxVitTransformerCfg(), drop_path=0., ): super().__init__() conv_cls = ConvNeXtBlock if conv_cfg.block_type == 'convnext' else MbConvBlock if num_conv > 1: convs = [conv_cls(dim, dim_out, stride=stride, cfg=conv_cfg, drop_path=drop_path)] convs += [conv_cls(dim_out, dim_out, cfg=conv_cfg, drop_path=drop_path)] * (num_conv - 1) self.conv = nn.Sequential(*convs) else: self.conv = conv_cls(dim, dim_out, stride=stride, cfg=conv_cfg, drop_path=drop_path) self.attn = ParallelPartitionAttention(dim=dim_out, cfg=transformer_cfg, drop_path=drop_path) def init_weights(self, scheme=''): named_apply(partial(_init_transformer, scheme=scheme), self.attn) named_apply(partial(_init_conv, scheme=scheme), self.conv) def forward(self, x): x = self.conv(x) x = x.permute(0, 2, 3, 1) x = self.attn(x) x = x.permute(0, 3, 1, 2) return x class MaxxVitStage(nn.Module): def __init__( self, in_chs: int, out_chs: int, stride: int = 2, depth: int = 4, feat_size: Tuple[int, int] = (14, 14), block_types: Union[str, Tuple[str]] = 'C', transformer_cfg: MaxxVitTransformerCfg = MaxxVitTransformerCfg(), conv_cfg: MaxxVitConvCfg = MaxxVitConvCfg(), drop_path: Union[float, List[float]] = 0., ): super().__init__() self.grad_checkpointing = False block_types = extend_tuple(block_types, depth) blocks = [] for i, t in enumerate(block_types): block_stride = stride if i == 0 else 1 assert t in ('C', 'T', 'M', 'PM') if t == 'C': conv_cls = ConvNeXtBlock if conv_cfg.block_type == 'convnext' else MbConvBlock blocks += [conv_cls( in_chs, out_chs, stride=block_stride, cfg=conv_cfg, drop_path=drop_path[i], )] elif t == 'T': rel_pos_cls = get_rel_pos_cls(transformer_cfg, feat_size) blocks += [TransformerBlock2d( in_chs, out_chs, stride=block_stride, rel_pos_cls=rel_pos_cls, cfg=transformer_cfg, drop_path=drop_path[i], )] elif t == 'M': blocks += [MaxxVitBlock( in_chs, out_chs, stride=block_stride, conv_cfg=conv_cfg, transformer_cfg=transformer_cfg, drop_path=drop_path[i], )] elif t == 'PM': blocks += [ParallelMaxxVitBlock( in_chs, out_chs, stride=block_stride, conv_cfg=conv_cfg, transformer_cfg=transformer_cfg, drop_path=drop_path[i], )] in_chs = out_chs self.blocks = nn.Sequential(*blocks) def forward(self, x): if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint_seq(self.blocks, x) else: x = self.blocks(x) return x class Stem(nn.Module): def __init__( self, in_chs: int, out_chs: int, kernel_size: int = 3, padding: str = '', bias: bool = False, act_layer: str = 'gelu', norm_layer: str = 'batchnorm2d', norm_eps: float = 1e-5, ): super().__init__() if not isinstance(out_chs, (list, tuple)): out_chs = to_2tuple(out_chs) norm_act_layer = partial(get_norm_act_layer(norm_layer, act_layer), eps=norm_eps) self.out_chs = out_chs[-1] self.stride = 2 self.conv1 = create_conv2d(in_chs, out_chs[0], kernel_size, stride=2, padding=padding, bias=bias) self.norm1 = norm_act_layer(out_chs[0]) self.conv2 = create_conv2d(out_chs[0], out_chs[1], kernel_size, stride=1, padding=padding, bias=bias) def init_weights(self, scheme=''): named_apply(partial(_init_conv, scheme=scheme), self) def forward(self, x): x = self.conv1(x) x = self.norm1(x) x = self.conv2(x) return x def cfg_window_size(cfg: MaxxVitTransformerCfg, img_size: Tuple[int, int]): if cfg.window_size is not None: assert cfg.grid_size return cfg partition_size = img_size[0] // cfg.partition_ratio, img_size[1] // cfg.partition_ratio cfg = replace(cfg, window_size=partition_size, grid_size=partition_size) return cfg def _overlay_kwargs(cfg: MaxxVitCfg, **kwargs): transformer_kwargs = {} conv_kwargs = {} base_kwargs = {} for k, v in kwargs.items(): if k.startswith('transformer_'): transformer_kwargs[k.replace('transformer_', '')] = v elif k.startswith('conv_'): conv_kwargs[k.replace('conv_', '')] = v else: base_kwargs[k] = v cfg = replace( cfg, transformer_cfg=replace(cfg.transformer_cfg, **transformer_kwargs), conv_cfg=replace(cfg.conv_cfg, **conv_kwargs), **base_kwargs ) return cfg class MaxxVit(nn.Module): """ CoaTNet + MaxVit base model. Highly configurable for different block compositions, tensor layouts, pooling types. """ def __init__( self, cfg: MaxxVitCfg, img_size: Union[int, Tuple[int, int]] = 224, in_chans: int = 3, num_classes: int = 1000, global_pool: str = 'avg', drop_rate: float = 0., drop_path_rate: float = 0., **kwargs, ): super().__init__() img_size = to_2tuple(img_size) if kwargs: cfg = _overlay_kwargs(cfg, **kwargs) transformer_cfg = cfg_window_size(cfg.transformer_cfg, img_size) self.num_classes = num_classes self.global_pool = global_pool self.num_features = self.embed_dim = cfg.embed_dim[-1] self.drop_rate = drop_rate self.grad_checkpointing = False self.feature_info = [] self.stem = Stem( in_chs=in_chans, out_chs=cfg.stem_width, padding=cfg.conv_cfg.padding, bias=cfg.stem_bias, act_layer=cfg.conv_cfg.act_layer, norm_layer=cfg.conv_cfg.norm_layer, norm_eps=cfg.conv_cfg.norm_eps, ) stride = self.stem.stride self.feature_info += [dict(num_chs=self.stem.out_chs, reduction=2, module='stem')] feat_size = tuple([i // s for i, s in zip(img_size, to_2tuple(stride))]) num_stages = len(cfg.embed_dim) assert len(cfg.depths) == num_stages dpr = [x.tolist() for x in torch.linspace(0, drop_path_rate, sum(cfg.depths)).split(cfg.depths)] in_chs = self.stem.out_chs stages = [] for i in range(num_stages): stage_stride = 2 out_chs = cfg.embed_dim[i] feat_size = tuple([(r - 1) // stage_stride + 1 for r in feat_size]) stages += [MaxxVitStage( in_chs, out_chs, depth=cfg.depths[i], block_types=cfg.block_type[i], conv_cfg=cfg.conv_cfg, transformer_cfg=transformer_cfg, feat_size=feat_size, drop_path=dpr[i], )] stride *= stage_stride in_chs = out_chs self.feature_info += [dict(num_chs=out_chs, reduction=stride, module=f'stages.{i}')] self.stages = nn.Sequential(*stages) final_norm_layer = partial(get_norm_layer(cfg.transformer_cfg.norm_layer), eps=cfg.transformer_cfg.norm_eps) if cfg.head_hidden_size: self.norm = nn.Identity() self.head_hidden_size = cfg.head_hidden_size self.head = NormMlpClassifierHead( self.num_features, num_classes, hidden_size=self.head_hidden_size, pool_type=global_pool, drop_rate=drop_rate, norm_layer=final_norm_layer, ) else: # standard classifier head w/ norm, pooling, fc classifier self.head_hidden_size = self.num_features self.norm = final_norm_layer(self.num_features) self.head = ClassifierHead(self.num_features, num_classes, pool_type=global_pool, drop_rate=drop_rate) # Weight init (default PyTorch init works well for AdamW if scheme not set) assert cfg.weight_init in ('', 'normal', 'trunc_normal', 'xavier_normal', 'vit_eff') if cfg.weight_init: named_apply(partial(self._init_weights, scheme=cfg.weight_init), self) def _init_weights(self, module, name, scheme=''): if hasattr(module, 'init_weights'): try: module.init_weights(scheme=scheme) except TypeError: module.init_weights() @torch.jit.ignore def no_weight_decay(self): return { k for k, _ in self.named_parameters() if any(n in k for n in ["relative_position_bias_table", "rel_pos.mlp"])} @torch.jit.ignore def group_matcher(self, coarse=False): matcher = dict( stem=r'^stem', # stem and embed blocks=[(r'^stages\.(\d+)', None), (r'^norm', (99999,))] ) return matcher @torch.jit.ignore def set_grad_checkpointing(self, enable=True): for s in self.stages: s.grad_checkpointing = enable @torch.jit.ignore def get_classifier(self) -> nn.Module: return self.head.fc def reset_classifier(self, num_classes: int, global_pool: Optional[str] = None): self.num_classes = num_classes self.head.reset(num_classes, global_pool) def forward_intermediates( self, x: torch.Tensor, indices: Optional[Union[int, List[int]]] = None, norm: bool = False, stop_early: bool = False, output_fmt: str = 'NCHW', intermediates_only: bool = False, ) -> Union[List[torch.Tensor], Tuple[torch.Tensor, List[torch.Tensor]]]: """ Forward features that returns intermediates. Args: x: Input image tensor indices: Take last n blocks if int, all if None, select matching indices if sequence norm: Apply norm layer to compatible intermediates stop_early: Stop iterating over blocks when last desired intermediate hit output_fmt: Shape of intermediate feature outputs intermediates_only: Only return intermediate features Returns: """ assert output_fmt in ('NCHW',), 'Output shape must be NCHW.' intermediates = [] take_indices, max_index = feature_take_indices(len(self.stages) + 1, indices) # forward pass feat_idx = 0 # stem is index 0 x = self.stem(x) if feat_idx in take_indices: intermediates.append(x) last_idx = len(self.stages) if torch.jit.is_scripting() or not stop_early: # can't slice blocks in torchscript stages = self.stages else: stages = self.stages[:max_index] for stage in stages: feat_idx += 1 x = stage(x) if feat_idx in take_indices: if norm and feat_idx == last_idx: x_inter = self.norm(x) # applying final norm to last intermediate else: x_inter = x intermediates.append(x_inter) if intermediates_only: return intermediates x = self.norm(x) return x, intermediates def prune_intermediate_layers( self, indices: Union[int, List[int]] = 1, prune_norm: bool = False, prune_head: bool = True, ): """ Prune layers not required for specified intermediates. """ take_indices, max_index = feature_take_indices(len(self.stages) + 1, indices) self.stages = self.stages[:max_index] # truncate blocks w/ stem as idx 0 if prune_norm: self.norm = nn.Identity() if prune_head: self.head = self.reset_classifier(0, '') return take_indices def forward_features(self, x): x = self.stem(x) x = self.stages(x) x = self.norm(x) return x def forward_head(self, x, pre_logits: bool = False): return self.head(x, pre_logits=pre_logits) if pre_logits else self.head(x) def forward(self, x): x = self.forward_features(x) x = self.forward_head(x) return x def _rw_coat_cfg( stride_mode='pool', pool_type='avg2', conv_output_bias=False, conv_attn_early=False, conv_attn_act_layer='relu', conv_norm_layer='', transformer_shortcut_bias=True, transformer_norm_layer='layernorm2d', transformer_norm_layer_cl='layernorm', init_values=None, rel_pos_type='bias', rel_pos_dim=512, ): # 'RW' timm variant models were created and trained before seeing https://github.com/google-research/maxvit # Common differences for initial timm models: # - pre-norm layer in MZBConv included an activation after norm # - mbconv expansion calculated from input instead of output chs # - mbconv shortcut and final 1x1 conv did not have a bias # - SE act layer was relu, not silu # - mbconv uses silu in timm, not gelu # - expansion in attention block done via output proj, not input proj # Variable differences (evolved over training initial models): # - avg pool with kernel_size=2 favoured downsampling (instead of maxpool for coat) # - SE attention was between conv2 and norm/act # - default to avg pool for mbconv downsample instead of 1x1 or dw conv # - transformer block shortcut has no bias return dict( conv_cfg=MaxxVitConvCfg( stride_mode=stride_mode, pool_type=pool_type, pre_norm_act=True, expand_output=False, output_bias=conv_output_bias, attn_early=conv_attn_early, attn_act_layer=conv_attn_act_layer, act_layer='silu', norm_layer=conv_norm_layer, ), transformer_cfg=MaxxVitTransformerCfg( expand_first=False, shortcut_bias=transformer_shortcut_bias, pool_type=pool_type, init_values=init_values, norm_layer=transformer_norm_layer, norm_layer_cl=transformer_norm_layer_cl, rel_pos_type=rel_pos_type, rel_pos_dim=rel_pos_dim, ), ) def _rw_max_cfg( stride_mode='dw', pool_type='avg2', conv_output_bias=False, conv_attn_ratio=1 / 16, conv_norm_layer='', transformer_norm_layer='layernorm2d', transformer_norm_layer_cl='layernorm', window_size=None, dim_head=32, init_values=None, rel_pos_type='bias', rel_pos_dim=512, ): # 'RW' timm variant models were created and trained before seeing https://github.com/google-research/maxvit # Differences of initial timm models: # - mbconv expansion calculated from input instead of output chs # - mbconv shortcut and final 1x1 conv did not have a bias # - mbconv uses silu in timm, not gelu # - expansion in attention block done via output proj, not input proj return dict( conv_cfg=MaxxVitConvCfg( stride_mode=stride_mode, pool_type=pool_type, expand_output=False, output_bias=conv_output_bias, attn_ratio=conv_attn_ratio, act_layer='silu', norm_layer=conv_norm_layer, ), transformer_cfg=MaxxVitTransformerCfg( expand_first=False, pool_type=pool_type, dim_head=dim_head, window_size=window_size, init_values=init_values, norm_layer=transformer_norm_layer, norm_layer_cl=transformer_norm_layer_cl, rel_pos_type=rel_pos_type, rel_pos_dim=rel_pos_dim, ), ) def _next_cfg( stride_mode='dw', pool_type='avg2', conv_norm_layer='layernorm2d', conv_norm_layer_cl='layernorm', transformer_norm_layer='layernorm2d', transformer_norm_layer_cl='layernorm', window_size=None, no_block_attn=False, init_values=1e-6, rel_pos_type='mlp', # MLP by default for maxxvit rel_pos_dim=512, ): # For experimental models with convnext instead of mbconv init_values = to_2tuple(init_values) return dict( conv_cfg=MaxxVitConvCfg( block_type='convnext', stride_mode=stride_mode, pool_type=pool_type, expand_output=False, init_values=init_values[0], norm_layer=conv_norm_layer, norm_layer_cl=conv_norm_layer_cl, ), transformer_cfg=MaxxVitTransformerCfg( expand_first=False, pool_type=pool_type, window_size=window_size, no_block_attn=no_block_attn, # enabled for MaxxViT-V2 init_values=init_values[1], norm_layer=transformer_norm_layer, norm_layer_cl=transformer_norm_layer_cl, rel_pos_type=rel_pos_type, rel_pos_dim=rel_pos_dim, ), ) def _tf_cfg(): return dict( conv_cfg=MaxxVitConvCfg( norm_eps=1e-3, act_layer='gelu_tanh', padding='same', ), transformer_cfg=MaxxVitTransformerCfg( norm_eps=1e-5, act_layer='gelu_tanh', head_first=False, # heads are interleaved (q_nh, q_hdim, k_nh, q_hdim, ....) rel_pos_type='bias_tf', ), ) model_cfgs = dict( # timm specific CoAtNet configs coatnet_pico_rw=MaxxVitCfg( embed_dim=(64, 128, 256, 512), depths=(2, 3, 5, 2), stem_width=(32, 64), **_rw_max_cfg( # using newer max defaults here conv_output_bias=True, conv_attn_ratio=0.25, ), ), coatnet_nano_rw=MaxxVitCfg( embed_dim=(64, 128, 256, 512), depths=(3, 4, 6, 3), stem_width=(32, 64), **_rw_max_cfg( # using newer max defaults here stride_mode='pool', conv_output_bias=True, conv_attn_ratio=0.25, ), ), coatnet_0_rw=MaxxVitCfg( embed_dim=(96, 192, 384, 768), depths=(2, 3, 7, 2), # deeper than paper '0' model stem_width=(32, 64), **_rw_coat_cfg( conv_attn_early=True, transformer_shortcut_bias=False, ), ), coatnet_1_rw=MaxxVitCfg( embed_dim=(96, 192, 384, 768), depths=(2, 6, 14, 2), stem_width=(32, 64), **_rw_coat_cfg( stride_mode='dw', conv_attn_early=True, transformer_shortcut_bias=False, ) ), coatnet_2_rw=MaxxVitCfg( embed_dim=(128, 256, 512, 1024), depths=(2, 6, 14, 2), stem_width=(64, 128), **_rw_coat_cfg( stride_mode='dw', conv_attn_act_layer='silu', #init_values=1e-6, ), ), coatnet_3_rw=MaxxVitCfg( embed_dim=(192, 384, 768, 1536), depths=(2, 6, 14, 2), stem_width=(96, 192), **_rw_coat_cfg( stride_mode='dw', conv_attn_act_layer='silu', init_values=1e-6, ), ), # Experimental CoAtNet configs w/ ImageNet-1k train (different norm layers, MLP rel-pos) coatnet_bn_0_rw=MaxxVitCfg( embed_dim=(96, 192, 384, 768), depths=(2, 3, 7, 2), # deeper than paper '0' model stem_width=(32, 64), **_rw_coat_cfg( stride_mode='dw', conv_attn_early=True, transformer_shortcut_bias=False, transformer_norm_layer='batchnorm2d', ) ), coatnet_rmlp_nano_rw=MaxxVitCfg( embed_dim=(64, 128, 256, 512), depths=(3, 4, 6, 3), stem_width=(32, 64), **_rw_max_cfg( conv_output_bias=True, conv_attn_ratio=0.25, rel_pos_type='mlp', rel_pos_dim=384, ), ), coatnet_rmlp_0_rw=MaxxVitCfg( embed_dim=(96, 192, 384, 768), depths=(2, 3, 7, 2), # deeper than paper '0' model stem_width=(32, 64), **_rw_coat_cfg( stride_mode='dw', rel_pos_type='mlp', ), ), coatnet_rmlp_1_rw=MaxxVitCfg( embed_dim=(96, 192, 384, 768), depths=(2, 6, 14, 2), stem_width=(32, 64), **_rw_coat_cfg( pool_type='max', conv_attn_early=True, transformer_shortcut_bias=False, rel_pos_type='mlp', rel_pos_dim=384, # was supposed to be 512, woops ), ), coatnet_rmlp_1_rw2=MaxxVitCfg( embed_dim=(96, 192, 384, 768), depths=(2, 6, 14, 2), stem_width=(32, 64), **_rw_coat_cfg( stride_mode='dw', rel_pos_type='mlp', rel_pos_dim=512, # was supposed to be 512, woops ), ), coatnet_rmlp_2_rw=MaxxVitCfg( embed_dim=(128, 256, 512, 1024), depths=(2, 6, 14, 2), stem_width=(64, 128), **_rw_coat_cfg( stride_mode='dw', conv_attn_act_layer='silu', init_values=1e-6, rel_pos_type='mlp' ), ), coatnet_rmlp_3_rw=MaxxVitCfg( embed_dim=(192, 384, 768, 1536), depths=(2, 6, 14, 2), stem_width=(96, 192), **_rw_coat_cfg( stride_mode='dw', conv_attn_act_layer='silu', init_values=1e-6, rel_pos_type='mlp' ), ), coatnet_nano_cc=MaxxVitCfg( embed_dim=(64, 128, 256, 512), depths=(3, 4, 6, 3), stem_width=(32, 64), block_type=('C', 'C', ('C', 'T'), ('C', 'T')), **_rw_coat_cfg(), ), coatnext_nano_rw=MaxxVitCfg( embed_dim=(64, 128, 256, 512), depths=(3, 4, 6, 3), stem_width=(32, 64), weight_init='normal', **_next_cfg( rel_pos_type='bias', init_values=(1e-5, None) ), ), # Trying to be like the CoAtNet paper configs coatnet_0=MaxxVitCfg( embed_dim=(96, 192, 384, 768), depths=(2, 3, 5, 2), stem_width=64, head_hidden_size=768, ), coatnet_1=MaxxVitCfg( embed_dim=(96, 192, 384, 768), depths=(2, 6, 14, 2), stem_width=64, head_hidden_size=768, ), coatnet_2=MaxxVitCfg( embed_dim=(128, 256, 512, 1024), depths=(2, 6, 14, 2), stem_width=128, head_hidden_size=1024, ), coatnet_3=MaxxVitCfg( embed_dim=(192, 384, 768, 1536), depths=(2, 6, 14, 2), stem_width=192, head_hidden_size=1536, ), coatnet_4=MaxxVitCfg( embed_dim=(192, 384, 768, 1536), depths=(2, 12, 28, 2), stem_width=192, head_hidden_size=1536, ), coatnet_5=MaxxVitCfg( embed_dim=(256, 512, 1280, 2048), depths=(2, 12, 28, 2), stem_width=192, head_hidden_size=2048, ), # Experimental MaxVit configs maxvit_pico_rw=MaxxVitCfg( embed_dim=(32, 64, 128, 256), depths=(2, 2, 5, 2), block_type=('M',) * 4, stem_width=(24, 32), **_rw_max_cfg(), ), maxvit_nano_rw=MaxxVitCfg( embed_dim=(64, 128, 256, 512), depths=(1, 2, 3, 1), block_type=('M',) * 4, stem_width=(32, 64), **_rw_max_cfg(), ), maxvit_tiny_rw=MaxxVitCfg( embed_dim=(64, 128, 256, 512), depths=(2, 2, 5, 2), block_type=('M',) * 4, stem_width=(32, 64), **_rw_max_cfg(), ), maxvit_tiny_pm=MaxxVitCfg( embed_dim=(64, 128, 256, 512), depths=(2, 2, 5, 2), block_type=('PM',) * 4, stem_width=(32, 64), **_rw_max_cfg(), ), maxvit_rmlp_pico_rw=MaxxVitCfg( embed_dim=(32, 64, 128, 256), depths=(2, 2, 5, 2), block_type=('M',) * 4, stem_width=(24, 32), **_rw_max_cfg(rel_pos_type='mlp'), ), maxvit_rmlp_nano_rw=MaxxVitCfg( embed_dim=(64, 128, 256, 512), depths=(1, 2, 3, 1), block_type=('M',) * 4, stem_width=(32, 64), **_rw_max_cfg(rel_pos_type='mlp'), ), maxvit_rmlp_tiny_rw=MaxxVitCfg( embed_dim=(64, 128, 256, 512), depths=(2, 2, 5, 2), block_type=('M',) * 4, stem_width=(32, 64), **_rw_max_cfg(rel_pos_type='mlp'), ), maxvit_rmlp_small_rw=MaxxVitCfg( embed_dim=(96, 192, 384, 768), depths=(2, 2, 5, 2), block_type=('M',) * 4, stem_width=(32, 64), **_rw_max_cfg( rel_pos_type='mlp', init_values=1e-6, ), ), maxvit_rmlp_base_rw=MaxxVitCfg( embed_dim=(96, 192, 384, 768), depths=(2, 6, 14, 2), block_type=('M',) * 4, stem_width=(32, 64), head_hidden_size=768, **_rw_max_cfg( rel_pos_type='mlp', ), ), maxxvit_rmlp_nano_rw=MaxxVitCfg( embed_dim=(64, 128, 256, 512), depths=(1, 2, 3, 1), block_type=('M',) * 4, stem_width=(32, 64), weight_init='normal', **_next_cfg(), ), maxxvit_rmlp_tiny_rw=MaxxVitCfg( embed_dim=(64, 128, 256, 512), depths=(2, 2, 5, 2), block_type=('M',) * 4, stem_width=(32, 64), **_next_cfg(), ), maxxvit_rmlp_small_rw=MaxxVitCfg( embed_dim=(96, 192, 384, 768), depths=(2, 2, 5, 2), block_type=('M',) * 4, stem_width=(48, 96), **_next_cfg(), ), maxxvitv2_nano_rw=MaxxVitCfg( embed_dim=(96, 192, 384, 768), depths=(1, 2, 3, 1), block_type=('M',) * 4, stem_width=(48, 96), weight_init='normal', **_next_cfg( no_block_attn=True, rel_pos_type='bias', ), ), maxxvitv2_rmlp_base_rw=MaxxVitCfg( embed_dim=(128, 256, 512, 1024), depths=(2, 6, 12, 2), block_type=('M',) * 4, stem_width=(64, 128), **_next_cfg( no_block_attn=True, ), ), maxxvitv2_rmlp_large_rw=MaxxVitCfg( embed_dim=(160, 320, 640, 1280), depths=(2, 6, 16, 2), block_type=('M',) * 4, stem_width=(80, 160), head_hidden_size=1280, **_next_cfg( no_block_attn=True, ), ), # Trying to be like the MaxViT paper configs maxvit_tiny_tf=MaxxVitCfg( embed_dim=(64, 128, 256, 512), depths=(2, 2, 5, 2), block_type=('M',) * 4, stem_width=64, stem_bias=True, head_hidden_size=512, **_tf_cfg(), ), maxvit_small_tf=MaxxVitCfg( embed_dim=(96, 192, 384, 768), depths=(2, 2, 5, 2), block_type=('M',) * 4, stem_width=64, stem_bias=True, head_hidden_size=768, **_tf_cfg(), ), maxvit_base_tf=MaxxVitCfg( embed_dim=(96, 192, 384, 768), depths=(2, 6, 14, 2), block_type=('M',) * 4, stem_width=64, stem_bias=True, head_hidden_size=768, **_tf_cfg(), ), maxvit_large_tf=MaxxVitCfg( embed_dim=(128, 256, 512, 1024), depths=(2, 6, 14, 2), block_type=('M',) * 4, stem_width=128, stem_bias=True, head_hidden_size=1024, **_tf_cfg(), ), maxvit_xlarge_tf=MaxxVitCfg( embed_dim=(192, 384, 768, 1536), depths=(2, 6, 14, 2), block_type=('M',) * 4, stem_width=192, stem_bias=True, head_hidden_size=1536, **_tf_cfg(), ), ) def checkpoint_filter_fn(state_dict, model: nn.Module): model_state_dict = model.state_dict() out_dict = {} for k, v in state_dict.items(): if k.endswith('relative_position_bias_table'): m = model.get_submodule(k[:-29]) if v.shape != m.relative_position_bias_table.shape or m.window_size[0] != m.window_size[1]: v = resize_rel_pos_bias_table( v, new_window_size=m.window_size, new_bias_shape=m.relative_position_bias_table.shape, ) if k in model_state_dict and v.ndim != model_state_dict[k].ndim and v.numel() == model_state_dict[k].numel(): # adapt between conv2d / linear layers assert v.ndim in (2, 4) v = v.reshape(model_state_dict[k].shape) out_dict[k] = v return out_dict def _create_maxxvit(variant, cfg_variant=None, pretrained=False, **kwargs): if cfg_variant is None: if variant in model_cfgs: cfg_variant = variant else: cfg_variant = '_'.join(variant.split('_')[:-1]) return build_model_with_cfg( MaxxVit, variant, pretrained, model_cfg=model_cfgs[cfg_variant], feature_cfg=dict(flatten_sequential=True), pretrained_filter_fn=checkpoint_filter_fn, **kwargs) def _cfg(url='', **kwargs): return { 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': (7, 7), 'crop_pct': 0.95, 'interpolation': 'bicubic', 'mean': (0.5, 0.5, 0.5), 'std': (0.5, 0.5, 0.5), 'first_conv': 'stem.conv1', 'classifier': 'head.fc', 'fixed_input_size': True, **kwargs } default_cfgs = generate_default_cfgs({ # timm specific CoAtNet configs, ImageNet-1k pretrain, fixed rel-pos 'coatnet_pico_rw_224.untrained': _cfg(url=''), 'coatnet_nano_rw_224.sw_in1k': _cfg( hf_hub_id='timm/', url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights-maxx/coatnet_nano_rw_224_sw-f53093b4.pth', crop_pct=0.9), 'coatnet_0_rw_224.sw_in1k': _cfg( hf_hub_id='timm/', url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights-maxx/coatnet_0_rw_224_sw-a6439706.pth'), 'coatnet_1_rw_224.sw_in1k': _cfg( hf_hub_id='timm/', url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights-maxx/coatnet_1_rw_224_sw-5cae1ea8.pth' ), # timm specific CoAtNet configs, ImageNet-12k pretrain w/ 1k fine-tune, fixed rel-pos 'coatnet_2_rw_224.sw_in12k_ft_in1k': _cfg( hf_hub_id='timm/'), #'coatnet_3_rw_224.untrained': _cfg(url=''), # Experimental CoAtNet configs w/ ImageNet-12k pretrain -> 1k fine-tune (different norm layers, MLP rel-pos) 'coatnet_rmlp_1_rw2_224.sw_in12k_ft_in1k': _cfg( hf_hub_id='timm/'), 'coatnet_rmlp_2_rw_224.sw_in12k_ft_in1k': _cfg( hf_hub_id='timm/'), 'coatnet_rmlp_2_rw_384.sw_in12k_ft_in1k': _cfg( hf_hub_id='timm/', input_size=(3, 384, 384), pool_size=(12, 12), crop_pct=1.0, crop_mode='squash'), # Experimental CoAtNet configs w/ ImageNet-1k train (different norm layers, MLP rel-pos) 'coatnet_bn_0_rw_224.sw_in1k': _cfg( hf_hub_id='timm/', url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights-maxx/coatnet_bn_0_rw_224_sw-c228e218.pth', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD, crop_pct=0.95), 'coatnet_rmlp_nano_rw_224.sw_in1k': _cfg( hf_hub_id='timm/', url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights-maxx/coatnet_rmlp_nano_rw_224_sw-bd1d51b3.pth', crop_pct=0.9), 'coatnet_rmlp_0_rw_224.untrained': _cfg(url=''), 'coatnet_rmlp_1_rw_224.sw_in1k': _cfg( hf_hub_id='timm/', url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights-maxx/coatnet_rmlp_1_rw_224_sw-9051e6c3.pth'), 'coatnet_rmlp_2_rw_224.sw_in1k': _cfg( hf_hub_id='timm/', url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights-maxx/coatnet_rmlp_2_rw_224_sw-5ccfac55.pth'), 'coatnet_rmlp_3_rw_224.untrained': _cfg(url=''), 'coatnet_nano_cc_224.untrained': _cfg(url=''), 'coatnext_nano_rw_224.sw_in1k': _cfg( hf_hub_id='timm/', url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights-maxx/coatnext_nano_rw_224_ad-22cb71c2.pth', crop_pct=0.9), # ImagenNet-12k pretrain CoAtNet 'coatnet_2_rw_224.sw_in12k': _cfg( hf_hub_id='timm/', num_classes=11821), 'coatnet_3_rw_224.sw_in12k': _cfg( hf_hub_id='timm/', num_classes=11821), 'coatnet_rmlp_1_rw2_224.sw_in12k': _cfg( hf_hub_id='timm/', num_classes=11821), 'coatnet_rmlp_2_rw_224.sw_in12k': _cfg( hf_hub_id='timm/', num_classes=11821), # Trying to be like the CoAtNet paper configs (will adapt if 'tf' weights are ever released) 'coatnet_0_224.untrained': _cfg(url=''), 'coatnet_1_224.untrained': _cfg(url=''), 'coatnet_2_224.untrained': _cfg(url=''), 'coatnet_3_224.untrained': _cfg(url=''), 'coatnet_4_224.untrained': _cfg(url=''), 'coatnet_5_224.untrained': _cfg(url=''), # timm specific MaxVit configs, ImageNet-1k pretrain or untrained 'maxvit_pico_rw_256.untrained': _cfg(url='', input_size=(3, 256, 256), pool_size=(8, 8)), 'maxvit_nano_rw_256.sw_in1k': _cfg( hf_hub_id='timm/', url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights-maxx/maxvit_nano_rw_256_sw-fb127241.pth', input_size=(3, 256, 256), pool_size=(8, 8)), 'maxvit_tiny_rw_224.sw_in1k': _cfg( hf_hub_id='timm/', url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights-maxx/maxvit_tiny_rw_224_sw-7d0dffeb.pth'), 'maxvit_tiny_rw_256.untrained': _cfg( url='', input_size=(3, 256, 256), pool_size=(8, 8)), 'maxvit_tiny_pm_256.untrained': _cfg(url='', input_size=(3, 256, 256), pool_size=(8, 8)), # timm specific MaxVit w/ MLP rel-pos, ImageNet-1k pretrain 'maxvit_rmlp_pico_rw_256.sw_in1k': _cfg( hf_hub_id='timm/', url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights-maxx/maxvit_rmlp_pico_rw_256_sw-8d82f2c6.pth', input_size=(3, 256, 256), pool_size=(8, 8)), 'maxvit_rmlp_nano_rw_256.sw_in1k': _cfg( hf_hub_id='timm/', url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights-maxx/maxvit_rmlp_nano_rw_256_sw-c17bb0d6.pth', input_size=(3, 256, 256), pool_size=(8, 8)), 'maxvit_rmlp_tiny_rw_256.sw_in1k': _cfg( hf_hub_id='timm/', url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights-maxx/maxvit_rmlp_tiny_rw_256_sw-bbef0ff5.pth', input_size=(3, 256, 256), pool_size=(8, 8)), 'maxvit_rmlp_small_rw_224.sw_in1k': _cfg( hf_hub_id='timm/', url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights-maxx/maxvit_rmlp_small_rw_224_sw-6ef0ae4f.pth', crop_pct=0.9, ), 'maxvit_rmlp_small_rw_256.untrained': _cfg( url='', input_size=(3, 256, 256), pool_size=(8, 8)), # timm specific MaxVit w/ ImageNet-12k pretrain and 1k fine-tune 'maxvit_rmlp_base_rw_224.sw_in12k_ft_in1k': _cfg( hf_hub_id='timm/', ), 'maxvit_rmlp_base_rw_384.sw_in12k_ft_in1k': _cfg( hf_hub_id='timm/', input_size=(3, 384, 384), pool_size=(12, 12), crop_pct=1.0, crop_mode='squash'), # timm specific MaxVit w/ ImageNet-12k pretrain 'maxvit_rmlp_base_rw_224.sw_in12k': _cfg( hf_hub_id='timm/', num_classes=11821, ), # timm MaxxViT configs (ConvNeXt conv blocks mixed with MaxVit transformer blocks) 'maxxvit_rmlp_nano_rw_256.sw_in1k': _cfg( hf_hub_id='timm/', url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights-maxx/maxxvit_rmlp_nano_rw_256_sw-0325d459.pth', input_size=(3, 256, 256), pool_size=(8, 8)), 'maxxvit_rmlp_tiny_rw_256.untrained': _cfg(url='', input_size=(3, 256, 256), pool_size=(8, 8)), 'maxxvit_rmlp_small_rw_256.sw_in1k': _cfg( hf_hub_id='timm/', url='https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights-maxx/maxxvit_rmlp_small_rw_256_sw-37e217ff.pth', input_size=(3, 256, 256), pool_size=(8, 8)), # timm MaxxViT-V2 configs (ConvNeXt conv blocks mixed with MaxVit transformer blocks, more width, no block attn) 'maxxvitv2_nano_rw_256.sw_in1k': _cfg( hf_hub_id='timm/', input_size=(3, 256, 256), pool_size=(8, 8)), 'maxxvitv2_rmlp_base_rw_224.sw_in12k_ft_in1k': _cfg( hf_hub_id='timm/'), 'maxxvitv2_rmlp_base_rw_384.sw_in12k_ft_in1k': _cfg( hf_hub_id='timm/', input_size=(3, 384, 384), pool_size=(12, 12), crop_pct=1.0, crop_mode='squash'), 'maxxvitv2_rmlp_large_rw_224.untrained': _cfg(url=''), 'maxxvitv2_rmlp_base_rw_224.sw_in12k': _cfg( hf_hub_id='timm/', num_classes=11821), # MaxViT models ported from official Tensorflow impl 'maxvit_tiny_tf_224.in1k': _cfg( hf_hub_id='timm/', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD), 'maxvit_tiny_tf_384.in1k': _cfg( hf_hub_id='timm/', input_size=(3, 384, 384), pool_size=(12, 12), crop_pct=1.0, crop_mode='squash'), 'maxvit_tiny_tf_512.in1k': _cfg( hf_hub_id='timm/', input_size=(3, 512, 512), pool_size=(16, 16), crop_pct=1.0, crop_mode='squash'), 'maxvit_small_tf_224.in1k': _cfg( hf_hub_id='timm/', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD), 'maxvit_small_tf_384.in1k': _cfg( hf_hub_id='timm/', input_size=(3, 384, 384), pool_size=(12, 12), crop_pct=1.0, crop_mode='squash'), 'maxvit_small_tf_512.in1k': _cfg( hf_hub_id='timm/', input_size=(3, 512, 512), pool_size=(16, 16), crop_pct=1.0, crop_mode='squash'), 'maxvit_base_tf_224.in1k': _cfg( hf_hub_id='timm/', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD), 'maxvit_base_tf_384.in1k': _cfg( hf_hub_id='timm/', input_size=(3, 384, 384), pool_size=(12, 12), crop_pct=1.0, crop_mode='squash'), 'maxvit_base_tf_512.in1k': _cfg( hf_hub_id='timm/', input_size=(3, 512, 512), pool_size=(16, 16), crop_pct=1.0, crop_mode='squash'), 'maxvit_large_tf_224.in1k': _cfg( hf_hub_id='timm/', mean=IMAGENET_DEFAULT_MEAN, std=IMAGENET_DEFAULT_STD), 'maxvit_large_tf_384.in1k': _cfg( hf_hub_id='timm/', input_size=(3, 384, 384), pool_size=(12, 12), crop_pct=1.0, crop_mode='squash'), 'maxvit_large_tf_512.in1k': _cfg( hf_hub_id='timm/', input_size=(3, 512, 512), pool_size=(16, 16), crop_pct=1.0, crop_mode='squash'), 'maxvit_base_tf_224.in21k': _cfg( hf_hub_id='timm/', num_classes=21843), 'maxvit_base_tf_384.in21k_ft_in1k': _cfg( hf_hub_id='timm/', input_size=(3, 384, 384), pool_size=(12, 12), crop_pct=1.0, crop_mode='squash'), 'maxvit_base_tf_512.in21k_ft_in1k': _cfg( hf_hub_id='timm/', input_size=(3, 512, 512), pool_size=(16, 16), crop_pct=1.0, crop_mode='squash'), 'maxvit_large_tf_224.in21k': _cfg( hf_hub_id='timm/', num_classes=21843), 'maxvit_large_tf_384.in21k_ft_in1k': _cfg( hf_hub_id='timm/', input_size=(3, 384, 384), pool_size=(12, 12), crop_pct=1.0, crop_mode='squash'), 'maxvit_large_tf_512.in21k_ft_in1k': _cfg( hf_hub_id='timm/', input_size=(3, 512, 512), crop_pct=1.0, crop_mode='squash'), 'maxvit_xlarge_tf_224.in21k': _cfg( hf_hub_id='timm/', num_classes=21843), 'maxvit_xlarge_tf_384.in21k_ft_in1k': _cfg( hf_hub_id='timm/', input_size=(3, 384, 384), pool_size=(12, 12), crop_pct=1.0, crop_mode='squash'), 'maxvit_xlarge_tf_512.in21k_ft_in1k': _cfg( hf_hub_id='timm/', input_size=(3, 512, 512), pool_size=(16, 16), crop_pct=1.0, crop_mode='squash'), }) @register_model def coatnet_pico_rw_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('coatnet_pico_rw_224', pretrained=pretrained, **kwargs) @register_model def coatnet_nano_rw_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('coatnet_nano_rw_224', pretrained=pretrained, **kwargs) @register_model def coatnet_0_rw_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('coatnet_0_rw_224', pretrained=pretrained, **kwargs) @register_model def coatnet_1_rw_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('coatnet_1_rw_224', pretrained=pretrained, **kwargs) @register_model def coatnet_2_rw_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('coatnet_2_rw_224', pretrained=pretrained, **kwargs) @register_model def coatnet_3_rw_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('coatnet_3_rw_224', pretrained=pretrained, **kwargs) @register_model def coatnet_bn_0_rw_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('coatnet_bn_0_rw_224', pretrained=pretrained, **kwargs) @register_model def coatnet_rmlp_nano_rw_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('coatnet_rmlp_nano_rw_224', pretrained=pretrained, **kwargs) @register_model def coatnet_rmlp_0_rw_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('coatnet_rmlp_0_rw_224', pretrained=pretrained, **kwargs) @register_model def coatnet_rmlp_1_rw_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('coatnet_rmlp_1_rw_224', pretrained=pretrained, **kwargs) @register_model def coatnet_rmlp_1_rw2_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('coatnet_rmlp_1_rw2_224', pretrained=pretrained, **kwargs) @register_model def coatnet_rmlp_2_rw_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('coatnet_rmlp_2_rw_224', pretrained=pretrained, **kwargs) @register_model def coatnet_rmlp_2_rw_384(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('coatnet_rmlp_2_rw_384', pretrained=pretrained, **kwargs) @register_model def coatnet_rmlp_3_rw_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('coatnet_rmlp_3_rw_224', pretrained=pretrained, **kwargs) @register_model def coatnet_nano_cc_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('coatnet_nano_cc_224', pretrained=pretrained, **kwargs) @register_model def coatnext_nano_rw_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('coatnext_nano_rw_224', pretrained=pretrained, **kwargs) @register_model def coatnet_0_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('coatnet_0_224', pretrained=pretrained, **kwargs) @register_model def coatnet_1_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('coatnet_1_224', pretrained=pretrained, **kwargs) @register_model def coatnet_2_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('coatnet_2_224', pretrained=pretrained, **kwargs) @register_model def coatnet_3_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('coatnet_3_224', pretrained=pretrained, **kwargs) @register_model def coatnet_4_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('coatnet_4_224', pretrained=pretrained, **kwargs) @register_model def coatnet_5_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('coatnet_5_224', pretrained=pretrained, **kwargs) @register_model def maxvit_pico_rw_256(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxvit_pico_rw_256', pretrained=pretrained, **kwargs) @register_model def maxvit_nano_rw_256(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxvit_nano_rw_256', pretrained=pretrained, **kwargs) @register_model def maxvit_tiny_rw_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxvit_tiny_rw_224', pretrained=pretrained, **kwargs) @register_model def maxvit_tiny_rw_256(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxvit_tiny_rw_256', pretrained=pretrained, **kwargs) @register_model def maxvit_rmlp_pico_rw_256(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxvit_rmlp_pico_rw_256', pretrained=pretrained, **kwargs) @register_model def maxvit_rmlp_nano_rw_256(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxvit_rmlp_nano_rw_256', pretrained=pretrained, **kwargs) @register_model def maxvit_rmlp_tiny_rw_256(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxvit_rmlp_tiny_rw_256', pretrained=pretrained, **kwargs) @register_model def maxvit_rmlp_small_rw_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxvit_rmlp_small_rw_224', pretrained=pretrained, **kwargs) @register_model def maxvit_rmlp_small_rw_256(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxvit_rmlp_small_rw_256', pretrained=pretrained, **kwargs) @register_model def maxvit_rmlp_base_rw_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxvit_rmlp_base_rw_224', pretrained=pretrained, **kwargs) @register_model def maxvit_rmlp_base_rw_384(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxvit_rmlp_base_rw_384', pretrained=pretrained, **kwargs) @register_model def maxvit_tiny_pm_256(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxvit_tiny_pm_256', pretrained=pretrained, **kwargs) @register_model def maxxvit_rmlp_nano_rw_256(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxxvit_rmlp_nano_rw_256', pretrained=pretrained, **kwargs) @register_model def maxxvit_rmlp_tiny_rw_256(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxxvit_rmlp_tiny_rw_256', pretrained=pretrained, **kwargs) @register_model def maxxvit_rmlp_small_rw_256(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxxvit_rmlp_small_rw_256', pretrained=pretrained, **kwargs) @register_model def maxxvitv2_nano_rw_256(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxxvitv2_nano_rw_256', pretrained=pretrained, **kwargs) @register_model def maxxvitv2_rmlp_base_rw_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxxvitv2_rmlp_base_rw_224', pretrained=pretrained, **kwargs) @register_model def maxxvitv2_rmlp_base_rw_384(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxxvitv2_rmlp_base_rw_384', pretrained=pretrained, **kwargs) @register_model def maxxvitv2_rmlp_large_rw_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxxvitv2_rmlp_large_rw_224', pretrained=pretrained, **kwargs) @register_model def maxvit_tiny_tf_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxvit_tiny_tf_224', 'maxvit_tiny_tf', pretrained=pretrained, **kwargs) @register_model def maxvit_tiny_tf_384(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxvit_tiny_tf_384', 'maxvit_tiny_tf', pretrained=pretrained, **kwargs) @register_model def maxvit_tiny_tf_512(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxvit_tiny_tf_512', 'maxvit_tiny_tf', pretrained=pretrained, **kwargs) @register_model def maxvit_small_tf_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxvit_small_tf_224', 'maxvit_small_tf', pretrained=pretrained, **kwargs) @register_model def maxvit_small_tf_384(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxvit_small_tf_384', 'maxvit_small_tf', pretrained=pretrained, **kwargs) @register_model def maxvit_small_tf_512(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxvit_small_tf_512', 'maxvit_small_tf', pretrained=pretrained, **kwargs) @register_model def maxvit_base_tf_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxvit_base_tf_224', 'maxvit_base_tf', pretrained=pretrained, **kwargs) @register_model def maxvit_base_tf_384(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxvit_base_tf_384', 'maxvit_base_tf', pretrained=pretrained, **kwargs) @register_model def maxvit_base_tf_512(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxvit_base_tf_512', 'maxvit_base_tf', pretrained=pretrained, **kwargs) @register_model def maxvit_large_tf_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxvit_large_tf_224', 'maxvit_large_tf', pretrained=pretrained, **kwargs) @register_model def maxvit_large_tf_384(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxvit_large_tf_384', 'maxvit_large_tf', pretrained=pretrained, **kwargs) @register_model def maxvit_large_tf_512(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxvit_large_tf_512', 'maxvit_large_tf', pretrained=pretrained, **kwargs) @register_model def maxvit_xlarge_tf_224(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxvit_xlarge_tf_224', 'maxvit_xlarge_tf', pretrained=pretrained, **kwargs) @register_model def maxvit_xlarge_tf_384(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxvit_xlarge_tf_384', 'maxvit_xlarge_tf', pretrained=pretrained, **kwargs) @register_model def maxvit_xlarge_tf_512(pretrained=False, **kwargs) -> MaxxVit: return _create_maxxvit('maxvit_xlarge_tf_512', 'maxvit_xlarge_tf', pretrained=pretrained, **kwargs)
pytorch-image-models/timm/models/maxxvit.py/0
{ "file_path": "pytorch-image-models/timm/models/maxxvit.py", "repo_id": "pytorch-image-models", "token_count": 43954 }
206
""" An implementation of RepGhostNet Model as defined in: RepGhost: A Hardware-Efficient Ghost Module via Re-parameterization. https://arxiv.org/abs/2211.06088 Original implementation: https://github.com/ChengpengChen/RepGhost """ import copy from functools import partial from typing import Optional import torch import torch.nn as nn import torch.nn.functional as F from timm.data import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD from timm.layers import SelectAdaptivePool2d, Linear, make_divisible from ._builder import build_model_with_cfg from ._efficientnet_blocks import SqueezeExcite, ConvBnAct from ._manipulate import checkpoint_seq from ._registry import register_model, generate_default_cfgs __all__ = ['RepGhostNet'] _SE_LAYER = partial(SqueezeExcite, gate_layer='hard_sigmoid', rd_round_fn=partial(make_divisible, divisor=4)) class RepGhostModule(nn.Module): def __init__( self, in_chs, out_chs, kernel_size=1, dw_size=3, stride=1, relu=True, reparam=True, ): super(RepGhostModule, self).__init__() self.out_chs = out_chs init_chs = out_chs new_chs = out_chs self.primary_conv = nn.Sequential( nn.Conv2d(in_chs, init_chs, kernel_size, stride, kernel_size // 2, bias=False), nn.BatchNorm2d(init_chs), nn.ReLU(inplace=True) if relu else nn.Identity(), ) fusion_conv = [] fusion_bn = [] if reparam: fusion_conv.append(nn.Identity()) fusion_bn.append(nn.BatchNorm2d(init_chs)) self.fusion_conv = nn.Sequential(*fusion_conv) self.fusion_bn = nn.Sequential(*fusion_bn) self.cheap_operation = nn.Sequential( nn.Conv2d(init_chs, new_chs, dw_size, 1, dw_size//2, groups=init_chs, bias=False), nn.BatchNorm2d(new_chs), # nn.ReLU(inplace=True) if relu else nn.Identity(), ) self.relu = nn.ReLU(inplace=False) if relu else nn.Identity() def forward(self, x): x1 = self.primary_conv(x) x2 = self.cheap_operation(x1) for conv, bn in zip(self.fusion_conv, self.fusion_bn): x2 = x2 + bn(conv(x1)) return self.relu(x2) def get_equivalent_kernel_bias(self): kernel3x3, bias3x3 = self._fuse_bn_tensor(self.cheap_operation[0], self.cheap_operation[1]) for conv, bn in zip(self.fusion_conv, self.fusion_bn): kernel, bias = self._fuse_bn_tensor(conv, bn, kernel3x3.shape[0], kernel3x3.device) kernel3x3 += self._pad_1x1_to_3x3_tensor(kernel) bias3x3 += bias return kernel3x3, bias3x3 @staticmethod def _pad_1x1_to_3x3_tensor(kernel1x1): if kernel1x1 is None: return 0 else: return torch.nn.functional.pad(kernel1x1, [1, 1, 1, 1]) @staticmethod def _fuse_bn_tensor(conv, bn, in_channels=None, device=None): in_channels = in_channels if in_channels else bn.running_mean.shape[0] device = device if device else bn.weight.device if isinstance(conv, nn.Conv2d): kernel = conv.weight assert conv.bias is None else: assert isinstance(conv, nn.Identity) kernel = torch.ones(in_channels, 1, 1, 1, device=device) if isinstance(bn, nn.BatchNorm2d): running_mean = bn.running_mean running_var = bn.running_var gamma = bn.weight beta = bn.bias eps = bn.eps std = (running_var + eps).sqrt() t = (gamma / std).reshape(-1, 1, 1, 1) return kernel * t, beta - running_mean * gamma / std assert isinstance(bn, nn.Identity) return kernel, torch.zeros(in_channels).to(kernel.device) def switch_to_deploy(self): if len(self.fusion_conv) == 0 and len(self.fusion_bn) == 0: return kernel, bias = self.get_equivalent_kernel_bias() self.cheap_operation = nn.Conv2d( in_channels=self.cheap_operation[0].in_channels, out_channels=self.cheap_operation[0].out_channels, kernel_size=self.cheap_operation[0].kernel_size, padding=self.cheap_operation[0].padding, dilation=self.cheap_operation[0].dilation, groups=self.cheap_operation[0].groups, bias=True) self.cheap_operation.weight.data = kernel self.cheap_operation.bias.data = bias self.__delattr__('fusion_conv') self.__delattr__('fusion_bn') self.fusion_conv = [] self.fusion_bn = [] def reparameterize(self): self.switch_to_deploy() class RepGhostBottleneck(nn.Module): """ RepGhost bottleneck w/ optional SE""" def __init__( self, in_chs, mid_chs, out_chs, dw_kernel_size=3, stride=1, act_layer=nn.ReLU, se_ratio=0., reparam=True, ): super(RepGhostBottleneck, self).__init__() has_se = se_ratio is not None and se_ratio > 0. self.stride = stride # Point-wise expansion self.ghost1 = RepGhostModule(in_chs, mid_chs, relu=True, reparam=reparam) # Depth-wise convolution if self.stride > 1: self.conv_dw = nn.Conv2d( mid_chs, mid_chs, dw_kernel_size, stride=stride, padding=(dw_kernel_size-1)//2, groups=mid_chs, bias=False) self.bn_dw = nn.BatchNorm2d(mid_chs) else: self.conv_dw = None self.bn_dw = None # Squeeze-and-excitation self.se = _SE_LAYER(mid_chs, rd_ratio=se_ratio) if has_se else None # Point-wise linear projection self.ghost2 = RepGhostModule(mid_chs, out_chs, relu=False, reparam=reparam) # shortcut if in_chs == out_chs and self.stride == 1: self.shortcut = nn.Sequential() else: self.shortcut = nn.Sequential( nn.Conv2d( in_chs, in_chs, dw_kernel_size, stride=stride, padding=(dw_kernel_size-1)//2, groups=in_chs, bias=False), nn.BatchNorm2d(in_chs), nn.Conv2d(in_chs, out_chs, 1, stride=1, padding=0, bias=False), nn.BatchNorm2d(out_chs), ) def forward(self, x): shortcut = x # 1st ghost bottleneck x = self.ghost1(x) # Depth-wise convolution if self.conv_dw is not None: x = self.conv_dw(x) x = self.bn_dw(x) # Squeeze-and-excitation if self.se is not None: x = self.se(x) # 2nd ghost bottleneck x = self.ghost2(x) x += self.shortcut(shortcut) return x class RepGhostNet(nn.Module): def __init__( self, cfgs, num_classes=1000, width=1.0, in_chans=3, output_stride=32, global_pool='avg', drop_rate=0.2, reparam=True, ): super(RepGhostNet, self).__init__() # setting of inverted residual blocks assert output_stride == 32, 'only output_stride==32 is valid, dilation not supported' self.cfgs = cfgs self.num_classes = num_classes self.drop_rate = drop_rate self.grad_checkpointing = False self.feature_info = [] # building first layer stem_chs = make_divisible(16 * width, 4) self.conv_stem = nn.Conv2d(in_chans, stem_chs, 3, 2, 1, bias=False) self.feature_info.append(dict(num_chs=stem_chs, reduction=2, module=f'conv_stem')) self.bn1 = nn.BatchNorm2d(stem_chs) self.act1 = nn.ReLU(inplace=True) prev_chs = stem_chs # building inverted residual blocks stages = nn.ModuleList([]) block = RepGhostBottleneck stage_idx = 0 net_stride = 2 for cfg in self.cfgs: layers = [] s = 1 for k, exp_size, c, se_ratio, s in cfg: out_chs = make_divisible(c * width, 4) mid_chs = make_divisible(exp_size * width, 4) layers.append(block(prev_chs, mid_chs, out_chs, k, s, se_ratio=se_ratio, reparam=reparam)) prev_chs = out_chs if s > 1: net_stride *= 2 self.feature_info.append(dict( num_chs=prev_chs, reduction=net_stride, module=f'blocks.{stage_idx}')) stages.append(nn.Sequential(*layers)) stage_idx += 1 out_chs = make_divisible(exp_size * width * 2, 4) stages.append(nn.Sequential(ConvBnAct(prev_chs, out_chs, 1))) self.pool_dim = prev_chs = out_chs self.blocks = nn.Sequential(*stages) # building last several layers self.num_features = prev_chs self.head_hidden_size = out_chs = 1280 self.global_pool = SelectAdaptivePool2d(pool_type=global_pool) self.conv_head = nn.Conv2d(prev_chs, out_chs, 1, 1, 0, bias=True) self.act2 = nn.ReLU(inplace=True) self.flatten = nn.Flatten(1) if global_pool else nn.Identity() # don't flatten if pooling disabled self.classifier = Linear(out_chs, num_classes) if num_classes > 0 else nn.Identity() @torch.jit.ignore def group_matcher(self, coarse=False): matcher = dict( stem=r'^conv_stem|bn1', blocks=[ (r'^blocks\.(\d+)' if coarse else r'^blocks\.(\d+)\.(\d+)', None), (r'conv_head', (99999,)) ] ) return matcher @torch.jit.ignore def set_grad_checkpointing(self, enable=True): self.grad_checkpointing = enable @torch.jit.ignore def get_classifier(self) -> nn.Module: return self.classifier def reset_classifier(self, num_classes: int, global_pool: Optional[str] = None): self.num_classes = num_classes if global_pool is not None: # NOTE: cannot meaningfully change pooling of efficient head after creation self.global_pool = SelectAdaptivePool2d(pool_type=global_pool) self.flatten = nn.Flatten(1) if global_pool else nn.Identity() # don't flatten if pooling disabled self.classifier = Linear(self.head_hidden_size, num_classes) if num_classes > 0 else nn.Identity() def forward_features(self, x): x = self.conv_stem(x) x = self.bn1(x) x = self.act1(x) if self.grad_checkpointing and not torch.jit.is_scripting(): x = checkpoint_seq(self.blocks, x, flatten=True) else: x = self.blocks(x) return x def forward_head(self, x, pre_logits: bool = False): x = self.global_pool(x) x = self.conv_head(x) x = self.act2(x) x = self.flatten(x) if self.drop_rate > 0.: x = F.dropout(x, p=self.drop_rate, training=self.training) return x if pre_logits else self.classifier(x) def forward(self, x): x = self.forward_features(x) x = self.forward_head(x) return x def convert_to_deploy(self): repghost_model_convert(self, do_copy=False) def repghost_model_convert(model: torch.nn.Module, save_path=None, do_copy=True): """ taken from from https://github.com/DingXiaoH/RepVGG/blob/main/repvgg.py """ if do_copy: model = copy.deepcopy(model) for module in model.modules(): if hasattr(module, 'switch_to_deploy'): module.switch_to_deploy() if save_path is not None: torch.save(model.state_dict(), save_path) return model def _create_repghostnet(variant, width=1.0, pretrained=False, **kwargs): """ Constructs a RepGhostNet model """ cfgs = [ # k, t, c, SE, s # stage1 [[3, 8, 16, 0, 1]], # stage2 [[3, 24, 24, 0, 2]], [[3, 36, 24, 0, 1]], # stage3 [[5, 36, 40, 0.25, 2]], [[5, 60, 40, 0.25, 1]], # stage4 [[3, 120, 80, 0, 2]], [[3, 100, 80, 0, 1], [3, 120, 80, 0, 1], [3, 120, 80, 0, 1], [3, 240, 112, 0.25, 1], [3, 336, 112, 0.25, 1] ], # stage5 [[5, 336, 160, 0.25, 2]], [[5, 480, 160, 0, 1], [5, 480, 160, 0.25, 1], [5, 480, 160, 0, 1], [5, 480, 160, 0.25, 1] ] ] model_kwargs = dict( cfgs=cfgs, width=width, **kwargs, ) return build_model_with_cfg( RepGhostNet, variant, pretrained, feature_cfg=dict(flatten_sequential=True), **model_kwargs, ) def _cfg(url='', **kwargs): return { 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': (7, 7), 'crop_pct': 0.875, 'interpolation': 'bicubic', 'mean': IMAGENET_DEFAULT_MEAN, 'std': IMAGENET_DEFAULT_STD, 'first_conv': 'conv_stem', 'classifier': 'classifier', **kwargs } default_cfgs = generate_default_cfgs({ 'repghostnet_050.in1k': _cfg( hf_hub_id='timm/', # url='https://github.com/ChengpengChen/RepGhost/releases/download/RepGhost/repghostnet_0_5x_43M_66.95.pth.tar' ), 'repghostnet_058.in1k': _cfg( hf_hub_id='timm/', # url='https://github.com/ChengpengChen/RepGhost/releases/download/RepGhost/repghostnet_0_58x_60M_68.94.pth.tar' ), 'repghostnet_080.in1k': _cfg( hf_hub_id='timm/', # url='https://github.com/ChengpengChen/RepGhost/releases/download/RepGhost/repghostnet_0_8x_96M_72.24.pth.tar' ), 'repghostnet_100.in1k': _cfg( hf_hub_id='timm/', # url='https://github.com/ChengpengChen/RepGhost/releases/download/RepGhost/repghostnet_1_0x_142M_74.22.pth.tar' ), 'repghostnet_111.in1k': _cfg( hf_hub_id='timm/', # url='https://github.com/ChengpengChen/RepGhost/releases/download/RepGhost/repghostnet_1_11x_170M_75.07.pth.tar' ), 'repghostnet_130.in1k': _cfg( hf_hub_id='timm/', # url='https://github.com/ChengpengChen/RepGhost/releases/download/RepGhost/repghostnet_1_3x_231M_76.37.pth.tar' ), 'repghostnet_150.in1k': _cfg( hf_hub_id='timm/', # url='https://github.com/ChengpengChen/RepGhost/releases/download/RepGhost/repghostnet_1_5x_301M_77.45.pth.tar' ), 'repghostnet_200.in1k': _cfg( hf_hub_id='timm/', # url='https://github.com/ChengpengChen/RepGhost/releases/download/RepGhost/repghostnet_2_0x_516M_78.81.pth.tar' ), }) @register_model def repghostnet_050(pretrained=False, **kwargs) -> RepGhostNet: """ RepGhostNet-0.5x """ model = _create_repghostnet('repghostnet_050', width=0.5, pretrained=pretrained, **kwargs) return model @register_model def repghostnet_058(pretrained=False, **kwargs) -> RepGhostNet: """ RepGhostNet-0.58x """ model = _create_repghostnet('repghostnet_058', width=0.58, pretrained=pretrained, **kwargs) return model @register_model def repghostnet_080(pretrained=False, **kwargs) -> RepGhostNet: """ RepGhostNet-0.8x """ model = _create_repghostnet('repghostnet_080', width=0.8, pretrained=pretrained, **kwargs) return model @register_model def repghostnet_100(pretrained=False, **kwargs) -> RepGhostNet: """ RepGhostNet-1.0x """ model = _create_repghostnet('repghostnet_100', width=1.0, pretrained=pretrained, **kwargs) return model @register_model def repghostnet_111(pretrained=False, **kwargs) -> RepGhostNet: """ RepGhostNet-1.11x """ model = _create_repghostnet('repghostnet_111', width=1.11, pretrained=pretrained, **kwargs) return model @register_model def repghostnet_130(pretrained=False, **kwargs) -> RepGhostNet: """ RepGhostNet-1.3x """ model = _create_repghostnet('repghostnet_130', width=1.3, pretrained=pretrained, **kwargs) return model @register_model def repghostnet_150(pretrained=False, **kwargs) -> RepGhostNet: """ RepGhostNet-1.5x """ model = _create_repghostnet('repghostnet_150', width=1.5, pretrained=pretrained, **kwargs) return model @register_model def repghostnet_200(pretrained=False, **kwargs) -> RepGhostNet: """ RepGhostNet-2.0x """ model = _create_repghostnet('repghostnet_200', width=2.0, pretrained=pretrained, **kwargs) return model
pytorch-image-models/timm/models/repghost.py/0
{ "file_path": "pytorch-image-models/timm/models/repghost.py", "repo_id": "pytorch-image-models", "token_count": 8221 }
207
""" TResNet: High Performance GPU-Dedicated Architecture https://arxiv.org/pdf/2003.13630.pdf Original model: https://github.com/mrT23/TResNet """ from collections import OrderedDict from functools import partial from typing import Optional import torch import torch.nn as nn from timm.layers import SpaceToDepth, BlurPool2d, ClassifierHead, SEModule, ConvNormAct, DropPath from ._builder import build_model_with_cfg from ._manipulate import checkpoint_seq from ._registry import register_model, generate_default_cfgs, register_model_deprecations __all__ = ['TResNet'] # model_registry will add each entrypoint fn to this class BasicBlock(nn.Module): expansion = 1 def __init__( self, inplanes, planes, stride=1, downsample=None, use_se=True, aa_layer=None, drop_path_rate=0. ): super(BasicBlock, self).__init__() self.downsample = downsample self.stride = stride act_layer = partial(nn.LeakyReLU, negative_slope=1e-3) self.conv1 = ConvNormAct(inplanes, planes, kernel_size=3, stride=stride, act_layer=act_layer, aa_layer=aa_layer) self.conv2 = ConvNormAct(planes, planes, kernel_size=3, stride=1, apply_act=False) self.act = nn.ReLU(inplace=True) rd_chs = max(planes * self.expansion // 4, 64) self.se = SEModule(planes * self.expansion, rd_channels=rd_chs) if use_se else None self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0 else nn.Identity() def forward(self, x): if self.downsample is not None: shortcut = self.downsample(x) else: shortcut = x out = self.conv1(x) out = self.conv2(out) if self.se is not None: out = self.se(out) out = self.drop_path(out) + shortcut out = self.act(out) return out class Bottleneck(nn.Module): expansion = 4 def __init__( self, inplanes, planes, stride=1, downsample=None, use_se=True, act_layer=None, aa_layer=None, drop_path_rate=0., ): super(Bottleneck, self).__init__() self.downsample = downsample self.stride = stride act_layer = act_layer or partial(nn.LeakyReLU, negative_slope=1e-3) self.conv1 = ConvNormAct( inplanes, planes, kernel_size=1, stride=1, act_layer=act_layer) self.conv2 = ConvNormAct( planes, planes, kernel_size=3, stride=stride, act_layer=act_layer, aa_layer=aa_layer) reduction_chs = max(planes * self.expansion // 8, 64) self.se = SEModule(planes, rd_channels=reduction_chs) if use_se else None self.conv3 = ConvNormAct( planes, planes * self.expansion, kernel_size=1, stride=1, apply_act=False) self.drop_path = DropPath(drop_path_rate) if drop_path_rate > 0 else nn.Identity() self.act = nn.ReLU(inplace=True) def forward(self, x): if self.downsample is not None: shortcut = self.downsample(x) else: shortcut = x out = self.conv1(x) out = self.conv2(out) if self.se is not None: out = self.se(out) out = self.conv3(out) out = self.drop_path(out) + shortcut out = self.act(out) return out class TResNet(nn.Module): def __init__( self, layers, in_chans=3, num_classes=1000, width_factor=1.0, v2=False, global_pool='fast', drop_rate=0., drop_path_rate=0., ): self.num_classes = num_classes self.drop_rate = drop_rate self.grad_checkpointing = False super(TResNet, self).__init__() aa_layer = BlurPool2d act_layer = nn.LeakyReLU # TResnet stages self.inplanes = int(64 * width_factor) self.planes = int(64 * width_factor) if v2: self.inplanes = self.inplanes // 8 * 8 self.planes = self.planes // 8 * 8 dpr = [x.tolist() for x in torch.linspace(0, drop_path_rate, sum(layers)).split(layers)] conv1 = ConvNormAct(in_chans * 16, self.planes, stride=1, kernel_size=3, act_layer=act_layer) layer1 = self._make_layer( Bottleneck if v2 else BasicBlock, self.planes, layers[0], stride=1, use_se=True, aa_layer=aa_layer, drop_path_rate=dpr[0]) layer2 = self._make_layer( Bottleneck if v2 else BasicBlock, self.planes * 2, layers[1], stride=2, use_se=True, aa_layer=aa_layer, drop_path_rate=dpr[1]) layer3 = self._make_layer( Bottleneck, self.planes * 4, layers[2], stride=2, use_se=True, aa_layer=aa_layer, drop_path_rate=dpr[2]) layer4 = self._make_layer( Bottleneck, self.planes * 8, layers[3], stride=2, use_se=False, aa_layer=aa_layer, drop_path_rate=dpr[3]) # body self.body = nn.Sequential(OrderedDict([ ('s2d', SpaceToDepth()), ('conv1', conv1), ('layer1', layer1), ('layer2', layer2), ('layer3', layer3), ('layer4', layer4), ])) self.feature_info = [ dict(num_chs=self.planes, reduction=2, module=''), # Not with S2D? dict(num_chs=self.planes * (Bottleneck.expansion if v2 else 1), reduction=4, module='body.layer1'), dict(num_chs=self.planes * 2 * (Bottleneck.expansion if v2 else 1), reduction=8, module='body.layer2'), dict(num_chs=self.planes * 4 * Bottleneck.expansion, reduction=16, module='body.layer3'), dict(num_chs=self.planes * 8 * Bottleneck.expansion, reduction=32, module='body.layer4'), ] # head self.num_features = self.head_hidden_size = (self.planes * 8) * Bottleneck.expansion self.head = ClassifierHead(self.num_features, num_classes, pool_type=global_pool, drop_rate=drop_rate) # model initialization for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='leaky_relu') if isinstance(m, nn.Linear): m.weight.data.normal_(0, 0.01) # residual connections special initialization for m in self.modules(): if isinstance(m, BasicBlock): nn.init.zeros_(m.conv2.bn.weight) if isinstance(m, Bottleneck): nn.init.zeros_(m.conv3.bn.weight) def _make_layer(self, block, planes, blocks, stride=1, use_se=True, aa_layer=None, drop_path_rate=0.): downsample = None if stride != 1 or self.inplanes != planes * block.expansion: layers = [] if stride == 2: # avg pooling before 1x1 conv layers.append(nn.AvgPool2d(kernel_size=2, stride=2, ceil_mode=True, count_include_pad=False)) layers += [ConvNormAct( self.inplanes, planes * block.expansion, kernel_size=1, stride=1, apply_act=False)] downsample = nn.Sequential(*layers) layers = [] for i in range(blocks): layers.append(block( self.inplanes, planes, stride=stride if i == 0 else 1, downsample=downsample if i == 0 else None, use_se=use_se, aa_layer=aa_layer, drop_path_rate=drop_path_rate[i] if isinstance(drop_path_rate, list) else drop_path_rate, )) self.inplanes = planes * block.expansion return nn.Sequential(*layers) @torch.jit.ignore def group_matcher(self, coarse=False): matcher = dict(stem=r'^body\.conv1', blocks=r'^body\.layer(\d+)' if coarse else r'^body\.layer(\d+)\.(\d+)') return matcher @torch.jit.ignore def set_grad_checkpointing(self, enable=True): self.grad_checkpointing = enable @torch.jit.ignore def get_classifier(self) -> nn.Module: return self.head.fc def reset_classifier(self, num_classes: int, global_pool: Optional[str] = None): self.head.reset(num_classes, pool_type=global_pool) def forward_features(self, x): if self.grad_checkpointing and not torch.jit.is_scripting(): x = self.body.s2d(x) x = self.body.conv1(x) x = checkpoint_seq([ self.body.layer1, self.body.layer2, self.body.layer3, self.body.layer4], x, flatten=True) else: x = self.body(x) return x def forward_head(self, x, pre_logits: bool = False): return self.head(x, pre_logits=pre_logits) if pre_logits else self.head(x) def forward(self, x): x = self.forward_features(x) x = self.forward_head(x) return x def checkpoint_filter_fn(state_dict, model): if 'body.conv1.conv.weight' in state_dict: return state_dict import re state_dict = state_dict.get('model', state_dict) state_dict = state_dict.get('state_dict', state_dict) out_dict = {} for k, v in state_dict.items(): k = re.sub(r'conv(\d+)\.0.0', lambda x: f'conv{int(x.group(1))}.conv', k) k = re.sub(r'conv(\d+)\.0.1', lambda x: f'conv{int(x.group(1))}.bn', k) k = re.sub(r'conv(\d+)\.0', lambda x: f'conv{int(x.group(1))}.conv', k) k = re.sub(r'conv(\d+)\.1', lambda x: f'conv{int(x.group(1))}.bn', k) k = re.sub(r'downsample\.(\d+)\.0', lambda x: f'downsample.{int(x.group(1))}.conv', k) k = re.sub(r'downsample\.(\d+)\.1', lambda x: f'downsample.{int(x.group(1))}.bn', k) if k.endswith('bn.weight'): # convert weight from inplace_abn to batchnorm v = v.abs().add(1e-5) out_dict[k] = v return out_dict def _create_tresnet(variant, pretrained=False, **kwargs): return build_model_with_cfg( TResNet, variant, pretrained, pretrained_filter_fn=checkpoint_filter_fn, feature_cfg=dict(out_indices=(1, 2, 3, 4), flatten_sequential=True), **kwargs, ) def _cfg(url='', **kwargs): return { 'url': url, 'num_classes': 1000, 'input_size': (3, 224, 224), 'pool_size': (7, 7), 'crop_pct': 0.875, 'interpolation': 'bilinear', 'mean': (0., 0., 0.), 'std': (1., 1., 1.), 'first_conv': 'body.conv1.conv', 'classifier': 'head.fc', **kwargs } default_cfgs = generate_default_cfgs({ 'tresnet_m.miil_in21k_ft_in1k': _cfg(hf_hub_id='timm/'), 'tresnet_m.miil_in21k': _cfg(hf_hub_id='timm/', num_classes=11221), 'tresnet_m.miil_in1k': _cfg(hf_hub_id='timm/'), 'tresnet_l.miil_in1k': _cfg(hf_hub_id='timm/'), 'tresnet_xl.miil_in1k': _cfg(hf_hub_id='timm/'), 'tresnet_m.miil_in1k_448': _cfg( input_size=(3, 448, 448), pool_size=(14, 14), hf_hub_id='timm/'), 'tresnet_l.miil_in1k_448': _cfg( input_size=(3, 448, 448), pool_size=(14, 14), hf_hub_id='timm/'), 'tresnet_xl.miil_in1k_448': _cfg( input_size=(3, 448, 448), pool_size=(14, 14), hf_hub_id='timm/'), 'tresnet_v2_l.miil_in21k_ft_in1k': _cfg(hf_hub_id='timm/'), 'tresnet_v2_l.miil_in21k': _cfg(hf_hub_id='timm/', num_classes=11221), }) @register_model def tresnet_m(pretrained=False, **kwargs) -> TResNet: model_args = dict(layers=[3, 4, 11, 3]) return _create_tresnet('tresnet_m', pretrained=pretrained, **dict(model_args, **kwargs)) @register_model def tresnet_l(pretrained=False, **kwargs) -> TResNet: model_args = dict(layers=[4, 5, 18, 3], width_factor=1.2) return _create_tresnet('tresnet_l', pretrained=pretrained, **dict(model_args, **kwargs)) @register_model def tresnet_xl(pretrained=False, **kwargs) -> TResNet: model_args = dict(layers=[4, 5, 24, 3], width_factor=1.3) return _create_tresnet('tresnet_xl', pretrained=pretrained, **dict(model_args, **kwargs)) @register_model def tresnet_v2_l(pretrained=False, **kwargs) -> TResNet: model_args = dict(layers=[3, 4, 23, 3], width_factor=1.0, v2=True) return _create_tresnet('tresnet_v2_l', pretrained=pretrained, **dict(model_args, **kwargs)) register_model_deprecations(__name__, { 'tresnet_m_miil_in21k': 'tresnet_m.miil_in21k', 'tresnet_m_448': 'tresnet_m.miil_in1k_448', 'tresnet_l_448': 'tresnet_l.miil_in1k_448', 'tresnet_xl_448': 'tresnet_xl.miil_in1k_448', })
pytorch-image-models/timm/models/tresnet.py/0
{ "file_path": "pytorch-image-models/timm/models/tresnet.py", "repo_id": "pytorch-image-models", "token_count": 6171 }
208
""" Adafactor Optimizer Lifted from https://github.com/pytorch/fairseq/blob/master/fairseq/optim/adafactor.py Original header/copyright below. """ # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch import math class Adafactor(torch.optim.Optimizer): """Implements Adafactor algorithm. This implementation is based on: `Adafactor: Adaptive Learning Rates with Sublinear Memory Cost` (see https://arxiv.org/abs/1804.04235) Note that this optimizer internally adjusts the learning rate depending on the *scale_parameter*, *relative_step* and *warmup_init* options. To use a manual (external) learning rate schedule you should set `scale_parameter=False` and `relative_step=False`. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float, optional): external learning rate (default: None) eps (tuple[float, float]): regularization constants for square gradient and parameter scale respectively (default: (1e-30, 1e-3)) clip_threshold (float): threshold of root mean square of final gradient update (default: 1.0) decay_rate (float): coefficient used to compute running averages of square gradient (default: -0.8) beta1 (float): coefficient used for computing running averages of gradient (default: None) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) scale_parameter (bool): if True, learning rate is scaled by root mean square of parameter (default: True) warmup_init (bool): time-dependent learning rate computation depends on whether warm-up initialization is being used (default: False) """ def __init__(self, params, lr=None, eps=1e-30, eps_scale=1e-3, clip_threshold=1.0, decay_rate=-0.8, betas=None, weight_decay=0.0, scale_parameter=True, warmup_init=False): relative_step = not lr if warmup_init and not relative_step: raise ValueError('warmup_init requires relative_step=True') beta1 = None if betas is None else betas[0] # make it compat with standard betas arg defaults = dict(lr=lr, eps=eps, eps_scale=eps_scale, clip_threshold=clip_threshold, decay_rate=decay_rate, beta1=beta1, weight_decay=weight_decay, scale_parameter=scale_parameter, relative_step=relative_step, warmup_init=warmup_init) super(Adafactor, self).__init__(params, defaults) @staticmethod def _get_lr(param_group, param_state): if param_group['relative_step']: min_step = 1e-6 * param_state['step'] if param_group['warmup_init'] else 1e-2 lr_t = min(min_step, 1.0 / math.sqrt(param_state['step'])) param_scale = 1.0 if param_group['scale_parameter']: param_scale = max(param_group['eps_scale'], param_state['RMS']) param_group['lr'] = lr_t * param_scale return param_group['lr'] @staticmethod def _get_options(param_group, param_shape): factored = len(param_shape) >= 2 use_first_moment = param_group['beta1'] is not None return factored, use_first_moment @staticmethod def _rms(tensor): return tensor.norm(2) / (tensor.numel() ** 0.5) def _approx_sq_grad(self, exp_avg_sq_row, exp_avg_sq_col): r_factor = (exp_avg_sq_row / exp_avg_sq_row.mean(dim=-1, keepdim=True)).rsqrt_().unsqueeze(-1) c_factor = exp_avg_sq_col.unsqueeze(-2).rsqrt() return torch.mul(r_factor, c_factor) @torch.no_grad() def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: for p in group['params']: if p.grad is None: continue grad = p.grad if grad.dtype in {torch.float16, torch.bfloat16}: grad = grad.float() if grad.is_sparse: raise RuntimeError('Adafactor does not support sparse gradients.') state = self.state[p] factored, use_first_moment = self._get_options(group, grad.shape) # State Initialization if len(state) == 0: state['step'] = 0 if use_first_moment: # Exponential moving average of gradient values state['exp_avg'] = torch.zeros_like(grad) if factored: state['exp_avg_sq_row'] = torch.zeros(grad.shape[:-1]).to(grad) state['exp_avg_sq_col'] = torch.zeros(grad.shape[:-2] + grad.shape[-1:]).to(grad) else: state['exp_avg_sq'] = torch.zeros_like(grad) state['RMS'] = 0 else: if use_first_moment: state['exp_avg'] = state['exp_avg'].to(grad) if factored: state['exp_avg_sq_row'] = state['exp_avg_sq_row'].to(grad) state['exp_avg_sq_col'] = state['exp_avg_sq_col'].to(grad) else: state['exp_avg_sq'] = state['exp_avg_sq'].to(grad) p_fp32 = p if p.dtype in {torch.float16, torch.bfloat16}: p_fp32 = p_fp32.float() state['step'] += 1 state['RMS'] = self._rms(p_fp32) lr_t = self._get_lr(group, state) beta2t = 1.0 - math.pow(state['step'], group['decay_rate']) update = grad ** 2 + group['eps'] if factored: exp_avg_sq_row = state['exp_avg_sq_row'] exp_avg_sq_col = state['exp_avg_sq_col'] exp_avg_sq_row.mul_(beta2t).add_(update.mean(dim=-1), alpha=1.0 - beta2t) exp_avg_sq_col.mul_(beta2t).add_(update.mean(dim=-2), alpha=1.0 - beta2t) # Approximation of exponential moving average of square of gradient update = self._approx_sq_grad(exp_avg_sq_row, exp_avg_sq_col) update.mul_(grad) else: exp_avg_sq = state['exp_avg_sq'] exp_avg_sq.mul_(beta2t).add_(update, alpha=1.0 - beta2t) update = exp_avg_sq.rsqrt().mul_(grad) update.div_((self._rms(update) / group['clip_threshold']).clamp_(min=1.0)) update.mul_(lr_t) if use_first_moment: exp_avg = state['exp_avg'] exp_avg.mul_(group['beta1']).add_(update, alpha=1 - group['beta1']) update = exp_avg if group['weight_decay'] != 0: p_fp32.add_(p_fp32, alpha=-group['weight_decay'] * lr_t) p_fp32.add_(-update) if p.dtype in {torch.float16, torch.bfloat16}: p.copy_(p_fp32) return loss
pytorch-image-models/timm/optim/adafactor.py/0
{ "file_path": "pytorch-image-models/timm/optim/adafactor.py", "repo_id": "pytorch-image-models", "token_count": 3656 }
209
""" SGDP Optimizer Implementation copied from https://github.com/clovaai/AdamP/blob/master/adamp/sgdp.py Paper: `Slowing Down the Weight Norm Increase in Momentum-based Optimizers` - https://arxiv.org/abs/2006.08217 Code: https://github.com/clovaai/AdamP Copyright (c) 2020-present NAVER Corp. MIT license """ import torch import torch.nn.functional as F from torch.optim.optimizer import Optimizer, required import math from .adamp import projection class SGDP(Optimizer): def __init__(self, params, lr=required, momentum=0, dampening=0, weight_decay=0, nesterov=False, eps=1e-8, delta=0.1, wd_ratio=0.1): defaults = dict( lr=lr, momentum=momentum, dampening=dampening, weight_decay=weight_decay, nesterov=nesterov, eps=eps, delta=delta, wd_ratio=wd_ratio) super(SGDP, self).__init__(params, defaults) @torch.no_grad() def step(self, closure=None): loss = None if closure is not None: with torch.enable_grad(): loss = closure() for group in self.param_groups: weight_decay = group['weight_decay'] momentum = group['momentum'] dampening = group['dampening'] nesterov = group['nesterov'] for p in group['params']: if p.grad is None: continue grad = p.grad state = self.state[p] # State initialization if len(state) == 0: state['momentum'] = torch.zeros_like(p) # SGD buf = state['momentum'] buf.mul_(momentum).add_(grad, alpha=1. - dampening) if nesterov: d_p = grad + momentum * buf else: d_p = buf # Projection wd_ratio = 1. if len(p.shape) > 1: d_p, wd_ratio = projection(p, grad, d_p, group['delta'], group['wd_ratio'], group['eps']) # Weight decay if weight_decay != 0: p.mul_(1. - group['lr'] * group['weight_decay'] * wd_ratio / (1-momentum)) # Step p.add_(d_p, alpha=-group['lr']) return loss
pytorch-image-models/timm/optim/sgdp.py/0
{ "file_path": "pytorch-image-models/timm/optim/sgdp.py", "repo_id": "pytorch-image-models", "token_count": 1186 }
210
""" CUDA / AMP utils Hacked together by / Copyright 2020 Ross Wightman """ import torch try: from apex import amp has_apex = True except ImportError: amp = None has_apex = False from .clip_grad import dispatch_clip_grad class ApexScaler: state_dict_key = "amp" def __call__( self, loss, optimizer, clip_grad=None, clip_mode='norm', parameters=None, create_graph=False, need_update=True, ): with amp.scale_loss(loss, optimizer) as scaled_loss: scaled_loss.backward(create_graph=create_graph) if need_update: if clip_grad is not None: dispatch_clip_grad(amp.master_params(optimizer), clip_grad, mode=clip_mode) optimizer.step() def state_dict(self): if 'state_dict' in amp.__dict__: return amp.state_dict() def load_state_dict(self, state_dict): if 'load_state_dict' in amp.__dict__: amp.load_state_dict(state_dict) class NativeScaler: state_dict_key = "amp_scaler" def __init__(self): self._scaler = torch.cuda.amp.GradScaler() def __call__( self, loss, optimizer, clip_grad=None, clip_mode='norm', parameters=None, create_graph=False, need_update=True, ): self._scaler.scale(loss).backward(create_graph=create_graph) if need_update: if clip_grad is not None: assert parameters is not None self._scaler.unscale_(optimizer) # unscale the gradients of optimizer's assigned params in-place dispatch_clip_grad(parameters, clip_grad, mode=clip_mode) self._scaler.step(optimizer) self._scaler.update() def state_dict(self): return self._scaler.state_dict() def load_state_dict(self, state_dict): self._scaler.load_state_dict(state_dict)
pytorch-image-models/timm/utils/cuda.py/0
{ "file_path": "pytorch-image-models/timm/utils/cuda.py", "repo_id": "pytorch-image-models", "token_count": 980 }
211
use std::fs; fn main() -> Result<(), Box<dyn std::error::Error>> { println!("cargo:rerun-if-changed=../../proto/"); fs::create_dir_all("src/v2/pb").unwrap_or(()); let mut config = prost_build::Config::new(); config.protoc_arg("--experimental_allow_proto3_optional"); tonic_build::configure() .build_client(true) .build_server(false) .out_dir("src/v2/pb") .include_file("mod.rs") .compile_with_config(config, &["../../proto/generate.proto"], &["../../proto"]) .map_err(|e| match e.kind(){ std::io::ErrorKind::NotFound => {panic!("`protoc` not found, install libprotoc")}, std::io::ErrorKind::Other => {panic!("`protoc` version unsupported, upgrade protoc: https://github.com/protocolbuffers/protobuf/releases")}, e => {e} }).unwrap_or_else(|e| panic!("protobuf compilation failed: {e}")); fs::create_dir_all("src/v3/pb").unwrap_or(()); let mut config = prost_build::Config::new(); config.protoc_arg("--experimental_allow_proto3_optional"); tonic_build::configure() .build_client(true) .build_server(false) .out_dir("src/v3/pb") .include_file("mod.rs") .compile_with_config(config, &["../../proto/v3/generate.proto"], &["../../proto"]) .unwrap_or_else(|e| panic!("protobuf compilation failed: {e}")); Ok(()) }
text-generation-inference/backends/client/build.rs/0
{ "file_path": "text-generation-inference/backends/client/build.rs", "repo_id": "text-generation-inference", "token_count": 624 }
212
fetchcontent_declare( json URL https://github.com/nlohmann/json/releases/download/v3.11.3/json.tar.xz ) fetchcontent_makeavailable(json)
text-generation-inference/backends/trtllm/cmake/json.cmake/0
{ "file_path": "text-generation-inference/backends/trtllm/cmake/json.cmake", "repo_id": "text-generation-inference", "token_count": 68 }
213
use std::sync::Arc; use criterion::{black_box, criterion_group, criterion_main, Criterion}; use rand::Rng; use text_generation_router_v3::block_allocator::Allocator; use text_generation_router_v3::radix::RadixAllocator; fn prefix_cache_benchmark(c: &mut Criterion) { // let prefixes: Vec<Vec<u32>> = (0..8192) // .chunks(256) // .into_iter() // .map(|c| c.collect()) // .collect(); let mut cache = RadixAllocator::new(1, 262144, None); c.bench_function("Radix allocator", |b| { b.iter_batched( || { //prefixes // .choose_multiple(&mut rand::thread_rng(), 5) // .fold(Vec::new(), |mut v, s| { // v.extend(s); // v // }) (0..7936) .map(|_| rand::thread_rng().gen_range(0..1024)) .collect::<Vec<u32>>() }, |prefill| { let alloc = cache.allocate( prefill.len() as u32 + 13, Some(Arc::new(black_box(prefill))), ); if let Some(alloc) = alloc { cache.free(alloc.blocks.clone(), alloc.allocation_id); } }, criterion::BatchSize::SmallInput, ); }); } criterion_group!(benches, prefix_cache_benchmark); criterion_main!(benches);
text-generation-inference/backends/v3/benches/prefix_cache.rs/0
{ "file_path": "text-generation-inference/backends/v3/benches/prefix_cache.rs", "repo_id": "text-generation-inference", "token_count": 806 }
214
mod app; mod event; mod generation; mod table; mod utils; use crate::app::App; use crate::event::Event; use crossterm::ExecutableCommand; use std::io; use text_generation_client::v3::{GrammarType, NextTokenChooserParameters, ShardedClient}; use tokenizers::Tokenizer; use tokio::sync::{broadcast, mpsc}; use tui::backend::CrosstermBackend; use tui::Terminal; /// Run benchmarking app #[allow(clippy::too_many_arguments)] pub async fn run( tokenizer_name: String, tokenizer: Tokenizer, batch_size: Vec<u32>, sequence_length: u32, decode_length: u32, top_n_tokens: Option<u32>, n_runs: usize, warmups: usize, temperature: Option<f32>, top_k: Option<u32>, top_p: Option<f32>, typical_p: Option<f32>, repetition_penalty: Option<f32>, frequency_penalty: Option<f32>, watermark: bool, do_sample: bool, client: ShardedClient, ) -> Result<(), std::io::Error> { let parameters = NextTokenChooserParameters { temperature: temperature.unwrap_or(1.0), top_k: top_k.unwrap_or(0), top_p: top_p.unwrap_or(1.0), typical_p: typical_p.unwrap_or(1.0), do_sample, seed: 0, repetition_penalty: repetition_penalty.unwrap_or(1.0), frequency_penalty: frequency_penalty.unwrap_or(0.0), watermark, grammar: String::new(), grammar_type: GrammarType::None as i32, }; // Initialize terminal properties crossterm::terminal::enable_raw_mode()?; io::stdout().execute(crossterm::terminal::EnterAlternateScreen)?; io::stdout().execute(crossterm::cursor::Hide)?; // Initialize terminal let mut terminal = { let backend = CrosstermBackend::new(io::stdout()); Terminal::new(backend)? }; // Create message channel between generation_task and app let (run_sender, run_receiver) = mpsc::channel(8); // Crossterm event channel let (event_sender, mut event_receiver) = mpsc::channel(8); // Shutdown channel to terminate tasks let (shutdown_sender, _) = broadcast::channel(1); // Channel to check if tasks terminated let (shutdown_guard_sender, mut shutdown_guard_receiver) = mpsc::channel(1); // Create generation task tokio::spawn(generation::generation_task( tokenizer, batch_size.clone(), sequence_length, decode_length, top_n_tokens, n_runs, warmups, parameters, client, run_sender, shutdown_sender.subscribe(), shutdown_guard_sender.clone(), )); // Create event task tokio::spawn(event::terminal_event_task( 250, event_sender, shutdown_sender.subscribe(), shutdown_guard_sender.clone(), )); // Drop our end of shutdown sender drop(shutdown_guard_sender); // Create App let mut app = App::new( run_receiver, tokenizer_name.clone(), sequence_length, decode_length, n_runs, batch_size, ); while app.running { // Draw frame terminal.draw(|frame| app.render(frame))?; // Await a new event from event handling task match event_receiver.recv().await { None => break, // Update app state Some(event) => match event { Event::Tick => app.tick(), Event::Key(key_event) => app.handle_key_event(key_event), _ => {} }, } } // Ask tasks to shutdown let _ = shutdown_sender.send(()); // Wait for tasks to shutdown let _ = shutdown_guard_receiver.recv().await; // Revert terminal to original view io::stdout().execute(crossterm::terminal::LeaveAlternateScreen)?; crossterm::terminal::disable_raw_mode()?; io::stdout().execute(crossterm::cursor::Show)?; let parameters_table = table::parameters_table( tokenizer_name, sequence_length, decode_length, top_n_tokens, n_runs, warmups, temperature, top_k, top_p, typical_p, repetition_penalty, frequency_penalty, watermark, do_sample, ); println!("\n{parameters_table}\n"); let latency_table = table::latency_table(&app.data); println!("\n{latency_table}\n"); let throughput_table = table::throughput_table(&app.data); println!("\n{throughput_table}\n"); Ok(()) }
text-generation-inference/benchmark/src/lib.rs/0
{ "file_path": "text-generation-inference/benchmark/src/lib.rs", "repo_id": "text-generation-inference", "token_count": 1949 }
215
from typing import Dict # Text Generation Inference Errors class ValidationError(Exception): def __init__(self, message: str): super().__init__(message) class GenerationError(Exception): def __init__(self, message: str): super().__init__(message) class OverloadedError(Exception): def __init__(self, message: str): super().__init__(message) class IncompleteGenerationError(Exception): def __init__(self, message: str): super().__init__(message) # API Inference Errors class BadRequestError(Exception): def __init__(self, message: str): super().__init__(message) class ShardNotReadyError(Exception): def __init__(self, message: str): super().__init__(message) class ShardTimeoutError(Exception): def __init__(self, message: str): super().__init__(message) class NotFoundError(Exception): def __init__(self, message: str): super().__init__(message) class RateLimitExceededError(Exception): def __init__(self, message: str): super().__init__(message) class NotSupportedError(Exception): def __init__(self, model_id: str): message = ( f"Model `{model_id}` is not available for inference with this client. \n" "Use `huggingface_hub.inference_api.InferenceApi` instead." ) super(NotSupportedError, self).__init__(message) # Unknown error class UnknownError(Exception): def __init__(self, message: str): super().__init__(message) def parse_error(status_code: int, payload: Dict[str, str]) -> Exception: """ Parse error given an HTTP status code and a json payload Args: status_code (`int`): HTTP status code payload (`Dict[str, str]`): Json payload Returns: Exception: parsed exception """ # Try to parse a Text Generation Inference error message = payload["error"] if "error_type" in payload: error_type = payload["error_type"] if error_type == "generation": return GenerationError(message) if error_type == "incomplete_generation": return IncompleteGenerationError(message) if error_type == "overloaded": return OverloadedError(message) if error_type == "validation": return ValidationError(message) # Try to parse a APIInference error if status_code == 400: return BadRequestError(message) if status_code == 403 or status_code == 424: return ShardNotReadyError(message) if status_code == 504: return ShardTimeoutError(message) if status_code == 404: return NotFoundError(message) if status_code == 429: return RateLimitExceededError(message) # Fallback to an unknown error return UnknownError(message)
text-generation-inference/clients/python/text_generation/errors.py/0
{ "file_path": "text-generation-inference/clients/python/text_generation/errors.py", "repo_id": "text-generation-inference", "token_count": 1080 }
216
# Guidance Text Generation Inference (TGI) now supports [JSON and regex grammars](#grammar-and-constraints) and [tools and functions](#tools-and-functions) to help developers guide LLM responses to fit their needs. These feature are available starting from version `1.4.3`. They are accessible via the [`huggingface_hub`](https://pypi.org/project/huggingface-hub/) library. The tool support is compatible with OpenAI's client libraries. The following guide will walk you through the new features and how to use them! _note: guidance is supported as grammar in the `/generate` endpoint and as tools in the `v1/chat/completions` endpoint._ ## How it works TGI leverages the [outlines](https://github.com/outlines-dev/outlines) library to efficiently parse and compile the grammatical structures and tools specified by users. This integration transforms the defined grammars into an intermediate representation that acts as a framework to guide and constrain content generation, ensuring that outputs adhere to the specified grammatical rules. If you are interested in the technical details on how outlines is used in TGI, you can check out the [conceptual guidance documentation](../conceptual/guidance). ## Table of Contents 📚 ### Grammar and Constraints - [The Grammar Parameter](#the-grammar-parameter): Shape your AI's responses with precision. - [Constrain with Pydantic](#constrain-with-pydantic): Define a grammar using Pydantic models. - [JSON Schema Integration](#json-schema-integration): Fine-grained control over your requests via JSON schema. - [Using the client](#using-the-client): Use TGI's client libraries to shape the AI's responses. ### Tools and Functions - [The Tools Parameter](#the-tools-parameter): Enhance the AI's capabilities with predefined functions. - [Via the client](#text-generation-inference-client): Use TGI's client libraries to interact with the Messages API and Tool functions. - [OpenAI integration](#openai-integration): Use OpenAI's client libraries to interact with TGI's Messages API and Tool functions. ## Grammar and Constraints 🛣️ ### The Grammar Parameter In TGI `1.4.3`, we've introduced the grammar parameter, which allows you to specify the format of the response you want from the LLM. Using curl, you can make a request to TGI's Messages API with the grammar parameter. This is the most primitive way to interact with the API and using [Pydantic](#constrain-with-pydantic) is recommended for ease of use and readability. ```json curl localhost:3000/generate \ -X POST \ -H 'Content-Type: application/json' \ -d '{ "inputs": "I saw a puppy a cat and a raccoon during my bike ride in the park", "parameters": { "repetition_penalty": 1.3, "grammar": { "type": "json", "value": { "properties": { "location": { "type": "string" }, "activity": { "type": "string" }, "animals_seen": { "type": "integer", "minimum": 1, "maximum": 5 }, "animals": { "type": "array", "items": { "type": "string" } } }, "required": ["location", "activity", "animals_seen", "animals"] } } } }' // {"generated_text":"{ \n\n\"activity\": \"biking\",\n\"animals\": [\"puppy\",\"cat\",\"raccoon\"],\n\"animals_seen\": 3,\n\"location\": \"park\"\n}"} ``` ### Hugging Face Hub Python Library The Hugging Face Hub Python library provides a client that makes it easy to interact with the Messages API. Here's an example of how to use the client to send a request with a grammar parameter. ```python from huggingface_hub import InferenceClient client = InferenceClient("http://localhost:3000") schema = { "properties": { "location": {"title": "Location", "type": "string"}, "activity": {"title": "Activity", "type": "string"}, "animals_seen": { "maximum": 5, "minimum": 1, "title": "Animals Seen", "type": "integer", }, "animals": {"items": {"type": "string"}, "title": "Animals", "type": "array"}, }, "required": ["location", "activity", "animals_seen", "animals"], "title": "Animals", "type": "object", } user_input = "I saw a puppy a cat and a raccoon during my bike ride in the park" resp = client.text_generation( f"convert to JSON: 'f{user_input}'. please use the following schema: {schema}", max_new_tokens=100, seed=42, grammar={"type": "json", "value": schema}, ) print(resp) # { "activity": "bike ride", "animals": ["puppy", "cat", "raccoon"], "animals_seen": 3, "location": "park" } ``` A grammar can be defined using Pydantic models, JSON schemas, or regular expressions. The LLM will then generate a response that conforms to the specified grammar. > Note: A grammar must compile to an intermediate representation to constrain the output. Grammar compilation is a computationally expensive and may take a few seconds to complete on the first request. Subsequent requests will use the cached grammar and will be much faster. ### Constrain with Pydantic Using Pydantic models we can define a similar grammar as the previous example in a shorter and more readable way. ```python from huggingface_hub import InferenceClient from pydantic import BaseModel, conint from typing import List class Animals(BaseModel): location: str activity: str animals_seen: conint(ge=1, le=5) # Constrained integer type animals: List[str] client = InferenceClient("http://localhost:3000") user_input = "I saw a puppy a cat and a raccoon during my bike ride in the park" resp = client.text_generation( f"convert to JSON: 'f{user_input}'. please use the following schema: {Animals.schema()}", max_new_tokens=100, seed=42, grammar={"type": "json", "value": Animals.schema()}, ) print(resp) # { "activity": "bike ride", "animals": ["puppy", "cat", "raccoon"], "animals_seen": 3, "location": "park" } ``` defining a grammar as regular expressions ```python from huggingface_hub import InferenceClient client = InferenceClient("http://localhost:3000") section_regex = "(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" regexp = f"HELLO\.{section_regex}\.WORLD\.{section_regex}" # This is a more realistic example of an ip address regex # regexp = f"{section_regex}\.{section_regex}\.{section_regex}\.{section_regex}" resp = client.text_generation( f"Whats Googles DNS? Please use the following regex: {regexp}", seed=42, grammar={ "type": "regex", "value": regexp, }, ) print(resp) # HELLO.255.WORLD.255 ``` ## Tools and Functions 🛠️ ### The Tools Parameter In addition to the grammar parameter, we've also introduced a set of tools and functions to help you get the most out of the Messages API. Tools are a set of user defined functions that can be used in tandem with the chat functionality to enhance the LLM's capabilities. Functions, similar to grammar are defined as JSON schema and can be passed as part of the parameters to the Messages API. Functions, similar to grammar are defined as JSON schema and can be passed as part of the parameters to the Messages API. ```json curl localhost:3000/v1/chat/completions \ -X POST \ -H 'Content-Type: application/json' \ -d '{ "model": "tgi", "messages": [ { "role": "user", "content": "What is the weather like in New York?" } ], "tools": [ { "type": "function", "function": { "name": "get_current_weather", "description": "Get the current weather", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA" }, "format": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "The temperature unit to use. Infer this from the users location." } }, "required": ["location", "format"] } } } ], "tool_choice": "get_current_weather" }' // {"id":"","object":"text_completion","created":1709051640,"model":"HuggingFaceH4/zephyr-7b-beta","system_fingerprint":"1.4.3-native","choices":[{"index":0,"message":{"role":"assistant","tool_calls":{"id":0,"type":"function","function":{"description":null,"name":"tools","parameters":{"format":"celsius","location":"New York"}}}},"logprobs":null,"finish_reason":"eos_token"}],"usage":{"prompt_tokens":157,"completion_tokens":19,"total_tokens":176}} ``` ### Chat Completion with Tools Grammars are supported in the `/generate` endpoint, while tools are supported in the `/chat/completions` endpoint. Here's an example of how to use the client to send a request with a tool parameter. ```python from huggingface_hub import InferenceClient client = InferenceClient("http://localhost:3000") tools = [ { "type": "function", "function": { "name": "get_current_weather", "description": "Get the current weather", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA", }, "format": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "The temperature unit to use. Infer this from the users location.", }, }, "required": ["location", "format"], }, }, }, { "type": "function", "function": { "name": "get_n_day_weather_forecast", "description": "Get an N-day weather forecast", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA", }, "format": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "The temperature unit to use. Infer this from the users location.", }, "num_days": { "type": "integer", "description": "The number of days to forecast", }, }, "required": ["location", "format", "num_days"], }, }, }, ] chat = client.chat_completion( messages=[ { "role": "system", "content": "You're a helpful assistant! Answer the users question best you can.", }, { "role": "user", "content": "What is the weather like in Brooklyn, New York?", }, ], tools=tools, seed=42, max_tokens=100, ) print(chat.choices[0].message.tool_calls) # [ChatCompletionOutputToolCall(function=ChatCompletionOutputFunctionDefinition(arguments={'format': 'fahrenheit', 'location': 'Brooklyn, New York', 'num_days': 7}, name='get_n_day_weather_forecast', description=None), id=0, type='function')] ``` ### OpenAI integration TGI exposes an OpenAI-compatible API, which means you can use OpenAI's client libraries to interact with TGI's Messages API and Tool functions. However there are some minor differences in the API, for example `tool_choice="auto"` will ALWAYS choose the tool for you. This is different from OpenAI's API where `tool_choice="auto"` will choose a tool if the model thinks it's necessary. ```python from openai import OpenAI # Initialize the client, pointing it to one of the available models client = OpenAI( base_url="http://localhost:3000/v1", api_key="_", ) # NOTE: tools defined above and removed for brevity chat_completion = client.chat.completions.create( model="tgi", messages=[ { "role": "system", "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.", }, { "role": "user", "content": "What's the weather like the next 3 days in San Francisco, CA?", }, ], tools=tools, tool_choice="auto", # tool selected by model max_tokens=500, ) called = chat_completion.choices[0].message.tool_calls print(called) # { # "id": 0, # "type": "function", # "function": { # "description": None, # "name": "tools", # "parameters": { # "format": "celsius", # "location": "San Francisco, CA", # "num_days": 3, # }, # }, # } ```
text-generation-inference/docs/source/basic_tutorials/using_guidance.md/0
{ "file_path": "text-generation-inference/docs/source/basic_tutorials/using_guidance.md", "repo_id": "text-generation-inference", "token_count": 5583 }
217
# Using TGI with Intel GPUs TGI optimized models are supported on Intel Data Center GPU [Max1100](https://www.intel.com/content/www/us/en/products/sku/232876/intel-data-center-gpu-max-1100/specifications.html), [Max1550](https://www.intel.com/content/www/us/en/products/sku/232873/intel-data-center-gpu-max-1550/specifications.html), the recommended usage is through Docker. On a server powered by Intel GPUs, TGI can be launched with the following command: ```bash model=teknium/OpenHermes-2.5-Mistral-7B volume=$PWD/data # share a volume with the Docker container to avoid downloading weights every run docker run --rm --privileged --cap-add=sys_nice \ --device=/dev/dri \ --ipc=host --shm-size 1g --net host -v $volume:/data \ ghcr.io/huggingface/text-generation-inference:2.2.0-intel-xpu \ --model-id $model --cuda-graphs 0 ``` # Using TGI with Intel CPUs Intel® Extension for PyTorch (IPEX) also provides further optimizations for Intel CPUs. The IPEX provides optimization operations such as flash attention, page attention, Add + LayerNorm, ROPE and more. On a server powered by Intel CPU, TGI can be launched with the following command: ```bash model=teknium/OpenHermes-2.5-Mistral-7B volume=$PWD/data # share a volume with the Docker container to avoid downloading weights every run docker run --rm --privileged --cap-add=sys_nice \ --device=/dev/dri \ --ipc=host --shm-size 1g --net host -v $volume:/data \ ghcr.io/huggingface/text-generation-inference:2.2.0-intel-cpu \ --model-id $model --cuda-graphs 0 ``` The launched TGI server can then be queried from clients, make sure to check out the [Consuming TGI](./basic_tutorials/consuming_tgi) guide.
text-generation-inference/docs/source/installation_intel.md/0
{ "file_path": "text-generation-inference/docs/source/installation_intel.md", "repo_id": "text-generation-inference", "token_count": 562 }
218
{ "details": { "best_of_sequences": null, "finish_reason": "length", "generated_tokens": 10, "prefill": [ { "id": 1, "logprob": null, "text": "<s>" }, { "id": 4321, "logprob": -8.6875, "text": "Test" }, { "id": 2009, "logprob": -11.546875, "text": "request" } ], "seed": null, "tokens": [ { "id": 363, "logprob": -1.5351562, "special": false, "text": " for" }, { "id": 847, "logprob": -2.5722656, "special": false, "text": " /" }, { "id": 2754, "logprob": -2.2714844, "special": false, "text": "api" }, { "id": 29914, "logprob": -0.03414917, "special": false, "text": "/" }, { "id": 29894, "logprob": -0.95996094, "special": false, "text": "v" }, { "id": 29896, "logprob": -0.3635254, "special": false, "text": "1" }, { "id": 29914, "logprob": -0.013031006, "special": false, "text": "/" }, { "id": 16418, "logprob": -3.1523438, "special": false, "text": "projects" }, { "id": 29914, "logprob": -0.43701172, "special": false, "text": "/" }, { "id": 29896, "logprob": -1.9394531, "special": false, "text": "1" } ], "top_tokens": null }, "generated_text": " for /api/v1/projects/1" }
text-generation-inference/integration-tests/models/__snapshots__/test_flash_llama/test_flash_llama.json/0
{ "file_path": "text-generation-inference/integration-tests/models/__snapshots__/test_flash_llama/test_flash_llama.json", "repo_id": "text-generation-inference", "token_count": 1050 }
219
{ "details": { "best_of_sequences": null, "finish_reason": "length", "generated_tokens": 10, "prefill": [ { "id": 1, "logprob": null, "text": "<s>" }, { "id": 4321, "logprob": -9.0859375, "text": "Test" }, { "id": 2009, "logprob": -16.359375, "text": "request" } ], "seed": 0, "tokens": [ { "id": 5229, "logprob": -0.6645508, "special": false, "text": " failed" }, { "id": 29901, "logprob": 0.0, "special": false, "text": ":" }, { "id": 6527, "logprob": -2.2324219, "special": false, "text": " Could" }, { "id": 451, "logprob": 0.0, "special": false, "text": " not" }, { "id": 6088, "logprob": -1.6074219, "special": false, "text": " parse" }, { "id": 1243, "logprob": -1.6298828, "special": false, "text": " test" }, { "id": 1206, "logprob": -0.72558594, "special": false, "text": " case" }, { "id": 1024, "logprob": -0.40429688, "special": false, "text": " name" }, { "id": 515, "logprob": 0.0, "special": false, "text": " from" }, { "id": 525, "logprob": -1.2519531, "special": false, "text": " '" } ], "top_tokens": null }, "generated_text": "Test request failed: Could not parse test case name from '" }
text-generation-inference/integration-tests/models/__snapshots__/test_flash_llama_marlin_24/test_flash_llama_marlin24_all_params.json/0
{ "file_path": "text-generation-inference/integration-tests/models/__snapshots__/test_flash_llama_marlin_24/test_flash_llama_marlin24_all_params.json", "repo_id": "text-generation-inference", "token_count": 1040 }
220
{ "choices": [ { "finish_reason": "eos_token", "index": 0, "logprobs": null, "message": { "content": "{\n \"temperature\": [\n 35,\n 34,\n 36\n ],\n \"unit\": \"°c\"\n}", "role": "assistant" } } ], "created": 1718044128, "id": "", "model": "TinyLlama/TinyLlama-1.1B-Chat-v1.0", "object": "text_completion", "system_fingerprint": "2.0.5-dev0-native", "usage": { "completion_tokens": 39, "prompt_tokens": 136, "total_tokens": 175 } }
text-generation-inference/integration-tests/models/__snapshots__/test_grammar_response_format_llama/test_grammar_response_format_llama_json.json/0
{ "file_path": "text-generation-inference/integration-tests/models/__snapshots__/test_grammar_response_format_llama/test_grammar_response_format_llama_json.json", "repo_id": "text-generation-inference", "token_count": 283 }
221
{ "details": { "best_of_sequences": null, "finish_reason": "length", "generated_tokens": 10, "prefill": [ { "id": 2502, "logprob": null, "text": " red" }, { "id": 13, "logprob": -2.734375, "text": "," }, { "id": 8862, "logprob": -3.6875, "text": " yellow" }, { "id": 13, "logprob": -0.40234375, "text": "," }, { "id": 209, "logprob": -8.25, "text": " " } ], "seed": 0, "tokens": [ { "id": 187, "logprob": 0.0, "special": false, "text": "\n" }, { "id": 395, "logprob": -0.3125, "special": false, "text": "and" }, { "id": 4797, "logprob": 0.0, "special": false, "text": " blue" }, { "id": 9830, "logprob": -2.25, "special": false, "text": " colors" }, { "id": 15, "logprob": 0.0, "special": false, "text": "." }, { "id": 329, "logprob": -2.171875, "special": false, "text": " A" }, { "id": 1180, "logprob": -2.046875, "special": false, "text": " number" }, { "id": 273, "logprob": 0.0, "special": false, "text": " of" }, { "id": 1027, "logprob": -1.5546875, "special": false, "text": " different" }, { "id": 3295, "logprob": -0.97265625, "special": false, "text": " color" } ], "top_tokens": null }, "generated_text": "blue, red, yellow, \nand blue colors. A number of different color" }
text-generation-inference/integration-tests/models/__snapshots__/test_mamba/test_mamba_all_params.json/0
{ "file_path": "text-generation-inference/integration-tests/models/__snapshots__/test_mamba/test_mamba_all_params.json", "repo_id": "text-generation-inference", "token_count": 1157 }
222
{ "choices": [ { "finish_reason": "eos_token", "index": 0, "logprobs": null, "message": { "content": null, "name": null, "role": "assistant", "tool_calls": [ { "function": { "arguments": { "format": "celsius", "location": "Brooklyn" }, "description": null, "name": "get_current_weather" }, "id": 0, "type": "function" } ] }, "usage": null } ], "created": 1712782670, "id": "", "model": "TinyLlama/TinyLlama-1.1B-Chat-v1.0", "object": "text_completion", "system_fingerprint": "2.0.1-native", "usage": { "completion_tokens": 37, "prompt_tokens": 524, "total_tokens": 561 } }
text-generation-inference/integration-tests/models/__snapshots__/test_tools_llama/test_flash_llama_grammar_tools.json/0
{ "file_path": "text-generation-inference/integration-tests/models/__snapshots__/test_tools_llama/test_flash_llama_grammar_tools.json", "repo_id": "text-generation-inference", "token_count": 495 }
223
import pytest @pytest.fixture(scope="module") def flash_gpt2_handle(launcher): with launcher("openai-community/gpt2", num_shard=2) as handle: yield handle @pytest.fixture(scope="module") async def flash_gpt2(flash_gpt2_handle): await flash_gpt2_handle.health(300) return flash_gpt2_handle.client @pytest.mark.release @pytest.mark.asyncio async def test_flash_gpt2(flash_gpt2, response_snapshot): response = await flash_gpt2.generate( "What is deep learning?", max_new_tokens=10, decoder_input_details=True, ) assert response.details.generated_tokens == 10 assert response == response_snapshot @pytest.mark.release @pytest.mark.asyncio async def test_flash_gpt2_load(flash_gpt2, generate_load, response_snapshot): responses = await generate_load( flash_gpt2, "What is deep learning?", max_new_tokens=10, n=4, ) generated_texts = [r.generated_text for r in responses] assert len(generated_texts) == 4 assert all( [text == generated_texts[0] for text in generated_texts] ), generated_texts assert responses == response_snapshot
text-generation-inference/integration-tests/models/test_flash_gpt2.py/0
{ "file_path": "text-generation-inference/integration-tests/models/test_flash_gpt2.py", "repo_id": "text-generation-inference", "token_count": 476 }
224
import pytest @pytest.fixture(scope="module") def flash_starcoder_handle(launcher): with launcher("bigcode/starcoder", num_shard=2) as handle: yield handle @pytest.fixture(scope="module") async def flash_starcoder(flash_starcoder_handle): await flash_starcoder_handle.health(300) return flash_starcoder_handle.client @pytest.mark.release @pytest.mark.asyncio @pytest.mark.private async def test_flash_starcoder(flash_starcoder, response_snapshot): response = await flash_starcoder.generate( "def print_hello", max_new_tokens=10, decoder_input_details=True ) assert response.details.generated_tokens == 10 assert response == response_snapshot @pytest.mark.release @pytest.mark.asyncio @pytest.mark.private async def test_flash_starcoder_default_params(flash_starcoder, response_snapshot): response = await flash_starcoder.generate( "def print_hello", max_new_tokens=60, temperature=0.2, top_p=0.95, decoder_input_details=True, seed=0, ) assert response.details.generated_tokens == 60 assert response == response_snapshot @pytest.mark.release @pytest.mark.asyncio @pytest.mark.private async def test_flash_starcoder_load(flash_starcoder, generate_load, response_snapshot): responses = await generate_load( flash_starcoder, "def print_hello", max_new_tokens=10, n=4 ) assert len(responses) == 4 assert all([r.generated_text == responses[0].generated_text for r in responses]) assert responses == response_snapshot
text-generation-inference/integration-tests/models/test_flash_starcoder.py/0
{ "file_path": "text-generation-inference/integration-tests/models/test_flash_starcoder.py", "repo_id": "text-generation-inference", "token_count": 602 }
225
import pytest @pytest.fixture(scope="module") def flash_llama_grammar_tools_handle(launcher): with launcher( "TinyLlama/TinyLlama-1.1B-Chat-v1.0", num_shard=2, disable_grammar_support=False ) as handle: yield handle @pytest.fixture(scope="module") async def flash_llama_grammar_tools(flash_llama_grammar_tools_handle): await flash_llama_grammar_tools_handle.health(300) return flash_llama_grammar_tools_handle.client # tools to be used in the following tests tools = [ { "type": "function", "function": { "name": "get_current_weather", "description": "Get the current weather", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA", }, "format": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "The temperature unit to use. Infer this from the users location.", }, }, "required": ["location", "format"], "additionalProperties": False, }, }, }, { "type": "function", "function": { "name": "get_n_day_weather_forecast", "description": "Get an N-day weather forecast", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA", }, "format": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "The temperature unit to use. Infer this from the users location.", }, "num_days": { "type": "integer", "description": "The number of days to forecast", }, }, "required": ["location", "format", "num_days"], "additionalProperties": False, }, }, }, ] @pytest.mark.asyncio @pytest.mark.private async def test_flash_llama_grammar_tools(flash_llama_grammar_tools, response_snapshot): response = await flash_llama_grammar_tools.chat( max_tokens=100, seed=1, tools=tools, temperature=0.0, messages=[ { "role": "system", "content": "Youre a helpful assistant! Answer the users question best you can.", }, { "role": "user", "content": "What is the weather like in Brooklyn, New York?", }, ], ) assert response.choices[0].message.content is None assert response.choices[0].message.tool_calls == [ { "id": "0", "type": "function", "function": { "description": None, "name": "get_current_weather", "arguments": {"format": "celsius", "location": "Brooklyn, NY"}, }, } ] assert response == response_snapshot @pytest.mark.asyncio @pytest.mark.private async def test_flash_llama_grammar_tools_auto( flash_llama_grammar_tools, response_snapshot ): response = await flash_llama_grammar_tools.chat( max_tokens=100, seed=1, tools=tools, temperature=0.0, tool_choice="auto", messages=[ { "role": "system", "content": "Youre a helpful assistant! Answer the users question best you can.", }, { "role": "user", "content": "What is the weather like in Brooklyn, New York?", }, ], ) assert response.choices[0].message.content is None assert response.choices[0].message.tool_calls == [ { "id": "0", "type": "function", "function": { "description": None, "name": "get_current_weather", "arguments": {"format": "celsius", "location": "Brooklyn, NY"}, }, } ] assert response == response_snapshot @pytest.mark.asyncio @pytest.mark.private async def test_flash_llama_grammar_tools_choice( flash_llama_grammar_tools, response_snapshot ): response = await flash_llama_grammar_tools.chat( max_tokens=100, seed=1, tools=tools, temperature=0.0, tool_choice="get_current_weather", messages=[ { "role": "system", "content": "Youre a helpful assistant! Answer the users question best you can.", }, { "role": "user", "content": "What is the weather like in Brooklyn, New York?", }, ], ) assert response.choices[0].message.content is None assert response.choices[0].message.tool_calls == [ { "id": "0", "type": "function", "function": { "description": None, "name": "get_current_weather", "arguments": {"format": "celsius", "location": "Brooklyn, NY"}, }, } ] assert response == response_snapshot @pytest.mark.asyncio @pytest.mark.private async def test_flash_llama_grammar_tools_stream( flash_llama_grammar_tools, response_snapshot ): responses = await flash_llama_grammar_tools.chat( max_tokens=100, seed=1, tools=tools, temperature=0.0, tool_choice="get_current_weather", messages=[ { "role": "system", "content": "Youre a helpful assistant! Answer the users question best you can.", }, { "role": "user", "content": "What is the weather like in Paris, France?", }, ], stream=True, ) count = 0 async for response in responses: count += 1 assert count == 48 assert response == response_snapshot @pytest.mark.asyncio @pytest.mark.private async def test_flash_llama_grammar_tools_insufficient_information( flash_llama_grammar_tools, response_snapshot ): responses = await flash_llama_grammar_tools.chat( max_tokens=100, seed=24, tools=tools, tool_choice="auto", messages=[ { "role": "system", "content": "STRICTLY ONLY RESPOND IF THE USER ASKS A WEATHER RELATED QUESTION", }, { "role": "user", "content": "Tell me a story about 3 sea creatures", }, ], stream=False, ) assert responses.choices[0].message.content is None assert ( responses.choices[0].message.tool_calls[0]["function"]["name"] == "notify_error" ) assert responses == response_snapshot
text-generation-inference/integration-tests/models/test_tools_llama.py/0
{ "file_path": "text-generation-inference/integration-tests/models/test_tools_llama.py", "repo_id": "text-generation-inference", "token_count": 3753 }
226
use crate::config::Config; use clap::ValueEnum; use csv::ReaderBuilder; use reqwest::header::HeaderMap; use serde::Serialize; use std::{ fs::File, io::{self, BufRead}, path::Path, process::Command, time::Duration, }; use uuid::Uuid; const TELEMETRY_URL: &str = "https://huggingface.co/api/telemetry/tgi"; #[derive(Copy, Clone, Debug, Serialize, ValueEnum)] pub enum UsageStatsLevel { On, NoStack, Off, } #[derive(Debug, Clone, Serialize)] pub struct UserAgent { pub uid: String, pub args: Args, pub env: Env, } impl UserAgent { pub fn new(reduced_args: Args) -> Self { Self { uid: Uuid::new_v4().to_string(), args: reduced_args, env: Env::new(), } } } #[derive(Serialize, Debug)] pub enum EventType { Start, Stop, Error, } #[derive(Debug, Serialize)] pub struct UsageStatsEvent { user_agent: UserAgent, event_type: EventType, #[serde(skip_serializing_if = "Option::is_none")] error_reason: Option<String>, } impl UsageStatsEvent { pub fn new(user_agent: UserAgent, event_type: EventType, error_reason: Option<String>) -> Self { Self { user_agent, event_type, error_reason, } } pub async fn send(&self) { let mut headers = HeaderMap::new(); headers.insert("Content-Type", "application/json".parse().unwrap()); let body = serde_json::to_string(&self).unwrap(); let client = reqwest::Client::new(); let _ = client .post(TELEMETRY_URL) .headers(headers) .body(body) .timeout(Duration::from_secs(5)) .send() .await; } } #[derive(Debug, Clone, Serialize)] pub struct Args { model_config: Option<Config>, tokenizer_class: Option<String>, max_concurrent_requests: usize, max_best_of: usize, max_stop_sequences: usize, max_top_n_tokens: u32, max_input_tokens: usize, max_total_tokens: usize, // waiting_served_ratio: f32, // max_batch_prefill_tokens: u32, // max_batch_total_tokens: Option<u32>, // max_waiting_tokens: usize, // max_batch_size: Option<usize>, revision: Option<String>, validation_workers: usize, messages_api_enabled: bool, disable_grammar_support: bool, max_client_batch_size: usize, usage_stats_level: UsageStatsLevel, } impl Args { #[allow(clippy::too_many_arguments)] pub fn new( model_config: Option<Config>, tokenizer_class: Option<String>, max_concurrent_requests: usize, max_best_of: usize, max_stop_sequences: usize, max_top_n_tokens: u32, max_input_tokens: usize, max_total_tokens: usize, // waiting_served_ratio: f32, // max_batch_prefill_tokens: u32, // max_batch_total_tokens: Option<u32>, // max_waiting_tokens: usize, // max_batch_size: Option<usize>, revision: Option<String>, validation_workers: usize, messages_api_enabled: bool, disable_grammar_support: bool, max_client_batch_size: usize, usage_stats_level: UsageStatsLevel, ) -> Self { Self { model_config, tokenizer_class, max_concurrent_requests, max_best_of, max_stop_sequences, max_top_n_tokens, max_input_tokens, max_total_tokens, // waiting_served_ratio, // max_batch_prefill_tokens, // max_batch_total_tokens, // max_waiting_tokens, // max_batch_size, revision, validation_workers, messages_api_enabled, disable_grammar_support, max_client_batch_size, usage_stats_level, } } } /// This is more or less a copy of the code from the `text-generation-launcher` crate to avoid a dependency #[derive(Serialize, Debug, Clone)] pub struct Env { git_sha: &'static str, docker_label: &'static str, nvidia_info: Option<Vec<NvidiaSmiInfo>>, xpu_info: Option<Vec<XpuSmiInfo>>, system_env: SystemInfo, } #[derive(Debug, Serialize, Clone)] struct NvidiaSmiInfo { name: String, pci_bus_id: String, driver_version: String, pstate: String, pcie_link_gen_max: String, pcie_link_gen_current: String, temperature_gpu: String, utilization_gpu: String, utilization_memory: String, memory_total: String, memory_free: String, memory_used: String, reset_status_reset_required: String, reset_status_drain_and_reset_recommended: String, compute_cap: String, ecc_errors_corrected_volatile_total: String, mig_mode_current: String, power_draw_instant: String, power_limit: String, } impl NvidiaSmiInfo { fn new() -> Option<Vec<NvidiaSmiInfo>> { let output = Command::new("nvidia-smi") .args([ "--query-gpu=name,pci.bus_id,driver_version,pstate,pcie.link.gen.max,pcie.link.gen.gpucurrent,temperature.gpu,utilization.gpu,utilization.memory,memory.total,memory.free,memory.used,reset_status.reset_required,reset_status.drain_and_reset_recommended,compute_cap,ecc.errors.corrected.volatile.total,mig.mode.current,power.draw.instant,power.limit", "--format=csv" ]) .output() .ok()?; if !output.status.success() { return None; } let stdout = String::from_utf8(output.stdout).ok()?; let mut rdr = ReaderBuilder::new() .has_headers(true) .from_reader(stdout.as_bytes()); let mut infos = Vec::new(); for result in rdr.records() { let record = result.ok()?; infos.push(NvidiaSmiInfo { name: record[0].to_string(), pci_bus_id: record[1].to_string(), driver_version: record[2].to_string(), pstate: record[3].to_string(), pcie_link_gen_max: record[4].to_string(), pcie_link_gen_current: record[5].to_string(), temperature_gpu: record[6].to_string(), utilization_gpu: record[7].to_string(), utilization_memory: record[8].to_string(), memory_total: record[9].to_string(), memory_free: record[10].to_string(), memory_used: record[11].to_string(), reset_status_reset_required: record[12].to_string(), reset_status_drain_and_reset_recommended: record[13].to_string(), compute_cap: record[14].to_string(), ecc_errors_corrected_volatile_total: record[15].to_string(), mig_mode_current: record[16].to_string(), power_draw_instant: record[17].to_string(), power_limit: record[18].to_string(), }); } Some(infos) } } #[derive(Debug, Serialize, Clone)] struct XpuSmiInfo { device_id: usize, gpu_utilization: f32, gpu_power: f32, gpu_core_temperature: f32, gpu_memory_bandwidth_utilization: f32, } impl XpuSmiInfo { /// based on this https://github.com/intel/xpumanager/blob/master/doc/smi_user_guide.md#dump-the-device-statistics-in-csv-format fn new() -> Option<Vec<XpuSmiInfo>> { let output = Command::new("xpu-smi") .args([ "dump", "-d", "-1", "-m", "0,1,3,17", // Metrics IDs: GPU Utilization, GPU Power, GPU Core Temperature, GPU Memory Bandwidth Utilization "-n", "1", "-j", ]) .output() .ok()?; if !output.status.success() { return None; } let stdout = String::from_utf8(output.stdout).ok()?; let mut infos = Vec::new(); let json_data: serde_json::Value = match serde_json::from_str(&stdout) { Ok(data) => data, Err(_) => return None, }; if let Some(metrics_data) = json_data.as_array() { for entry in metrics_data { let device_id = entry["deviceId"].as_u64()? as usize; let gpu_utilization = entry["metrics"][0].as_f64()? as f32; let gpu_power = entry["metrics"][1].as_f64()? as f32; let gpu_core_temperature = entry["metrics"][2].as_f64()? as f32; let gpu_memory_bandwidth_utilization = entry["metrics"][3].as_f64()? as f32; infos.push(XpuSmiInfo { device_id, gpu_utilization, gpu_power, gpu_core_temperature, gpu_memory_bandwidth_utilization, }); } } Some(infos) } } #[derive(Serialize, Debug, Clone)] pub struct SystemInfo { cpu_count: usize, cpu_type: String, total_memory: u64, architecture: String, platform: String, } impl SystemInfo { fn new() -> Self { let mut system = sysinfo::System::new_all(); system.refresh_all(); let cpu_count = system.cpus().len(); let cpu_type = system.cpus()[0].brand().to_string(); let total_memory = system.total_memory(); let architecture = std::env::consts::ARCH.to_string(); let platform = format!( "{}-{}-{}", std::env::consts::OS, std::env::consts::FAMILY, std::env::consts::ARCH ); Self { cpu_count, cpu_type, total_memory, architecture, platform, } } } impl Default for Env { fn default() -> Self { Self::new() } } impl Env { pub fn new() -> Self { Self { system_env: SystemInfo::new(), nvidia_info: NvidiaSmiInfo::new(), xpu_info: XpuSmiInfo::new(), git_sha: option_env!("VERGEN_GIT_SHA").unwrap_or("N/A"), docker_label: option_env!("DOCKER_LABEL").unwrap_or("N/A"), } } } pub fn is_container() -> io::Result<bool> { let path = Path::new("/proc/self/cgroup"); let file = File::open(path)?; let reader = io::BufReader::new(file); for line in reader.lines() { let line = line?; // Check for common container runtimes if line.contains("/docker/") || line.contains("/docker-") || line.contains("/kubepods/") || line.contains("/kubepods-") || line.contains("containerd") || line.contains("crio") || line.contains("podman") { return Ok(true); } } Ok(false) }
text-generation-inference/router/src/usage_stats.rs/0
{ "file_path": "text-generation-inference/router/src/usage_stats.rs", "repo_id": "text-generation-inference", "token_count": 5309 }
227
# Text Generation Inference Python gRPC Server A Python gRPC server for Text Generation Inference ## Install ```shell make install ``` ## Run ```shell make run-dev ```
text-generation-inference/server/README.md/0
{ "file_path": "text-generation-inference/server/README.md", "repo_id": "text-generation-inference", "token_count": 56 }
228
// Adapted from turboderp exllama: https://github.com/turboderp/exllama #ifndef _tuning_h #define _tuning_h struct ExLlamaTuning { int matmul_recons_thd; bool matmul_fused_remap; bool matmul_no_half2; }; #endif
text-generation-inference/server/exllama_kernels/exllama_kernels/tuning.h/0
{ "file_path": "text-generation-inference/server/exllama_kernels/exllama_kernels/tuning.h", "repo_id": "text-generation-inference", "token_count": 106 }
229
#ifndef _qdq_5_cuh #define _qdq_5_cuh #include "qdq_util.cuh" #include "../../config.h" #if QMODE_5BIT == 1 // Permutation: // // v5555533 33311111 u4444422 22200000 (u, v lsb) // vbbbbb99 99977777 uaaaaa88 88866666 // vhhhhhff fffddddd ugggggee eeeccccc // vnnnnnll llljjjjj ummmmmkk kkkiiiii // vtttttrr rrrppppp usssssqq qqqooooo __forceinline__ __device__ void shuffle_5bit_32 ( uint32_t* q, int stride ) { uint32_t qa = q[0 * stride]; uint32_t qb = q[1 * stride]; uint32_t qc = q[2 * stride]; uint32_t qd = q[3 * stride]; uint32_t qe = q[4 * stride]; // qa: 66555554 44443333 32222211 11100000 // qb: ccccbbbb baaaaa99 99988888 77777666 // qc: jiiiiihh hhhggggg fffffeee eedddddc // qd: pppooooo nnnnnmmm mmlllllk kkkkjjjj // qe: vvvvvuuu uuttttts ssssrrrr rqqqqqpp uint32_t qf = qe >> 22; qe <<= 8; qe |= qd >> 24; qd <<= 6; qd |= qc >> 26; qc <<= 4; qc |= qb >> 28; qb <<= 2; qb |= qa >> 30; // qa: 555554 44443333 32222211 11100000 // qb: bbbbba aaaa9999 98888877 77766666 // qc: hhhhhg ggggffff feeeeedd dddccccc // qd: nnnnnm mmmmllll lkkkkkjj jjjiiiii // qe: ttttts ssssrrrr rqqqqqpp pppooooo // qf: vv vvvuuuuu uint32_t za = 0; uint32_t zb = 0; uint32_t zc = 0; uint32_t zd = 0; uint32_t ze = 0; for (int i = 0; i < 3; i++) { uint32_t t0 = qa & 0x1f; uint32_t t1 = (qa & 0x3e0) >> 5; qa >>= 10; za |= (t0 << (i * 5)); za |= (t1 << (i * 5 + 16)); } for (int i = 0; i < 3; i++) { uint32_t t0 = qb & 0x1f; uint32_t t1 = (qb & 0x3e0) >> 5; qb >>= 10; zb |= (t0 << (i * 5)); zb |= (t1 << (i * 5 + 16)); } for (int i = 0; i < 3; i++) { uint32_t t0 = qc & 0x1f; uint32_t t1 = (qc & 0x3e0) >> 5; qc >>= 10; zc |= (t0 << (i * 5)); zc |= (t1 << (i * 5 + 16)); } for (int i = 0; i < 3; i++) { uint32_t t0 = qd & 0x1f; uint32_t t1 = (qd & 0x3e0) >> 5; qd >>= 10; zd |= (t0 << (i * 5)); zd |= (t1 << (i * 5 + 16)); } for (int i = 0; i < 3; i++) { uint32_t t0 = qe & 0x1f; uint32_t t1 = (qe & 0x3e0) >> 5; qe >>= 10; ze |= (t0 << (i * 5)); ze |= (t1 << (i * 5 + 16)); } // za: 5555533 33311111 4444422 22200000 // zb: bbbbb99 99977777 aaaaa88 88866666 // zc: hhhhhff fffddddd gggggee eeeccccc // zd: nnnnnll llljjjjj mmmmmkk kkkiiiii // ze: tttttrr rrrppppp sssssqq qqqooooo // qf: vv vvvuuuuu za |= ((qf & 0x001) >> 0) << 15; zb |= ((qf & 0x002) >> 1) << 15; zc |= ((qf & 0x004) >> 2) << 15; zd |= ((qf & 0x008) >> 3) << 15; ze |= ((qf & 0x010) >> 4) << 15; za |= ((qf & 0x020) >> 5) << 31; zb |= ((qf & 0x040) >> 6) << 31; zc |= ((qf & 0x080) >> 7) << 31; zd |= ((qf & 0x100) >> 8) << 31; ze |= ((qf & 0x200) >> 9) << 31; // za: v5555533 33311111 u4444422 22200000 (u, v lsb) // zb: vbbbbb99 99977777 uaaaaa88 88866666 // zc: vhhhhhff fffddddd ugggggee eeeccccc // zd: vnnnnnll llljjjjj ummmmmkk kkkiiiii // ze: vtttttrr rrrppppp usssssqq qqqooooo q[0 * stride] = za; q[1 * stride] = zb; q[2 * stride] = zc; q[3 * stride] = zd; q[4 * stride] = ze; } __forceinline__ __device__ void dequant_5bit_32 ( const uint32_t q_0, const uint32_t q_1, const uint32_t q_2, const uint32_t q_3, const uint32_t q_4, half2 (&dq)[16], int stride ) { const uint32_t c0 = 0x64006400; const half y32_ = __float2half_rn(1.0f / 32.0f); const half2 y32 = __halves2half2(y32_, y32_); const half z1_ = __float2half_rn(-1024.0f - 16.0f); const half z32_ = __float2half_rn(-1024.0f / 32.0f - 16.0f); const half2 z1 = __halves2half2(z1_, z1_); const half2 z32 = __halves2half2(z32_, z32_); uint32_t qa = q_0; uint32_t qb = q_1; uint32_t qc = q_2; uint32_t qd = q_3; uint32_t qe = q_4; half2_uint32 q0 ((qa & 0x001f001f) | c0); // half2(q[ 0], q[ 1]) + 1024 half2_uint32 q1 ((qa & 0x03e003e0) | c0); // half2(q[ 2], q[ 3]) * 32 + 1024 qa >>= 10; half2_uint32 q2 ((qa & 0x001f001f) | c0); // half2(q[ 4], q[ 5]) + 1024 qa >>= 5; qa &= 0x00010001; half2_uint32 q3 ((qb & 0x001f001f) | c0); // half2(q[ 6], q[ 7]) + 1024 half2_uint32 q4 ((qb & 0x03e003e0) | c0); // half2(q[ 8], q[ 9]) * 32 + 1024 qb >>= 10; half2_uint32 q5 ((qb & 0x001f001f) | c0); // half2(q[10], q[11]) + 1024 qb >>= 4; qb &= 0x00020002; half2_uint32 q6 ((qc & 0x001f001f) | c0); // half2(q[12], q[13]) + 1024 half2_uint32 q7 ((qc & 0x03e003e0) | c0); // half2(q[14], q[15]) * 32 + 1024 qc >>= 10; half2_uint32 q8 ((qc & 0x001f001f) | c0); // half2(q[16], q[17]) + 1024 qc >>= 3; qc &= 0x00040004; half2_uint32 q9 ((qd & 0x001f001f) | c0); // half2(q[18], q[19]) + 1024 half2_uint32 q10((qd & 0x03e003e0) | c0); // half2(q[20], q[21]) * 32 + 1024 qd >>= 10; half2_uint32 q11((qd & 0x001f001f) | c0); // half2(q[22], q[23]) + 1024 qd >>= 2; qd &= 0x00080008; half2_uint32 q12((qe & 0x001f001f) | c0); // half2(q[24], q[25]) + 1024 half2_uint32 q13((qe & 0x03e003e0) | c0); // half2(q[26], q[27]) * 32 + 1024 qe >>= 10; half2_uint32 q14((qe & 0x001f001f) | c0); // half2(q[28], q[29]) + 1024 qe >>= 1; qe &= 0x00100010; half2_uint32 q15((qa | qb | qc | qd | qe) | c0); dq[ 0] = __hadd2( q0.as_half2, z1); dq[ 1] = __hfma2( q1.as_half2, y32, z32); dq[ 2] = __hadd2( q2.as_half2, z1); dq[ 3] = __hadd2( q3.as_half2, z1); dq[ 4] = __hfma2( q4.as_half2, y32, z32); dq[ 5] = __hadd2( q5.as_half2, z1); dq[ 6] = __hadd2( q6.as_half2, z1); dq[ 7] = __hfma2( q7.as_half2, y32, z32); dq[ 8] = __hadd2( q8.as_half2, z1); dq[ 9] = __hadd2( q9.as_half2, z1); dq[10] = __hfma2(q10.as_half2, y32, z32); dq[11] = __hadd2(q11.as_half2, z1); dq[12] = __hadd2(q12.as_half2, z1); dq[13] = __hfma2(q13.as_half2, y32, z32); dq[14] = __hadd2(q14.as_half2, z1); dq[15] = __hadd2(q15.as_half2, z1); } #else __forceinline__ __device__ void shuffle_5bit_32 ( uint32_t* q, int stride ) { } __forceinline__ __device__ void dequant_5bit_32 ( const uint32_t q_0, const uint32_t q_1, const uint32_t q_2, const uint32_t q_3, const uint32_t q_4, half2 (&dq)[16], int stride ) { half dqh[32]; for (int i = 0; i < 6; i++) dqh[ i] = dq_ns(exb( q_0, i * 5 , 0x1f), 16); dqh[ 6 ] = dq_ns(exb(q_1, q_0, 30, 0x1f), 16); for (int i = 0; i < 5; i++) dqh[ 7 + i] = dq_ns(exb( q_1, i * 5 + 3, 0x1f), 16); dqh[12 ] = dq_ns(exb(q_2, q_1, 28, 0x1f), 16); for (int i = 0; i < 6; i++) dqh[13 + i] = dq_ns(exb( q_2, i * 5 + 1, 0x1f), 16); dqh[19 ] = dq_ns(exb(q_3, q_2, 31, 0x1f), 16); for (int i = 0; i < 5; i++) dqh[20 + i] = dq_ns(exb( q_3, i * 5 + 4, 0x1f), 16); dqh[25 ] = dq_ns(exb(q_4, q_3, 29, 0x1f), 16); for (int i = 0; i < 6; i++) dqh[26 + i] = dq_ns(exb( q_4, i * 5 + 2, 0x1f), 16); for (int i = 0; i < 16; i++) dq[i] = __halves2half2(dqh[i * 2], dqh[i * 2 + 1]); } #endif #endif
text-generation-inference/server/exllamav2_kernels/exllamav2_kernels/cuda/quant/qdq_5.cuh/0
{ "file_path": "text-generation-inference/server/exllamav2_kernels/exllamav2_kernels/cuda/quant/qdq_5.cuh", "repo_id": "text-generation-inference", "token_count": 4272 }
230
import pytest from text_generation_server.pb import generate_pb2 from text_generation_server.models.causal_lm import CausalLMBatch, CausalLM @pytest.fixture(scope="session") def default_santacoder(): return CausalLM.fallback(model_id="bigcode/santacoder") @pytest.fixture def default_pb_request(default_pb_parameters, default_pb_stop_parameters): return generate_pb2.Request( id=0, inputs="def", input_chunks=generate_pb2.Input(chunks=[generate_pb2.InputChunk(text="def")]), prefill_logprobs=True, truncate=100, parameters=default_pb_parameters, stopping_parameters=default_pb_stop_parameters, ) @pytest.fixture def default_pb_batch(default_pb_request): return generate_pb2.Batch(id=0, requests=[default_pb_request], size=1) @pytest.fixture def default_fim_pb_request(default_pb_parameters, default_pb_stop_parameters): return generate_pb2.Request( id=0, inputs="<fim-prefix>def<fim-suffix>world<fim-middle>", input_chunks=generate_pb2.Input( chunks=[ generate_pb2.InputChunk( text="<fim-prefix>def<fim-suffix>world<fim-middle>" ) ] ), prefill_logprobs=True, truncate=100, parameters=default_pb_parameters, stopping_parameters=default_pb_stop_parameters, ) @pytest.fixture def default_fim_pb_batch(default_fim_pb_request): return generate_pb2.Batch(id=0, requests=[default_fim_pb_request], size=1) @pytest.mark.skip def test_santacoder_generate_token_completion(default_santacoder, default_pb_batch): batch = CausalLMBatch.from_pb( default_pb_batch, default_santacoder.tokenizer, default_santacoder.dtype, default_santacoder.device, ) next_batch = batch for _ in range(batch.stopping_criterias[0].max_new_tokens - 1): generations, next_batch, _ = default_santacoder.generate_token(next_batch) assert len(generations) == len(next_batch) generations, next_batch, _ = default_santacoder.generate_token(next_batch) assert next_batch is None assert len(generations) == 1 assert generations[0].generated_text.text == " test_get_all_users_with_" assert generations[0].request_id == batch.requests[0].id assert ( generations[0].generated_text.generated_tokens == batch.stopping_criterias[0].max_new_tokens ) @pytest.mark.skip def test_fim_santacoder_generate_token_completion( default_santacoder, default_fim_pb_batch ): batch = CausalLMBatch.from_pb( default_fim_pb_batch, default_santacoder.tokenizer, default_santacoder.dtype, default_santacoder.device, ) next_batch = batch for _ in range(batch.stopping_criterias[0].max_new_tokens - 1): generations, next_batch, _ = default_santacoder.generate_token(next_batch) assert len(generations) == len(next_batch) generations, next_batch, _ = default_santacoder.generate_token(next_batch) assert next_batch is None assert len(generations) == 1 assert ( generations[0].generated_text.text == """ineProperty(exports, "__esModule", { value""" ) assert generations[0].request_id == batch.requests[0].id assert ( generations[0].generated_text.generated_tokens == batch.stopping_criterias[0].max_new_tokens )
text-generation-inference/server/tests/models/test_santacoder.py/0
{ "file_path": "text-generation-inference/server/tests/models/test_santacoder.py", "repo_id": "text-generation-inference", "token_count": 1480 }
231
import torch import grpc from google.rpc import status_pb2, code_pb2 from grpc_status import rpc_status from grpc_interceptor.server import AsyncServerInterceptor from loguru import logger from typing import Callable, Any class ExceptionInterceptor(AsyncServerInterceptor): async def intercept( self, method: Callable, request_or_iterator: Any, context: grpc.ServicerContext, method_name: str, ) -> Any: try: response = method(request_or_iterator, context) return await response except Exception as err: method_name = method_name.split("/")[-1] logger.exception(f"Method {method_name} encountered an error.") # Runtime Error cannot be recovered from if isinstance(err, RuntimeError): exit(1) if torch.cuda.is_available(): torch.cuda.empty_cache() await context.abort_with_status( rpc_status.to_status( status_pb2.Status(code=code_pb2.INTERNAL, message=str(err)) ) )
text-generation-inference/server/text_generation_server/interceptor.py/0
{ "file_path": "text-generation-inference/server/text_generation_server/interceptor.py", "repo_id": "text-generation-inference", "token_count": 509 }
232
import os from dataclasses import dataclass from typing import List, Optional, Union import torch from loguru import logger from text_generation_server.utils.import_utils import SYSTEM from text_generation_server.utils.log import log_once from text_generation_server.utils.weights import Weight, Weights, WeightsLoader @dataclass class GPTQWeight(Weight): qweight: torch.Tensor qzeros: torch.Tensor scales: torch.Tensor g_idx: Optional[torch.Tensor] bits: int groupsize: int use_awq_kernel: bool use_exllama: bool def __post_init__(self): if self.scales.dtype == torch.float: self.scales = self.scales.half() @property def device(self) -> torch.device: return self.qweight.device def get_linear(self, bias: torch.Tensor): if self.use_awq_kernel: if SYSTEM == "rocm": raise NotImplementedError( "AWQ GEMM kernel can't be used on ROCm systems, please use `--quantize gptq` instead " "to use Exllama/GPTQ kernels for AWQ inference." ) try: from text_generation_server.layers.awq.quantize.qmodule import WQLinear return WQLinear( w_bit=self.bits, group_size=self.groupsize, qweight=self.qweight, qzeros=self.qzeros, scales=self.scales, bias=bias, ) except ImportError: raise NotImplementedError( "You do not seem to have awq installed, either install it (cd server && make install-awq), or try using GPTQ `---quantize gptq` a conversion AWQ->GPTQ will happen on the fly" ) elif self.use_exllama: try: from text_generation_server.layers.gptq import ExllamaQuantLinear except ImportError: raise NotImplementedError( "Exllama gptq kernels are not installed. Install them `cd server/exllama_kernels && python setup.py install && cd ../exllamav2_kernels && python setup.py install`" ) return ExllamaQuantLinear(self, bias) else: from text_generation_server.layers.gptq.quant_linear import QuantLinear return QuantLinear( self.qweight, self.qzeros, self.scales, self.g_idx, bias, self.bits, self.groupsize, ) class GPTQWeightsLoader(WeightsLoader): """ Loader for GPTQ- and AWQ-quantized weights. """ def __init__( self, *, bits: int, desc_act: bool, groupsize: int, quant_method: str, quantize: str, sym: bool, ): self.bits = bits self.desc_act = desc_act self.groupsize = groupsize self.quant_method = quant_method self.quantize = quantize self.sym = sym def get_weights(self, weights: Weights, prefix: str): self._get_gptq_params(weights) use_exllama = True if self.bits != 4: use_exllama = False if self.desc_act: log_once(logger.warning, "Disabling exllama because desc_act=True") use_exllama = False try: qweight = weights.get_tensor(f"{prefix}.qweight") except RuntimeError: raise RuntimeError( "Cannot load `gptq` weight, make sure the model is already quantized, or quantize it with `text-generation-server quantize ORIGINAL_MODEL_ID NEW_MODEL_ID`" ) if self.quantize == "gptq" and self.quant_method == "gptq": g_idx = weights.get_tensor(f"{prefix}.g_idx") else: g_idx = None from text_generation_server.layers.gptq import ( HAS_EXLLAMA, CAN_EXLLAMA, GPTQWeight, ) if use_exllama: if not HAS_EXLLAMA: if CAN_EXLLAMA: log_once( logger.warning, "Exllama GPTQ cuda kernels (which are faster) could have been used, but are not currently installed, try using BUILD_EXTENSIONS=True", ) use_exllama = False else: log_once(logger.info, f"Using exllama kernels v{HAS_EXLLAMA}") qzeros = weights.get_tensor(f"{prefix}.qzeros") scales = weights.get_tensor(f"{prefix}.scales") if use_exllama and g_idx is not None: g_idx = g_idx - g_idx[0] if self.quantize == "gptq" and self.quant_method == "awq": log_once( logger.info, "Converting AWQ model to Exllama/GPTQ packing format." ) from text_generation_server.layers.awq.conversion_utils import ( fast_awq_to_gptq, ) qweight, qzeros = fast_awq_to_gptq(qweight, qzeros) if use_exllama: g_idx = None else: g_idx = ( torch.arange( qweight.shape[0] * (32 // self.bits), device=qweight.device, ) // self.groupsize ).to(dtype=torch.int32) return GPTQWeight( qweight=qweight, qzeros=qzeros, scales=scales, g_idx=g_idx, bits=self.bits, groupsize=self.groupsize, use_exllama=use_exllama, ) def get_weights_col_packed( self, weights: Weights, prefix: str, block_sizes: Union[int, List[int]], ): try: qweight = weights.get_packed_sharded( f"{prefix}.qweight", dim=1, block_sizes=block_sizes ) except RuntimeError: raise RuntimeError( f"Cannot load `{self.quantize}` weight, make sure the model is already quantized." ) scales = weights.get_packed_sharded( f"{prefix}.scales", dim=1, block_sizes=block_sizes ) scales = scales.to(dtype=weights.dtype) self._get_gptq_params(weights) qzeros = weights.get_packed_sharded( f"{prefix}.qzeros", dim=1, block_sizes=block_sizes ) if self.quantize == "gptq" and self.quant_method == "gptq": g_idx = weights.get_tensor(f"{prefix}.g_idx") elif self.quantize == "gptq" and self.quant_method == "awq": log_once( logger.info, "Converting AWQ model to Exllama/GPTQ packing format." ) from text_generation_server.layers.awq.conversion_utils import ( fast_awq_to_gptq, ) qweight, qzeros = fast_awq_to_gptq(qweight, qzeros) g_idx = ( torch.arange( qweight.shape[0] * (32 // self.bits), device=qweight.device, ) // self.groupsize ).to(dtype=torch.int32) else: g_idx = None return GPTQWeight( qweight=qweight, qzeros=qzeros, scales=scales, g_idx=g_idx, bits=self.bits, groupsize=self.groupsize, use_awq_kernel=self.quantize == "awq", use_exllama=False, ) def get_multi_weights_col(self, weights: Weights, prefixes: List[str], dim: int): try: qweight = torch.cat( [weights.get_sharded(f"{p}.qweight", dim=1) for p in prefixes], dim=1 ) except RuntimeError: raise RuntimeError( f"Cannot load `{self.quantize}` weight, make sure the model is already quantized" ) scales = torch.cat( [weights.get_sharded(f"{p}.scales", dim=1) for p in prefixes], dim=1 ) self._get_gptq_params(weights) qzeros = torch.cat( [weights.get_sharded(f"{p}.qzeros", dim=1) for p in prefixes], dim=1 ) from text_generation_server.layers.gptq import HAS_EXLLAMA use_exllama = ( self.bits == 4 and HAS_EXLLAMA and self.quantize == "gptq" and not self.desc_act ) if self.quantize == "gptq" and self.quant_method == "gptq": w = [weights.get_tensor(f"{p}.g_idx") for p in prefixes] for w2 in w[1:]: torch.testing.assert_close(w2, w[0]) g_idx = w[0] elif self.quantize == "gptq" and self.quant_method == "awq": log_once( logger.info, "Converting AWQ model to Exllama/GPTQ packing format." ) from text_generation_server.layers.awq.conversion_utils import ( fast_awq_to_gptq, ) qweight, qzeros = fast_awq_to_gptq(qweight, qzeros) if use_exllama: g_idx = None else: g_idx = ( torch.arange( qweight.shape[0] * (32 // self.bits), device=qweight.device, ) // self.groupsize ).to(dtype=torch.int32) else: g_idx = None return GPTQWeight( qweight=qweight, qzeros=qzeros, scales=scales, g_idx=g_idx, bits=self.bits, groupsize=self.groupsize, use_awq_kernel=self.quantize == "awq", use_exllama=use_exllama, ) def get_weights_row(self, weights: Weights, prefix: str): self._get_gptq_params(weights) use_exllama = True if self.bits != 4: use_exllama = False if self.desc_act: log_once(logger.warning, "Disabling exllama because desc_act=True") use_exllama = False try: qweight = weights.get_sharded(f"{prefix}.qweight", dim=0) except RuntimeError: raise RuntimeError( "Cannot load `gptq` weight, make sure the model is already quantized, or quantize it with `text-generation-server quantize ORIGINAL_MODEL_ID NEW_MODEL_ID`" ) if self.quantize == "gptq" and self.quant_method == "gptq": g_idx = weights.get_sharded(f"{prefix}.g_idx", dim=0) else: g_idx = None if weights.process_group.size() > 1: if g_idx is not None: if ( not torch.equal( g_idx.cpu(), torch.tensor( [i // self.groupsize for i in range(g_idx.shape[0])], dtype=torch.int32, ), ) and not (g_idx == 0).all() ): # Exllama implementation does not support row tensor parallelism with act-order, as # it would require to reorder input activations that are split unto several GPUs use_exllama = False from text_generation_server.layers.gptq import ( CAN_EXLLAMA, HAS_EXLLAMA, GPTQWeight, ) if use_exllama: if not HAS_EXLLAMA: if CAN_EXLLAMA: log_once( logger.warning, "Exllama GPTQ cuda kernels (which are faster) could have been used, but are not currently installed, try using BUILD_EXTENSIONS=True", ) use_exllama = False else: log_once(logger.info, f"Using exllama kernels v{HAS_EXLLAMA}") if use_exllama and self.groupsize != -1: qzeros = weights.get_sharded(f"{prefix}.qzeros", dim=0) scales = weights.get_sharded(f"{prefix}.scales", dim=0) else: qzeros = weights.get_tensor(f"{prefix}.qzeros") scales = weights.get_tensor(f"{prefix}.scales") if use_exllama and g_idx is not None: g_idx = g_idx - g_idx[0] if self.quantize == "gptq" and self.quant_method == "awq": log_once( logger.info, "Converting AWQ model to Exllama/GPTQ packing format." ) from text_generation_server.layers.awq.conversion_utils import ( fast_awq_to_gptq, ) qweight, qzeros = fast_awq_to_gptq(qweight, qzeros) if use_exllama: g_idx = None else: g_idx = ( torch.arange( qweight.shape[0] * (32 // self.bits), device=qweight.device, ) // self.groupsize ).to(dtype=torch.int32) return GPTQWeight( qweight=qweight, qzeros=qzeros, scales=scales, g_idx=g_idx, bits=self.bits, groupsize=self.groupsize, use_awq_kernel=self.quantize == "awq", use_exllama=use_exllama, ) def _get_gptq_params(self, weights: Weights): if weights._has_tensor("gptq_bits") and weights._has_tensor("gptq_groupsize"): self.bits = weights.get_tensor("gptq_bits").item() self.groupsize = weights.get_tensor("gptq_groupsize").item() self.desc_act = False # `server quantize` used asymmetric quantization unconditionally # before the `gptq_sym` setting tensor was added. self.sym = ( weights.get_tensor("gptq_sym").item() if weights._has_tensor("gptq_sym") else False ) self.quant_method = "gptq" # Needs to be at the end because circular import. try: major, _minor = torch.cuda.get_device_capability() except Exception: major = 1 HAS_EXLLAMA = False CAN_EXLLAMA = major >= 8 or SYSTEM == "rocm" V2 = os.getenv("EXLLAMA_VERSION", "2") == "2" if os.getenv("DISABLE_EXLLAMA") == "True": HAS_EXLLAMA = False elif CAN_EXLLAMA: try: if V2: from text_generation_server.layers.gptq.exllamav2 import ( QuantLinear as ExllamaQuantLinear, # noqa: F401 create_exllama_buffers, # noqa: F401 set_device, # noqa: F401 ) HAS_EXLLAMA = "2" else: from text_generation_server.layers.gptq.exllama import ( Ex4bitLinear as ExllamaQuantLinear, # noqa: F401 create_exllama_buffers, # noqa: F401 set_device, # noqa: F401 ) HAS_EXLLAMA = "1" except ImportError: pass
text-generation-inference/server/text_generation_server/layers/gptq/__init__.py/0
{ "file_path": "text-generation-inference/server/text_generation_server/layers/gptq/__init__.py", "repo_id": "text-generation-inference", "token_count": 8210 }
233
import torch import math from torch import nn from torch.nn import functional as F from typing import Optional, Tuple from text_generation_server.layers import TensorParallelEmbedding, FastLinear from text_generation_server.layers.tensor_parallel import TensorParallelHead from text_generation_server.utils.speculate import get_speculate class MLPSpeculatorLayerNorm(nn.Module): """ A L2 normalization implementation ... Args ---- normalized_shape : int Dimensionality of input data (size of final tensor axis) elementwise_scale_weight : torch.Tensor learned scaling term after normalization? elementwise_shift_bias : torch.Tensor learned bias term after normalization? eps : float Safety term to prevent division by zero. Make sure the chosen value fits in the range of your encoding scheme (i.e. fp16 requires eps >= 6e-8). """ def __init__( self, prefix, config, weights, eps=1e-06, ): super(MLPSpeculatorLayerNorm, self).__init__() self.weight = weights.get_tensor(f"{prefix}.weight") self.bias = weights.get_tensor(f"{prefix}.bias") self.eps = eps def forward(self, x): xf = x xf = xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + self.eps) x = xf.type_as(x) x = self.weight * x x = x + self.bias return x INV_SQRT2 = 2**-0.5 def simple_norm(x: torch.Tensor, eps=1e-06): xf = x xf = xf * torch.rsqrt(xf.pow(2).mean(-1, keepdim=True) + eps) x = xf.type_as(x) return x * INV_SQRT2 class MLPSpeculatorModelTied(torch.nn.Module): def __init__(self, config, prefix, weights): super().__init__() self.config = config self.n_predict = get_speculate() self.hidden_size = config.hidden_size self.emb = TensorParallelEmbedding(f"{prefix}.emb.0", weights) self.proj0 = FastLinear.load( config, prefix=f"{prefix}.proj.0", weights=weights, bias=False, ) self.proj1 = FastLinear.load( config, prefix=f"{prefix}.proj.1", weights=weights, bias=False, ) self.head = FastLinear.load(config, f"{prefix}.head.0", weights, bias=False) self.ln = MLPSpeculatorLayerNorm( prefix=f"{prefix}.ln.0", config=config, weights=weights, ) # Weights ensure that state_0 accounts for 50% of state magnitude by final head in expectation self.state_weight = 0.5 ** (0.5 / self.n_predict) if self.n_predict > 0 else 1 self.activation = nn.GELU() self.vsize = config.vocab_size self.inner_dim = config.speculator_config["inner_dim"] self.top_k_tokens_per_head = [1] * self.n_predict self.emb_weight = math.sqrt(1 - self.state_weight**2) * math.sqrt( self.inner_dim / 2 ) self.emb.weight *= self.emb_weight def forward( self, hidden_states: torch.Tensor, input_ids: torch.Tensor, ): top_k_tokens_per_head = self.top_k_tokens_per_head # k indicates # of candidates # h indicates # of generated tokens state = hidden_states b = state.size(0) ind = input_ids.unsqueeze(0) all_probs = torch.empty( b, self.n_predict, self.vsize, device=state.device ) # b k h v assert ( len(top_k_tokens_per_head) == self.n_predict ), f"You must provide a topk number for each head ({self.n_predict} heads, {len(top_k_tokens_per_head)} provided)" for i in range(self.n_predict): # Project and predict z = self.emb(ind) # z = z.mul(self.emb_weight) # b k d if i == 0: state = self.proj0(state) * self.state_weight + z else: state = self.proj1(state) * self.state_weight + z state = self.activation(self.ln(state)) # b k d probs = F.log_softmax(self.head(state), dim=-1) # b k v _probs, preds = probs.topk(top_k_tokens_per_head[i], dim=-1) # b k k' # Update candidate set with new predictions # Update distribution set with new logits all_probs[:, i] = probs.exp() # Update state, log_probs and ind for new predictions state = state.unsqueeze(2).expand( -1, -1, top_k_tokens_per_head[i], -1 ) # b k k' d state = state.reshape(-1, b, state.size(3)) # b kk' d ind = preds.view(-1, b) # b kk' speculative_logits = all_probs return speculative_logits class MLPSpeculatorModel(torch.nn.Module): def __init__(self, config, prefix, weights): super().__init__() self.config = config self.n_predict = get_speculate() self.hidden_size = config.hidden_size self.emb = nn.ModuleList( [ TensorParallelEmbedding(f"{prefix}.emb.{i}", weights) for i in range(self.n_predict) ] ) self.proj = [ FastLinear.load( config, prefix=f"{prefix}.proj.{i}", weights=weights, bias=False, ) for i in range(self.n_predict) ] self.head = nn.ModuleList( [ FastLinear.load(config, f"{prefix}.head.{i}", weights, bias=False) for i in range(self.n_predict) ] ) self.ln = nn.ModuleList( [ MLPSpeculatorLayerNorm( prefix=f"{prefix}.ln.{i}", config=config, weights=weights, ) for i in range(self.n_predict) ] ) # Weights ensure that state_0 accounts for 50% of state magnitude by final head in expectation self.state_weight = 0.5 ** (0.5 / self.n_predict) if self.n_predict > 0 else 1 self.activation = nn.GELU() self.vsize = config.vocab_size self.inner_dim = config.speculator_config["inner_dim"] self.top_k_tokens_per_head = [1] * self.n_predict self.emb_weight = math.sqrt(1 - self.state_weight**2) * math.sqrt( self.inner_dim / 2 ) self.emb.weight *= self.emb_weight def forward( self, hidden_states: torch.Tensor, input_ids: torch.Tensor, ): top_k_tokens_per_head = self.top_k_tokens_per_head # k indicates # of candidates # h indicates # of generated tokens state = hidden_states b = state.size(0) ind = input_ids.unsqueeze(0) all_probs = torch.empty( b, self.n_predict, self.vsize, device=state.device ) # b k h v assert ( len(top_k_tokens_per_head) == self.n_predict ), f"You must provide a topk number for each head ({self.n_predict} heads, {len(top_k_tokens_per_head)} provided)" for i in range(self.n_predict): # Project and predict z = self.emb[i](ind) # z = z.mul(self.emb_weight) # b k d state = self.proj[i](state) * self.state_weight + z state = self.activation(self.ln[i](state)) # b k d probs = F.log_softmax(self.head[i](state), dim=-1) # b k v _probs, preds = probs.topk(top_k_tokens_per_head[i], dim=-1) # b k k' # Update candidate set with new predictions # Update distribution set with new logits all_probs[:, i] = probs.exp() # Update state, log_probs and ind for new predictions state = state.unsqueeze(2).expand( -1, -1, top_k_tokens_per_head[i], -1 ) # b k k' d state = state.reshape(-1, b, state.size(3)) # b kk' d ind = preds.view(-1, b) # b kk' speculative_logits = all_probs return speculative_logits class MLPSpeculatorHead(nn.Module): def __init__(self, lm_head, mlp_speculator, scale_input: bool): super().__init__() self.lm_head = lm_head self.mlp_speculator = mlp_speculator self.scale_input = scale_input def forward( self, input: torch.Tensor ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: logits = self.lm_head(input) # If we have too many tokens, we skip speculative logits if input.shape[0] > 128: return logits, None input_ids = logits.argmax(dim=-1) if self.scale_input: input = simple_norm(input) speculative_logits = self.mlp_speculator(input, input_ids) return logits, speculative_logits @staticmethod def load(config, prefix: str, weights): from pathlib import Path from safetensors import safe_open speculator_path = config.speculator["path"] for fname in config.speculator["model_paths"]: filename = str(Path(speculator_path) / fname) routing = weights.routing with safe_open(filename, framework="pytorch") as f: for k in f.keys(): if k in routing and routing[k] != filename: raise RuntimeError( f"Key {k} was found in multiple files: {filename} and {routing[k]}" ) routing[k] = filename tie_weights = config.speculator_config.get("tie_weights", False) if tie_weights: mlp_speculator = MLPSpeculatorModelTied(config, "speculator", weights) else: mlp_speculator = MLPSpeculatorModel(config, "speculator", weights) # This is used in https://huggingface.co/ibm-fms/llama3-70b-accelerator scale_input = config.speculator_config.get("scale_input", False) lm_head = TensorParallelHead.load(config, prefix, weights) return MLPSpeculatorHead(lm_head, mlp_speculator, scale_input)
text-generation-inference/server/text_generation_server/layers/mlp.py/0
{ "file_path": "text-generation-inference/server/text_generation_server/layers/mlp.py", "repo_id": "text-generation-inference", "token_count": 5007 }
234
# coding=utf-8 # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved. # # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX # and OPT implementations in this library. It has been modified from its # original forms to accommodate minor architectural differences compared # to GPT-NeoX and OPT used by the Meta AI team that trained the model. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import torch import torch.distributed from torch import nn from transformers.activations import ACT2FN from typing import Optional, List, Tuple from text_generation_server.layers.attention import ( paged_attention, attention, reshape_and_cache, Seqlen, ) from text_generation_server.layers import ( TensorParallelRowLinear, TensorParallelColumnLinear, TensorParallelEmbedding, SpeculativeHead, get_linear, ) from text_generation_server.layers.rotary import ( PositionRotaryEmbedding, ) from text_generation_server.layers.layernorm import ( FastLayerNorm, ) from text_generation_server.utils.import_utils import SYSTEM def load_attention(config, prefix: str, weights): return TensorParallelColumnLinear.load_multi( config, prefixes=[f"{prefix}.q_proj", f"{prefix}.k_proj", f"{prefix}.v_proj"], dim=0, weights=weights, bias=False, ) def load_row(config, prefix: str, weights, bias: bool): weight = weights.get_weights_row(prefix) if bias and weights.process_group.rank() == 0: # Rank is only on the first rank process bias = weights.get_tensor(f"{prefix}.bias") else: bias = None linear = get_linear(weight, bias) return TensorParallelRowLinear(linear, process_group=weights.process_group) class GPTJRotary(PositionRotaryEmbedding): def forward( self, query: torch.Tensor, key: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, ): # Such controlflows may add some overhead. if SYSTEM == "cuda": import rotary_emb q1 = query[..., ::2] q2 = query[..., 1::2] rotary_emb.apply_rotary(q1, q2, cos, sin, q1, q2, False) k1 = key[..., ::2] k2 = key[..., 1::2] rotary_emb.apply_rotary(k1, k2, cos, sin, k1, k2, False) elif SYSTEM == "rocm": from vllm._C import ops # NOTE: On RoCm systems, we use a ROPE implementatation adapted from VLLM which launches a single kernel for both query/key, contrary to flash-attn implementation used on NVIDIA systems. # Compiling flash-attn rotary on RoCm, it appears hipcc is unable to unroll loops, resulting in an even slower inference compared to eager: https://github.com/pytorch/pytorch/issues/113773 head_size = query.shape[-1] # Inplace operation, updating query and key. ops.rotary_embedding(query, key, head_size, cos, sin, False) elif SYSTEM == "ipex": import intel_extension_for_pytorch as ipex ipex.llm.functional.rotary_embedding( query, key, sin, cos, query.size(-1), False ) else: raise ValueError( "Your system seem to be not supported. Please check your install or open an issue at https://github.com/huggingface/text-generation-inference/issues with a clear reproduction." ) class FlashGPTJAttention(torch.nn.Module): def __init__( self, prefix: str, config, weights, ): super().__init__() self.num_heads = config.num_attention_heads self.hidden_size = config.hidden_size self.head_size = self.hidden_size // self.num_heads self.softmax_scale = self.head_size**-0.5 self.rotary_dim = config.rotary_dim if self.num_heads % weights.process_group.size() != 0: raise ValueError( f"`num_heads` must be divisible by `num_shards` (got `num_heads`: {self.num_heads} " f"and `num_shards`: {weights.process_group.size()}" ) self.num_heads = self.num_heads // weights.process_group.size() self.query_key_value = load_attention( config, prefix=prefix, weights=weights, ) self.o_proj = load_row( config, prefix=f"{prefix}.out_proj", weights=weights, bias=False, ) self.kv_head_mapping = torch.arange( 0, self.num_heads, dtype=torch.int32, device=weights.device ) self.rotary_emb = GPTJRotary.static( config=config, dim=self.rotary_dim, base=10000, device=weights.device, ) def forward( self, hidden_states, cos, sin, cu_seqlen_prefill, kv_cache, block_tables, slots, seqlen, max_s, ): query, key, value = self.query_key_value(hidden_states).split( self.head_size * self.num_heads, dim=1 ) query = query.view(-1, self.num_heads, self.head_size) key = key.view(-1, self.num_heads, self.head_size) value = value.view(-1, self.num_heads, self.head_size) # Compute rotary embeddings on rotary_ndims if self.rotary_dim is not None: self.rotary_emb( query[..., : self.rotary_dim], key[..., : self.rotary_dim], cos, sin ) else: self.rotary_emb(query, key, cos, sin) reshape_and_cache(key, value, kv_cache[0], kv_cache[1], slots) # Prefill if cu_seqlen_prefill is not None: # flash attention attn_output = attention( query, kv_cache[0], kv_cache[1], seqlen, block_tables, self.softmax_scale, ) # Decode else: attn_output = paged_attention( query, kv_cache[0], kv_cache[1], self.kv_head_mapping, self.softmax_scale, block_tables, seqlen, max_s, ) return self.o_proj(attn_output.view(-1, self.num_heads * self.head_size)) class GPTJMLP(nn.Module): def __init__(self, prefix: str, config, weights): super().__init__() act = config.activation_function self.act = ( ACT2FN[act] if "gelu" not in act else lambda x: torch.nn.functional.gelu( x, approximate=( "tanh" if act in ["gelu_fast", "gelu_pytorch_tanh"] else "none" ), ) ) self.fc_in = TensorParallelColumnLinear.load( config, prefix=f"{prefix}.fc_in", weights=weights, bias=True ) self.fc_out = load_row( config, prefix=f"{prefix}.fc_out", weights=weights, bias=True, ) def forward(self, hidden_states): hidden_states = self.fc_in(hidden_states) hidden_states = self.act(hidden_states) return self.fc_out(hidden_states) class FlashGPTJLayer(nn.Module): def __init__(self, prefix: str, config, weights): super().__init__() self.self_attn = FlashGPTJAttention( prefix=f"{prefix}.attn", config=config, weights=weights ) self.mlp = GPTJMLP(prefix=f"{prefix}.mlp", config=config, weights=weights) self.input_layernorm = FastLayerNorm.load( prefix=f"{prefix}.ln_1", weights=weights, eps=config.layer_norm_epsilon ) def forward( self, hidden_states, residual, cos, sin, cu_seqlen_prefill, kv_cache, block_tables, slots, seqlen, max_s, ): hidden_states, residual = self.input_layernorm(hidden_states, residual) # Self Attention attn_output = self.self_attn( hidden_states, cos, sin, cu_seqlen_prefill, kv_cache, block_tables, slots, seqlen, max_s, ) feed_forward_hidden_states = self.mlp(hidden_states) return attn_output + feed_forward_hidden_states, residual class FlashGPTJModel(torch.nn.Module): def __init__(self, prefix: str, config, weights): super().__init__() self.config = config self.wte = TensorParallelEmbedding(prefix=f"{prefix}.wte", weights=weights) self.layers = nn.ModuleList( [ FlashGPTJLayer( prefix=( f"h.{layer_id}" if not prefix else f"{prefix}.h.{layer_id}" ), config=config, weights=weights, ) for layer_id in range(config.num_hidden_layers) ] ) self.ln_f = FastLayerNorm.load( prefix="ln_f" if not prefix else f"{prefix}.ln_f", weights=weights, eps=config.layer_norm_epsilon, ) self.gradient_checkpointing = False self.head_size = self.layers[0].self_attn.head_size self.num_heads = self.layers[0].self_attn.num_heads def forward( self, input_ids: Optional[torch.LongTensor], position_ids: torch.Tensor, cu_seqlen_prefill: Optional[torch.Tensor], kv_cache: List[Tuple[torch.Tensor, torch.Tensor]], block_tables: torch.Tensor, slots: torch.Tensor, seqlen: Seqlen, max_s: int, prefill_cache_indices: Optional[torch.Tensor], ) -> torch.Tensor: hidden_states = self.wte(input_ids) # Get rotary cos and sin for this forward # Avoid to index in each layer cos, sin = self.layers[0].self_attn.rotary_emb.get_cos_sin( position_ids, max_s, hidden_states.dtype ) residual = None for i, layer in enumerate(self.layers): hidden_states, residual = layer( hidden_states, residual, cos, sin, cu_seqlen_prefill, kv_cache[i], block_tables, slots, seqlen, max_s, ) hidden_states, _ = self.ln_f(hidden_states, residual) return hidden_states class FlashGPTJForCausalLM(torch.nn.Module): def __init__(self, prefix: str, config, weights): super().__init__() if not prefix: prefix = "transformer" else: prefix = f"{prefix}.transformer" self.model = FlashGPTJModel(prefix, config, weights) self.lm_head = SpeculativeHead.load( config, prefix="lm_head", weights=weights, ) def forward( self, input_ids: torch.Tensor, position_ids: torch.Tensor, cu_seqlen_prefill: Optional[torch.Tensor], kv_cache: List[Tuple[torch.Tensor, torch.Tensor]], block_tables: torch.Tensor, slots: torch.Tensor, seqlen: Seqlen, max_s: int, prefill_cache_indices: Optional[torch.Tensor] = None, lm_head_indices: Optional[torch.Tensor] = None, adapter_data: Optional[torch.Tensor] = None, ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: hidden_states = self.model( input_ids, position_ids, cu_seqlen_prefill, kv_cache, block_tables, slots, seqlen, max_s, prefill_cache_indices=prefill_cache_indices, ) if lm_head_indices is not None: hidden_states = hidden_states[lm_head_indices] logits, speculative_logits = self.lm_head(hidden_states) return logits, speculative_logits
text-generation-inference/server/text_generation_server/models/custom_modeling/flash_gptj_modeling.py/0
{ "file_path": "text-generation-inference/server/text_generation_server/models/custom_modeling/flash_gptj_modeling.py", "repo_id": "text-generation-inference", "token_count": 6196 }
235
# coding=utf-8 # Copyright 2022 The HuggingFace Inc. team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Processor class for IDEFICS. """ from typing import Callable, List, Optional, Union from urllib.parse import urlparse from transformers.feature_extraction_utils import BatchFeature from transformers.processing_utils import ProcessorMixin from transformers.tokenization_utils_base import ( BatchEncoding, PaddingStrategy, TextInput, TruncationStrategy, ) from transformers.utils import TensorType, is_torch_available if is_torch_available(): import torch IMAGE_TOKEN = "<image>" # copied from m4.training.packing def incremental_to_binary_attention_mask(incremental_mask, num_classes=-1): # This function converts: [-1, 0, 1] => [[0, 0], [1, 0], [0, 1]] # If any of images index are more than num_classes, set them to -1. # Words after the max number of images allowed have been seen don't attend on anything if num_classes != -1: incremental_mask[incremental_mask >= num_classes] = -1 negatives = incremental_mask == -1 incremental_mask[negatives] = 0 attn_mask = torch.nn.functional.one_hot(incremental_mask, num_classes=num_classes) attn_mask[negatives, :] = 0 return attn_mask # copied from m4.training.packing def image_attention_mask_for_packed_input_ids(input_ids, tokenizer): image_attention_mask = torch.full_like(input_ids, fill_value=-1) next_image_attention_mask = torch.full_like(input_ids, fill_value=-1) image_token_id = tokenizer.convert_tokens_to_ids(IMAGE_TOKEN) eod_token_id = tokenizer.eos_token_id for batch_idx in range(input_ids.size(0)): count = -1 seen_eod = False for idx, token_id in enumerate(input_ids[batch_idx]): if token_id == image_token_id: count += 1 image_attention_mask[batch_idx][idx] = count seen_eod = False else: image_attention_mask[batch_idx][idx] = count if seen_eod: image_attention_mask[batch_idx][idx] = -1 if token_id == eod_token_id: seen_eod = True for batch_idx in range(input_ids.size(0)): count = -1 seen_eod = False for idx in range(input_ids[batch_idx].size(0) - 1, -1, -1): token_id = input_ids[batch_idx][idx] if token_id == image_token_id: count += 1 next_image_attention_mask[batch_idx][idx] = count seen_eod = False else: next_image_attention_mask[batch_idx][idx] = count if token_id == eod_token_id: seen_eod = True if seen_eod: next_image_attention_mask[batch_idx][idx] = -1 non_negative_indices = next_image_attention_mask[batch_idx] != -1 next_image_attention_mask[batch_idx][non_negative_indices] -= count next_image_attention_mask[batch_idx][non_negative_indices] *= -1 return image_attention_mask, next_image_attention_mask def is_url(string): """Checks if the passed string contains a valid url and nothing else. e.g. if space is included it's immediately invalidated the url""" if " " in string: return False result = urlparse(string) return all([result.scheme, result.netloc]) def is_image(string): """Checks if the passed string contains a valid url and nothing else. e.g. if space is included it's immediately invalidated the url""" return is_url(string) or string.startswith("data:") class IdeficsProcessor(ProcessorMixin): r""" Constructs a IDEFICS processor which wraps a LLama tokenizer and IDEFICS image processor into a single processor. [`IdeficsProcessor`] offers all the functionalities of [`IdeficsImageProcessor`] and [`LlamaTokenizerFast`]. See the docstring of [`~IdeficsProcessor.__call__`] and [`~IdeficsProcessor.decode`] for more information. Args: image_processor (`IdeficsImageProcessor`): An instance of [`IdeficsImageProcessor`]. The image processor is a required input. tokenizer (`LlamaTokenizerFast`): An instance of [`LlamaTokenizerFast`]. The tokenizer is a required input. image_size (`int`, *optional*, defaults to 224): Image size (assuming a square image) """ attributes = ["image_processor", "tokenizer"] image_processor_class = "IdeficsImageProcessor" tokenizer_class = "LlamaTokenizerFast" def __init__( self, image_processor, tokenizer=None, image_size=224, add_end_of_utterance_token=None, **kwargs, ): if image_processor is None: raise ValueError("You need to specify an `image_processor`.") if tokenizer is None: raise ValueError("You need to specify a `tokenizer`.") super().__init__(image_processor, tokenizer) self.current_processor = self.image_processor self.image_token_id = tokenizer.convert_tokens_to_ids(IMAGE_TOKEN) self.default_image_dims = ( self.image_processor.image_num_channels, self.image_processor.image_size, self.image_processor.image_size, ) self.tokenizer_was_trained_with_end_of_utterance_token = ( True if "<end_of_utterance>" in self.tokenizer.special_tokens_map.get("additional_special_tokens", []) else False ) def __call__( self, prompts: Union[List[TextInput], List[List[TextInput]]], padding: Union[bool, str, PaddingStrategy] = False, truncation: Union[bool, str, TruncationStrategy] = None, max_length: Optional[int] = None, transform: Callable = None, add_eos_token=False, add_end_of_utterance_token=None, debug=False, return_tensors: Optional[Union[str, TensorType]] = TensorType.PYTORCH, ) -> BatchEncoding: """This method takes batched or non-batched prompts made of text and images and converts them into prompts that the model was trained on and prepares the image pixel values for the model to process. Args: prompts (`Union[List[TextInput], [List[List[TextInput]]]]`): either a single prompt or a batched list of prompts - see the detailed description immediately after the end of the arguments doc section. padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`): Select a strategy to pad the returned sequences (according to the model's padding side and padding index) among: - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided). - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different lengths). max_length (`int`, *optional*): Maximum length of the returned list and optionally padding length (see above). truncation (`bool`, *optional*): Activates truncation to cut input sequences longer than `max_length` to `max_length`. transform (`Callable`, *optional*): A custom transform function that accepts a single image can be passed for training. For example, `torchvision.Compose` can be used to compose multiple functions. If `None` a preset inference-specific set of transforms will be applied to the images add_eos_token (`bool`, *optional*, defaults to `False`): Adds `eos_token` at the end of the final prompt if True` add_end_of_utterance_token (`bool`, *optional*) Whether to automatically add `<end_of_utterance>` after each prompt's text input (unless followed by an image). If `None` the tokenizer will be checked instead and if this token is found in `additional_special_tokens` then the value will be `True`. debug (`bool`, *optional*, defaults to `False`): `True` value will help debug prompt generation by dumping useful information return_tensors (`str` or `TensorType`, *optional*, defaults to `TensorType.PYTORCH`): The type of tensors to return. Can be one of: - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`. Returns: a dict with entries: `input_ids`, `attention_mask`, `pixel_values`, `image_attention_mask` which can be directly passed to `model.generate` Detailed explanation: Each entry in `prompts` is either a text to be passed as is or an image that will be processed. An image can be either an image object (`PIL.Image`) or a url from which the image can be retrieved. When the processor encounters an image it'll inject `<fake_token_around_image><image><fake_token_around_image>` entry into the prompt. Example: ```python checkpoint = "HuggingFaceM4/idefics-9b" processor = AutoProcessor.from_pretrained(checkpoint) url = "https://hips.hearstapps.com/hmg-prod/images/cute-photos-of-cats-in-grass-1593184777.jpg" img = processor.image_processor.fetch_images([url])[0] prompts = [ "User:", img, "Describe this image.\nAssistant: An image of two kittens in grass.\n", "User:", "https://hips.hearstapps.com/hmg-prod/images/dog-puns-1581708208.jpg", "Describe this image.\nAssistant:", ] inputs = processor(prompts, return_tensors="pt") generated_ids = model.generate(**inputs, max_length=100) generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0] ``` In this example the `prompts` will be converted into: ``` <s>User:<fake_token_around_image><image><fake_token_around_image>Describe this image. Assistant: An image of two kittens in grass. User:<fake_token_around_image><image><fake_token_around_image>Describe this image. Assistant:' ``` and the two images will be massaged using [`IdeficsImageProcessor.__call__`] method and placed inside the `pixel_values` dict entry of the return value. This example also examplifies that images can be passed as objects or as text urls. It can be seen that the first image is passed as object and the second one as a url. To do training do: ```python image_transform = transforms.Compose( [ transforms.RandomResizedCrop( (w, h), scale=(0.9, 1.0), interpolation=transforms.InterpolationMode.BICUBIC ), transforms.ToTensor(), transforms.Normalize(mean=self.image_mean, std=self.image_std), ] ) inputs = processor(prompts, transform=image_transform, return_tensors="pt") ``` In order to help debug prompt generation enable `debug=True` which will show you what's happening. """ # if the value isn't overriden by the user, check if the tokenizer was trained with this token and then use it if add_end_of_utterance_token is None: add_end_of_utterance_token = ( self.tokenizer_was_trained_with_end_of_utterance_token ) # turn non-batched prompts into batched if not any(isinstance(i, list) for i in prompts): prompts = [prompts] fake_token = "<fake_token_around_image>" image_token = "<image>" end_of_utterance_token = "<end_of_utterance>" def image_tokens(last_was_image): if last_was_image: return image_token + fake_token else: return fake_token + image_token + fake_token all_texts = [] all_images = [] for sample in prompts: # the model was trained on samples starting with <s> full_text = f"{self.tokenizer.bos_token}" # an image can either be an image object in the item or the url, everything else is a verbatim prompt text image_objects = [] last_was_image = False last_was_text = False for i, item in enumerate(sample): if i > 0: last_was_text = True if not last_was_image else False if isinstance(item, str): item = item.strip(" ") if is_image(item): image = self.image_processor.fetch_images(item) full_text += image_tokens(last_was_image) image_objects.append(image) last_was_image = True else: # we add end_of_utterance_token between each subsequent text prompts (but not at the last one!) if add_end_of_utterance_token and last_was_text: full_text += end_of_utterance_token full_text += item last_was_image = False else: # must be an image obj full_text += image_tokens(last_was_image) image_objects.append(item) last_was_image = True if add_eos_token: full_text += self.tokenizer.eos_token if debug is True: print(f"{full_text=}") image_objects = self.image_processor(image_objects, transform=transform) text_encoding = self.tokenizer( text=full_text, add_special_tokens=False, padding=padding, truncation=truncation, max_length=max_length, ) all_texts.append(text_encoding["input_ids"]) all_images.append(image_objects) max_seq_len = max(len(x) for x in all_texts) # max_num_images has to be at least 1 even when there are no images max_num_images = max(len(x) for x in all_images) max_num_images = max(1, max_num_images) at_least_one_image = sum(len(x) for x in all_images) > 0 output_input_ids = [] output_images = [] output_attention_masks = [] for text, images in zip(all_texts, all_images): padded_input_ids = [self.tokenizer.pad_token_id] * max_seq_len unpadded_seq_len = len(text) start = max_seq_len - unpadded_seq_len padded_input_ids[start:] = text[:max_seq_len] attention_mask = torch.zeros((max_seq_len,), dtype=torch.long) attention_mask[start:] = 1 image_count = padded_input_ids.count(self.image_token_id) local_max_num_images = min(image_count, max_num_images) current_images = images[:local_max_num_images] if len(current_images) > 0: padded_image_tensor = torch.zeros( max_num_images, *current_images.size()[1:] ) padded_image_tensor[: current_images.size(0)] = current_images else: padded_image_tensor = torch.zeros( max_num_images, *self.default_image_dims ) output_images.append(padded_image_tensor) output_input_ids.append(torch.tensor(padded_input_ids)) output_attention_masks.append(attention_mask) output_input_ids = torch.stack(output_input_ids) output_images = torch.stack(output_images) output_attention_masks = torch.stack(output_attention_masks) if at_least_one_image: image_attention_mask, _ = image_attention_mask_for_packed_input_ids( output_input_ids, self.tokenizer ) image_attention_mask = incremental_to_binary_attention_mask( image_attention_mask, num_classes=max_num_images ) else: # in full language mode we set the image mask to all-0s image_attention_mask = torch.zeros( output_input_ids.shape[0], output_input_ids.shape[1], 1, dtype=torch.bool, ) return BatchFeature( data={ "input_ids": output_input_ids, "attention_mask": output_attention_masks, "pixel_values": output_images, "image_attention_mask": image_attention_mask, } ) def batch_decode(self, *args, **kwargs): """ This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please refer to the docstring of this method for more information. """ return self.tokenizer.batch_decode(*args, **kwargs) def decode(self, *args, **kwargs): """ This method forwards all its arguments to LlamaTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to the docstring of this method for more information. """ return self.tokenizer.decode(*args, **kwargs) @property def model_input_names(self): tokenizer_input_names = self.tokenizer.model_input_names image_processor_input_names = self.image_processor.model_input_names return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names))
text-generation-inference/server/text_generation_server/models/custom_modeling/idefics_processing.py/0
{ "file_path": "text-generation-inference/server/text_generation_server/models/custom_modeling/idefics_processing.py", "repo_id": "text-generation-inference", "token_count": 8120 }
236
import torch import torch.distributed from transformers import AutoTokenizer, PreTrainedTokenizerBase from typing import Optional from text_generation_server.models.custom_modeling.mamba_modeling import ( MambaConfig, ) from loguru import logger from text_generation_server.pb import generate_pb2 from text_generation_server.utils import ( initialize_torch_distributed, weight_files, Weights, ) from text_generation_server.models.globals import CUDA_GRAPHS, MEM_POOL import time from text_generation_server.models.custom_modeling.mamba_modeling import ( MambaModel, InferenceParams, ) from text_generation_server.models import Model from typing import Any, List, Tuple, Type, Dict from text_generation_server.models.types import ( Batch, Tokens, Generation, GeneratedText, ) from text_generation_server.utils.chunks import concat_text_chunks from text_generation_server.utils.quantization import get_loader from text_generation_server.utils.tokens import batch_top_tokens, Sampling from dataclasses import dataclass from text_generation_server.utils import NextTokenChooser, StoppingCriteria def new_inference_params( n_blocks: int, batch_size: int, d_inner: int, d_conv: int, d_state: int, seqlen_offset: int, dtype: torch.dtype, device: torch.device, ): max_seqlen = 0 conv_states = torch.zeros( ( n_blocks, batch_size, d_inner, d_conv, ), device=device, dtype=dtype, ) ssm_states = torch.zeros( ( n_blocks, batch_size, d_inner, d_state, ), device=device, dtype=dtype, ) inference_params = InferenceParams( max_seqlen=max_seqlen, max_batch_size=batch_size, seqlen_offset=seqlen_offset, conv_states=conv_states, ssm_states=ssm_states, ) return inference_params @dataclass class MambaBatch(Batch): batch_id: int requests: List[generate_pb2.Request] requests_idx_mapping: Dict[int, int] # Decoder values input_ids: torch.Tensor # All tokens all_input_ids: List[torch.Tensor] # Lengths of all generations present in the batch input_lengths: List[int] prefix_offsets: List[int] read_offsets: List[int] # Generation helpers next_token_choosers: List[NextTokenChooser] stopping_criterias: List[StoppingCriteria] top_n_tokens: List[int] top_n_tokens_tensor: torch.Tensor # Metadata used for padding max_input_length: int padding_right_offset: int # Maximum number of tokens this batch will grow to max_tokens: int # Past metadata keys_head_dim_last: bool = True # Inference params inference_params: Optional[Dict[str, Any]] = None def to_pb(self) -> generate_pb2.CachedBatch: return generate_pb2.CachedBatch( id=self.batch_id, request_ids=[r.id for r in self.requests], size=len(self), max_tokens=self.max_tokens, ) @classmethod def from_pb( cls, pb: generate_pb2.Batch, tokenizer: PreTrainedTokenizerBase, dtype: torch.dtype, device: torch.device, ) -> "MambaBatch": inputs = [] next_token_choosers = [] stopping_criterias = [] top_n_tokens = [] prefix_offsets = [] read_offsets = [] requests_idx_mapping = {} # Parse batch max_truncation = 0 padding_right_offset = 0 max_decode_tokens = 0 for i, r in enumerate(pb.requests): requests_idx_mapping[r.id] = i inputs.append(concat_text_chunks(r.input_chunks.chunks)) next_token_choosers.append( NextTokenChooser.from_pb(r.parameters, device, tokenizer) ) stopping_criteria = StoppingCriteria.from_pb( r.stopping_parameters, tokenizer ) stopping_criterias.append(stopping_criteria) top_n_tokens.append(r.top_n_tokens) max_truncation = max(max_truncation, r.truncate) max_decode_tokens += stopping_criteria.max_new_tokens padding_right_offset = max( padding_right_offset, stopping_criteria.max_new_tokens ) tokenized_inputs = tokenizer( inputs, return_tensors="pt", padding=True, return_token_type_ids=False, truncation=True, max_length=max_truncation, ).to(device) for _ in pb.requests: input_len = tokenized_inputs["input_ids"].shape[1] prefix_offsets.append(input_len - 5) read_offsets.append(input_len) input_lengths = tokenized_inputs["attention_mask"].sum(1) max_input_length = input_lengths.max() input_ids = tokenized_inputs["input_ids"] all_input_ids = tokenized_inputs["input_ids"].T.split(1, dim=1) top_n_tokens_tensor = torch.tensor( top_n_tokens, device=device, dtype=torch.int64 ) max_tokens = len(inputs) * (max_input_length + max_decode_tokens) return cls( batch_id=pb.id, requests=pb.requests, requests_idx_mapping=requests_idx_mapping, input_ids=input_ids, # past_input_ids=None, all_input_ids=list(all_input_ids), input_lengths=input_lengths.tolist(), prefix_offsets=prefix_offsets, read_offsets=read_offsets, next_token_choosers=next_token_choosers, stopping_criterias=stopping_criterias, top_n_tokens=top_n_tokens, top_n_tokens_tensor=top_n_tokens_tensor, max_input_length=max_input_length.item(), padding_right_offset=padding_right_offset, max_tokens=max_tokens, ) def filter(self, request_ids: List[int]) -> Optional["MambaBatch"]: if len(request_ids) == 0: raise ValueError("Batch must have at least one request") if len(request_ids) == len(self): return self keep_indices = [] # New values after filtering requests_idx_mapping = {} requests = [] input_lengths = [] prefix_offsets = [] read_offsets = [] all_input_ids = [] max_input_length = 0 next_token_choosers = [] stopping_criterias = [] top_n_tokens = [] total_remaining_decode_tokens = 0 new_padding_right_offset = 0 indices = [] for i, request_id in enumerate(request_ids): idx = self.requests_idx_mapping[request_id] requests_idx_mapping[request_id] = i keep_indices.append(idx) requests.append(self.requests[idx]) prefix_offsets.append(self.prefix_offsets[idx]) read_offsets.append(self.read_offsets[idx]) all_input_ids.append(self.all_input_ids[idx]) request_input_length = self.input_lengths[idx] input_lengths.append(request_input_length) max_input_length = max(max_input_length, request_input_length) indices.append(idx) next_token_choosers.append(self.next_token_choosers[idx]) stopping_criteria = self.stopping_criterias[idx] stopping_criterias.append(stopping_criteria) top_n_tokens.append(self.top_n_tokens[idx]) remaining_decode_tokens = ( stopping_criteria.max_new_tokens - stopping_criteria.current_tokens ) total_remaining_decode_tokens += remaining_decode_tokens new_padding_right_offset = max( new_padding_right_offset, remaining_decode_tokens ) # Apply indices to input_ids, attention mask, past key values and other items that need to be cached input_ids = self.input_ids[keep_indices] top_n_tokens_tensor = self.top_n_tokens_tensor[keep_indices] max_tokens = len(request_ids) * max_input_length + total_remaining_decode_tokens self.requests = requests self.requests_idx_mapping = requests_idx_mapping self.input_ids = input_ids self.all_input_ids = all_input_ids self.input_lengths = input_lengths self.prefix_offsets = prefix_offsets self.read_offsets = read_offsets self.next_token_choosers = next_token_choosers self.stopping_criterias = stopping_criterias self.top_n_tokens = top_n_tokens self.top_n_tokens_tensor = top_n_tokens_tensor self.max_input_length = max_input_length self.padding_right_offset = new_padding_right_offset self.max_tokens = max_tokens # TODO # Kept it simple by just updating the state, maybe updating the other CPU values is necessary. self.inference_params.conv_states = self.inference_params.conv_states[ :, indices ] self.inference_params.ssm_states = self.inference_params.ssm_states[:, indices] return self @classmethod def concatenate(cls, batches: List["MambaBatch"]) -> "MambaBatch": # Used for padding total_batch_size = 0 max_input_length = 0 padding_right_offset = 0 for batch in batches: total_batch_size += len(batch) max_input_length = max(max_input_length, batch.max_input_length) padding_right_offset = max(padding_right_offset, batch.padding_right_offset) # Batch attributes requests = [] requests_idx_mapping = {} input_lengths = [] prefix_offsets = [] read_offsets = [] all_input_ids = [] next_token_choosers = [] stopping_criterias = [] top_n_tokens = [] max_tokens = 0 seqlen_offset = 0 (n_blocks, _, d_inner, d_conv) = batches[0].inference_params.conv_states.shape (_, _, _, d_state) = batches[0].inference_params.ssm_states.shape dtype = batches[0].inference_params.conv_states.dtype device = batches[0].inference_params.conv_states.device inference_params = new_inference_params( n_blocks=n_blocks, batch_size=total_batch_size, d_state=d_state, d_conv=d_conv, d_inner=d_inner, seqlen_offset=seqlen_offset, device=device, dtype=dtype, ) # Batch tensors input_ids = None top_n_tokens_tensor = None # Used for slicing correctly inside the tensors # Equivalent to a cumsum on batch sizes start_index = 0 for i, batch in enumerate(batches): requests.extend(batch.requests) input_lengths.extend(batch.input_lengths) prefix_offsets.extend(batch.prefix_offsets) read_offsets.extend(batch.read_offsets) all_input_ids.extend(batch.all_input_ids) next_token_choosers.extend(batch.next_token_choosers) stopping_criterias.extend(batch.stopping_criterias) top_n_tokens.extend(batch.top_n_tokens) if i == 0: requests_idx_mapping = batch.requests_idx_mapping else: # We need to offset the mapping for each batch by the cumulative batch size for k, v in batch.requests_idx_mapping.items(): requests_idx_mapping[k] = v + start_index # Slicing end index for this batch end_index = start_index + len(batch) # Create empty tensor # input_ids is always of shape [batch_size, 1] # We do not need to pad it if input_ids is None: input_ids = batch.input_ids.new_empty((total_batch_size, 1)) # Copy to correct indices input_ids[start_index:end_index] = batch.input_ids if top_n_tokens_tensor is None: top_n_tokens_tensor = batches[0].top_n_tokens_tensor.new_zeros( total_batch_size, ) top_n_tokens_tensor[start_index:end_index] = batch.top_n_tokens_tensor # Add eventual padding tokens that were added while concatenating max_tokens += batch.max_tokens + ( max_input_length - batch.max_input_length ) * len(batch) inference_params.max_seqlen = max( inference_params.max_seqlen, batch.inference_params.max_seqlen ) assert batch.inference_params.seqlen_offset != 0, "Invalid seqlen offset" inference_params.seqlen_offset = max( inference_params.seqlen_offset, batch.inference_params.seqlen_offset ) inference_params.conv_states[:, start_index:end_index] = ( batch.inference_params.conv_states ) inference_params.ssm_states[:, start_index:end_index] = ( batch.inference_params.ssm_states ) start_index = end_index return cls( batch_id=batches[0].batch_id, requests=requests, requests_idx_mapping=requests_idx_mapping, input_ids=input_ids, all_input_ids=all_input_ids, input_lengths=input_lengths, prefix_offsets=prefix_offsets, read_offsets=read_offsets, next_token_choosers=next_token_choosers, stopping_criterias=stopping_criterias, top_n_tokens=top_n_tokens, top_n_tokens_tensor=top_n_tokens_tensor, max_input_length=max_input_length, padding_right_offset=padding_right_offset, keys_head_dim_last=batches[0].keys_head_dim_last, max_tokens=max_tokens, inference_params=inference_params, ) def __len__(self): return len(self.requests) class Mamba(Model): def __init__( self, model_id: str, revision: Optional[str] = None, quantize: Optional[str] = None, speculator: Optional[str] = None, dtype: Optional[torch.dtype] = None, trust_remote_code: bool = False, ): self.quantize = quantize self.process_group, _rank, world_size = initialize_torch_distributed() if world_size > 1: raise RuntimeError("Mamba does not support Tensor Parallelism (TP)") self.cuda_graphs = {} if torch.cuda.is_available(): device = torch.device("cuda") # Bf16 is important. In f16 accumulations in the matmul are causing # differences while the server is under load. # This is detectable by the integration load test dtype = torch.bfloat16 if dtype is None else dtype else: if quantize: raise ValueError("quantization is not available on CPU") device = torch.device("cpu") dtype = torch.float32 if dtype is None else dtype tokenizer = AutoTokenizer.from_pretrained( "EleutherAI/gpt-neox-20b", revision=revision, padding_side="left", truncation_side="left", trust_remote_code=trust_remote_code, ) config = MambaConfig.from_pretrained( model_id, revision=revision, trust_remote_code=trust_remote_code ) tokenizer.bos_token_id = config.bos_token_id tokenizer.eos_token_id = config.eos_token_id tokenizer.pad_token = tokenizer.eos_token config.quantize = quantize config.speculator = speculator torch.distributed.barrier(group=self.process_group) weights_loader = get_loader( quantize=quantize, model_id=model_id, revision=revision ) filenames = weight_files(model_id, revision=revision, extension=".safetensors") weights = Weights( filenames, device, dtype, process_group=self.process_group, weights_loader=weights_loader, ) model = MambaModel(config, weights) torch.distributed.barrier(group=self.process_group) super(Mamba, self).__init__( model_id=model_id, model=model, tokenizer=tokenizer, requires_padding=True, dtype=dtype, device=device, ) @property def batch_type(self) -> Type[MambaBatch]: return MambaBatch def warmup(self, batch) -> Optional[int]: # TODO: implement warmup for Mamba if needed if CUDA_GRAPHS: if self.speculate is None or self.speculate == 0: try: logger.info(f"Cuda Graphs are enabled for sizes {CUDA_GRAPHS}") # Warmup cuda graphs for bs in CUDA_GRAPHS: self.cuda_graph_warmup(bs) except Exception: logger.exception("Decode cuda graph warmup failed") else: logger.info(f"Cuda Graphs are disabled (CUDA_GRAPHS={CUDA_GRAPHS}).") return None def cuda_graph_warmup(self, batch_size: int): input_ids = torch.zeros((batch_size, 1), dtype=torch.int64, device=self.device) n_blocks = len(self.model.blocks) d_state = self.model.config.d_state d_conv = self.model.config.d_conv # Inner takes the expand multiplication d_inner = self.model.config.d_inner # Important seqlen_offset to go through the update mecanism with the state seqlen_offset = 1 inference_params = new_inference_params( n_blocks=n_blocks, batch_size=batch_size, d_state=d_state, d_conv=d_conv, d_inner=d_inner, seqlen_offset=seqlen_offset, device=self.device, dtype=self.dtype, ) graph = torch.cuda.CUDAGraph() torch.cuda.synchronize() # Run once outside to warmup self.model.forward(input_ids=input_ids, inference_params=inference_params) torch.cuda.synchronize() with torch.cuda.graph(graph, pool=MEM_POOL): logits, speculative_logits = self.model.forward( input_ids=input_ids, inference_params=inference_params ) torch.cuda.synchronize() graph_dict = { "input_ids": input_ids, "inference_params": inference_params, "graph": graph, "logits": logits, "speculative_logits": speculative_logits, } self.cuda_graphs[batch_size] = graph_dict def tunableop_warmup(self, batch_size: int, seqlen: int): input_ids = torch.zeros((batch_size, 1), dtype=torch.int64, device=self.device) n_blocks = len(self.model.blocks) d_state = self.model.config.d_state d_conv = self.model.config.d_conv # Inner takes the expand multiplication d_inner = self.model.config.d_inner # Important seqlen_offset to go through the update mecanism with the state seqlen_offset = 1 inference_params = new_inference_params( n_blocks=n_blocks, batch_size=seqlen, d_state=d_state, d_conv=d_conv, d_inner=d_inner, seqlen_offset=seqlen_offset, device=self.device, dtype=self.dtype, ) self.model.forward(input_ids=input_ids, inference_params=inference_params) def forward( self, input_ids: torch.Tensor, inference_params: Any ) -> Tuple[torch.Tensor, torch.Tensor]: bs = input_ids.shape[0] padded_bs = bs if bs == 3: padded_bs = 4 elif 3 < bs <= 8: padded_bs = 8 elif bs > 8: padded_bs = (bs + 7) // 8 * 8 # Try to find an associated cuda graph cuda_graph = self.cuda_graphs.get(padded_bs, None) is_prefill = inference_params is None or inference_params.seqlen_offset == 0 if is_prefill or cuda_graph is None: return self.model( input_ids, inference_params=inference_params, ) # Copy inputs to the static inputs of the cuda graph # Static inputs are potentially padded cuda_graph["input_ids"][:bs] = input_ids cuda_graph["inference_params"].conv_states[ :, :bs ] = inference_params.conv_states cuda_graph["inference_params"].ssm_states[:, :bs] = inference_params.ssm_states # Replay the graph cuda_graph["graph"].replay() inference_params.conv_states.copy_( cuda_graph["inference_params"].conv_states[:, :bs] ) inference_params.ssm_states.copy_( cuda_graph["inference_params"].ssm_states[:, :bs] ) # Slice output to the correct shape speculative_logits = ( cuda_graph["speculative_logits"][:bs] if cuda_graph["speculative_logits"] is not None else None ) logits = cuda_graph["logits"][:bs] return logits, speculative_logits def generate_token(self, batch) -> Tuple[List[Any], Optional[Any], Tuple[int, int]]: start = time.time_ns() input_ids = ( batch.input_ids ) # batch.past_input_ids if batch.past_input_ids is not None else batch.input_ids batch_size, max_seqlen = input_ids.shape # Inference params if batch.inference_params is None: # 0 is important here seqlen_offset = 0 n_blocks = len(self.model.blocks) d_state = self.model.config.d_state d_conv = self.model.config.d_conv d_inner = self.model.config.d_inner inference_params = new_inference_params( n_blocks=n_blocks, batch_size=batch_size, d_state=d_state, d_conv=d_conv, d_inner=d_inner, seqlen_offset=seqlen_offset, device=self.device, dtype=self.dtype, ) batch.inference_params = inference_params # Forward pass logits, speculative_logits = self.forward( input_ids, inference_params=batch.inference_params ) # batch.inference_params = new_inference_params # Results generations: List[Generation] = [] stopped = True # Speculation is not active for causal accepted_ids = torch.ones_like(batch.input_ids)[:, 0] batch_top_token_ids, batch_top_token_logprobs = batch_top_tokens( batch.top_n_tokens, batch.top_n_tokens_tensor, torch.log_softmax(logits[:, -1], -1), accepted_ids, ) start_decode = time.time_ns() # Zipped iterator iterator = zip( batch.requests, batch.input_lengths, batch.prefix_offsets, batch.read_offsets, logits, batch.next_token_choosers, batch.stopping_criterias, batch.all_input_ids, batch.top_n_tokens, batch_top_token_ids, batch_top_token_logprobs, ) # For each member of the batch for i, ( request, input_length, prefix_offset, read_offset, logits, next_token_chooser, stopping_criteria, all_input_ids, top_n_tokens, top_token_ids, top_token_logprobs, ) in enumerate(iterator): # Select next token next_token_id, logprobs = next_token_chooser( all_input_ids.view(1, -1), logits[-1:, :] ) # Append next token to all tokens all_input_ids = torch.cat([all_input_ids, next_token_id]) new_input_length = input_length + 1 # Generated token next_token_logprob = logprobs[-1, next_token_id] next_token_id_squeezed = next_token_id.squeeze() next_token_text, prefix_offset, read_offset = self.decode_token( all_input_ids[:, 0], prefix_offset, read_offset ) # Evaluate stopping criteria stop, reason = stopping_criteria( next_token_id_squeezed, next_token_text, ) if not stop: stopped = False # Shard generations # All generations will be appended in the rust sharded client if i % self.world_size == self.rank: if stop: # Decode generated tokens output_text, _, _ = self.decode_token( all_input_ids[:, 0], prefix_offset=len(all_input_ids) - stopping_criteria.current_tokens - 1, read_offset=len(all_input_ids) - stopping_criteria.current_tokens, skip_special_tokens=True, ) # Get seed if isinstance(next_token_chooser.choice, Sampling): seed = next_token_chooser.choice.seed else: seed = None generated_text = GeneratedText( output_text, stopping_criteria.current_tokens, reason, seed ) else: generated_text = None if stopping_criteria.current_tokens == 1 and request.prefill_logprobs: # Remove generated token to only have prefill and add nan for first prompt token prefill_logprobs = [float("nan")] + torch.log_softmax( logits, -1 ).gather(1, all_input_ids[1:]).squeeze(1)[ -new_input_length:-1 ].tolist() prefill_token_ids = all_input_ids[-new_input_length:-1] prefill_texts = self.tokenizer.batch_decode( prefill_token_ids, clean_up_tokenization_spaces=False, skip_special_tokens=False, ) prefill_tokens = Tokens( prefill_token_ids, prefill_logprobs, prefill_texts, is_special=[], ) else: prefill_tokens = None if top_n_tokens > 0: toptoken_texts = self.tokenizer.batch_decode( top_token_ids, clean_up_tokenization_spaces=False, skip_special_tokens=False, ) special_toptokens = [ token_id in self.all_special_ids for token_id in top_token_ids ] top_tokens = Tokens( top_token_ids, top_token_logprobs, toptoken_texts, special_toptokens, ) else: top_tokens = None generation = Generation( request.id, prefill_tokens, Tokens( [next_token_id_squeezed], [next_token_logprob], [next_token_text], [next_token_id_squeezed.item() in self.all_special_ids], ), generated_text, top_tokens, ) generations.append(generation) # Update values batch.next_token_choosers[i] = batch.next_token_choosers[ i ].advance_grammar(next_token_id_squeezed.item()) batch.input_ids[i, 0] = next_token_id batch.all_input_ids[i] = all_input_ids batch.input_lengths[i] = new_input_length batch.prefix_offsets[i] = prefix_offset batch.read_offsets[i] = read_offset batch.max_input_length = max(batch.max_input_length, new_input_length) # We finished all generations in the batch; there is no next batch if stopped: forward_ns = start_decode - start decode_ns = time.time_ns() - start_decode return generations, None, (forward_ns, decode_ns) # Slice unused values from prefill batch.input_ids = batch.input_ids[:, :1] forward_ns = start_decode - start decode_ns = time.time_ns() - start_decode return generations, batch, (forward_ns, decode_ns)
text-generation-inference/server/text_generation_server/models/mamba.py/0
{ "file_path": "text-generation-inference/server/text_generation_server/models/mamba.py", "repo_id": "text-generation-inference", "token_count": 14875 }
237
from functools import lru_cache from text_generation_server.utils.dist import RANK @lru_cache(10) def log_once(log, msg: str, master=True): if master: log_master(log, msg) else: log(msg) def log_master(log, msg: str): if RANK == 0: log(msg)
text-generation-inference/server/text_generation_server/utils/log.py/0
{ "file_path": "text-generation-inference/server/text_generation_server/utils/log.py", "repo_id": "text-generation-inference", "token_count": 126 }
238
[target.aarch64-unknown-linux-musl] linker = "aarch64-linux-musl-gcc" rustflags = ["-C", "target-feature=-crt-static"]
tokenizers/bindings/node/.cargo/config.toml/0
{ "file_path": "tokenizers/bindings/node/.cargo/config.toml", "repo_id": "tokenizers", "token_count": 50 }
239
/* tslint:disable */ /* eslint-disable */ /* auto-generated by NAPI-RS */ export function bpeDecoder(suffix?: string | undefined | null): Decoder export function byteFallbackDecoder(): Decoder export function ctcDecoder( padToken?: string = '<pad>', wordDelimiterToken?: string | undefined | null, cleanup?: boolean | undefined | null, ): Decoder export function fuseDecoder(): Decoder export function metaspaceDecoder( replacement?: string = '▁', prependScheme?: prepend_scheme = 'always', split?: split = true, ): Decoder export function replaceDecoder(pattern: string, content: string): Decoder export function sequenceDecoder(decoders: Array<Decoder>): Decoder export function stripDecoder(content: string, left: number, right: number): Decoder export function wordPieceDecoder(prefix?: string = '##', cleanup?: bool = true): Decoder export const enum TruncationDirection { Left = 'Left', Right = 'Right', } export const enum TruncationStrategy { LongestFirst = 'LongestFirst', OnlyFirst = 'OnlyFirst', OnlySecond = 'OnlySecond', } export interface BpeOptions { cacheCapacity?: number dropout?: number unkToken?: string continuingSubwordPrefix?: string endOfWordSuffix?: string fuseUnk?: boolean byteFallback?: boolean } export interface WordPieceOptions { unkToken?: string continuingSubwordPrefix?: string maxInputCharsPerWord?: number } export interface WordLevelOptions { unkToken?: string } export interface UnigramOptions { unkId?: number byteFallback?: boolean } export function prependNormalizer(prepend: string): Normalizer export function stripAccentsNormalizer(): Normalizer export interface BertNormalizerOptions { cleanText?: boolean handleChineseChars?: boolean stripAccents?: boolean lowercase?: boolean } /** * bert_normalizer(options?: { * cleanText?: bool = true, * handleChineseChars?: bool = true, * stripAccents?: bool = true, * lowercase?: bool = true * }) */ export function bertNormalizer(options?: BertNormalizerOptions | undefined | null): Normalizer export function nfdNormalizer(): Normalizer export function nfkdNormalizer(): Normalizer export function nfcNormalizer(): Normalizer export function nfkcNormalizer(): Normalizer export function stripNormalizer(left?: boolean | undefined | null, right?: boolean | undefined | null): Normalizer export function sequenceNormalizer(normalizers: Array<Normalizer>): Normalizer export function lowercase(): Normalizer export function replace(pattern: string, content: string): Normalizer export function nmt(): Normalizer export function precompiled(bytes: Array<number>): Normalizer export const enum JsSplitDelimiterBehavior { Removed = 'Removed', Isolated = 'Isolated', MergedWithPrevious = 'MergedWithPrevious', MergedWithNext = 'MergedWithNext', Contiguous = 'Contiguous', } /** byte_level(addPrefixSpace: bool = true, useRegex: bool = true) */ export function byteLevelPreTokenizer( addPrefixSpace?: boolean | undefined | null, useRegex?: boolean | undefined | null, ): PreTokenizer export function byteLevelAlphabet(): Array<string> export function whitespacePreTokenizer(): PreTokenizer export function whitespaceSplitPreTokenizer(): PreTokenizer export function bertPreTokenizer(): PreTokenizer export function metaspacePreTokenizer( replacement?: string = '▁', prependScheme?: prepend_scheme = 'always', split?: split = true, ): PreTokenizer export function splitPreTokenizer(pattern: string, behavior: string, invert?: boolean | undefined | null): PreTokenizer export function punctuationPreTokenizer(behavior?: string | undefined | null): PreTokenizer export function sequencePreTokenizer(preTokenizers: Array<PreTokenizer>): PreTokenizer export function charDelimiterSplit(delimiter: string): PreTokenizer export function digitsPreTokenizer(individualDigits?: boolean | undefined | null): PreTokenizer export function bertProcessing(sep: [string, number], cls: [string, number]): Processor export function robertaProcessing( sep: [string, number], cls: [string, number], trimOffsets?: boolean | undefined | null, addPrefixSpace?: boolean | undefined | null, ): Processor export function byteLevelProcessing(trimOffsets?: boolean | undefined | null): Processor export function templateProcessing( single: string, pair?: string | undefined | null, specialTokens?: Array<[string, number]> | undefined | null, ): Processor export function sequenceProcessing(processors: Array<Processor>): Processor export const enum PaddingDirection { Left = 0, Right = 1, } export interface PaddingOptions { maxLength?: number direction?: string | PaddingDirection padToMultipleOf?: number padId?: number padTypeId?: number padToken?: string } export interface EncodeOptions { isPretokenized?: boolean addSpecialTokens?: boolean } export interface TruncationOptions { maxLength?: number strategy?: TruncationStrategy direction?: string | TruncationDirection stride?: number } export interface AddedTokenOptions { singleWord?: boolean leftStrip?: boolean rightStrip?: boolean normalized?: boolean } export interface JsFromPretrainedParameters { revision?: string authToken?: string } export function slice(s: string, beginIndex?: number | undefined | null, endIndex?: number | undefined | null): string export function mergeEncodings(encodings: Array<Encoding>, growingOffsets?: boolean | undefined | null): Encoding /** Decoder */ export class Decoder { decode(tokens: Array<string>): string } export type JsEncoding = Encoding export class Encoding { constructor() getLength(): number getNSequences(): number getIds(): Array<number> getTypeIds(): Array<number> getAttentionMask(): Array<number> getSpecialTokensMask(): Array<number> getTokens(): Array<string> getOffsets(): Array<Array<number>> getWordIds(): Array<number | undefined | null> charToToken(pos: number, seqId?: number | undefined | null): number | null charToWord(pos: number, seqId?: number | undefined | null): number | null pad(length: number, options?: PaddingOptions | undefined | null): void truncate( length: number, stride?: number | undefined | null, direction?: string | TruncationDirection | undefined | null, ): void wordToTokens(word: number, seqId?: number | undefined | null): [number, number] | null | undefined wordToChars(word: number, seqId?: number | undefined | null): [number, number] | null | undefined tokenToChars(token: number): [number, [number, number]] | null | undefined tokenToWord(token: number): number | null getOverflowing(): Array<Encoding> getSequenceIds(): Array<number | undefined | null> tokenToSequence(token: number): number | null } export class Model {} export type Bpe = BPE export class BPE { static empty(): Model static init(vocab: Vocab, merges: Merges, options?: BpeOptions | undefined | null): Model static fromFile(vocab: string, merges: string, options?: BpeOptions | undefined | null): Promise<Model> } export class WordPiece { static init(vocab: Vocab, options?: WordPieceOptions | undefined | null): Model static empty(): WordPiece static fromFile(vocab: string, options?: WordPieceOptions | undefined | null): Promise<Model> } export class WordLevel { static init(vocab: Vocab, options?: WordLevelOptions | undefined | null): Model static empty(): WordLevel static fromFile(vocab: string, options?: WordLevelOptions | undefined | null): Promise<Model> } export class Unigram { static init(vocab: Array<[string, number]>, options?: UnigramOptions | undefined | null): Model static empty(): Model } /** Normalizer */ export class Normalizer { normalizeString(sequence: string): string } /** PreTokenizers */ export class PreTokenizer { preTokenizeString(sequence: string): [string, [number, number]][] } export class Processor {} export class AddedToken { constructor(token: string, isSpecial: boolean, options?: AddedTokenOptions | undefined | null) getContent(): string } export class Tokenizer { constructor(model: Model) setPreTokenizer(preTokenizer: PreTokenizer): void setDecoder(decoder: Decoder): void setModel(model: Model): void setPostProcessor(postProcessor: Processor): void setNormalizer(normalizer: Normalizer): void save(path: string, pretty?: boolean | undefined | null): void addAddedTokens(tokens: Array<AddedToken>): number addTokens(tokens: Array<string>): number encode( sentence: InputSequence, pair?: InputSequence | null, encodeOptions?: EncodeOptions | undefined | null, ): Promise<JsEncoding> encodeBatch(sentences: EncodeInput[], encodeOptions?: EncodeOptions | undefined | null): Promise<JsEncoding[]> decode(ids: Array<number>, skipSpecialTokens: boolean): Promise<string> decodeBatch(ids: Array<Array<number>>, skipSpecialTokens: boolean): Promise<string[]> static fromString(s: string): Tokenizer static fromFile(file: string): Tokenizer addSpecialTokens(tokens: Array<string>): void setTruncation(maxLength: number, options?: TruncationOptions | undefined | null): void disableTruncation(): void setPadding(options?: PaddingOptions | undefined | null): void disablePadding(): void getDecoder(): Decoder | null getNormalizer(): Normalizer | null getPreTokenizer(): PreTokenizer | null getPostProcessor(): Processor | null getVocab(withAddedTokens?: boolean | undefined | null): Record<string, number> getVocabSize(withAddedTokens?: boolean | undefined | null): number idToToken(id: number): string | null tokenToId(token: string): number | null train(files: Array<string>): void runningTasks(): number postProcess( encoding: Encoding, pair?: Encoding | undefined | null, addSpecialTokens?: boolean | undefined | null, ): Encoding } export class Trainer {}
tokenizers/bindings/node/index.d.ts/0
{ "file_path": "tokenizers/bindings/node/index.d.ts", "repo_id": "tokenizers", "token_count": 2753 }
240
# `tokenizers-android-arm64` This is the **aarch64-linux-android** binary for `tokenizers`
tokenizers/bindings/node/npm/android-arm64/README.md/0
{ "file_path": "tokenizers/bindings/node/npm/android-arm64/README.md", "repo_id": "tokenizers", "token_count": 31 }
241
# `tokenizers-linux-x64-musl` This is the **x86_64-unknown-linux-musl** binary for `tokenizers`
tokenizers/bindings/node/npm/linux-x64-musl/README.md/0
{ "file_path": "tokenizers/bindings/node/npm/linux-x64-musl/README.md", "repo_id": "tokenizers", "token_count": 38 }
242
use crate::arc_rwlock_serde; use napi::bindgen_prelude::*; use napi_derive::napi; use serde::{Deserialize, Serialize}; use std::sync::{Arc, RwLock}; use tk::pre_tokenizers::PreTokenizerWrapper; use tk::PreTokenizedString; use tk::SplitDelimiterBehavior; use tokenizers as tk; #[napi(string_enum)] pub enum JsSplitDelimiterBehavior { Removed, Isolated, MergedWithPrevious, MergedWithNext, Contiguous, } impl TryFrom<String> for JsSplitDelimiterBehavior { type Error = Error; fn try_from(value: String) -> Result<Self> { match &value[..] { "removed" => Ok(JsSplitDelimiterBehavior::Removed), "isolated" => Ok(JsSplitDelimiterBehavior::Isolated), "mergedWithPrevious" => Ok(JsSplitDelimiterBehavior::MergedWithPrevious), "mergedWithNext" => Ok(JsSplitDelimiterBehavior::MergedWithNext), "contiguous" => Ok(JsSplitDelimiterBehavior::Contiguous), _ => Err(Error::from_reason( "Wrong value for SplitDelimiterBehavior, expected one of: \ `removed, isolated, mergedWithPrevious, mergedWithNext, contiguous`" .to_string(), )), } } } impl From<JsSplitDelimiterBehavior> for SplitDelimiterBehavior { fn from(value: JsSplitDelimiterBehavior) -> Self { match value { JsSplitDelimiterBehavior::Removed => SplitDelimiterBehavior::Removed, JsSplitDelimiterBehavior::Isolated => SplitDelimiterBehavior::Isolated, JsSplitDelimiterBehavior::MergedWithPrevious => SplitDelimiterBehavior::MergedWithPrevious, JsSplitDelimiterBehavior::MergedWithNext => SplitDelimiterBehavior::MergedWithNext, JsSplitDelimiterBehavior::Contiguous => SplitDelimiterBehavior::Contiguous, } } } /// PreTokenizers #[derive(Clone, Debug, Serialize, Deserialize)] #[napi] pub struct PreTokenizer { #[serde(flatten, with = "arc_rwlock_serde")] pretok: Option<Arc<RwLock<PreTokenizerWrapper>>>, } impl tk::PreTokenizer for PreTokenizer { fn pre_tokenize(&self, pretokenized: &mut PreTokenizedString) -> tk::Result<()> { self .pretok .as_ref() .ok_or("Uninitialized PreTokenizer")? .read() .unwrap() .pre_tokenize(pretokenized)?; Ok(()) } } #[napi] impl PreTokenizer { #[napi(ts_return_type = "[string, [number, number]][]")] pub fn pre_tokenize_string(&self, sequence: String, env: Env) -> Result<Vec<Array>> { use tk::PreTokenizer; let mut pretokenized = PreTokenizedString::from(sequence); self .pre_tokenize(&mut pretokenized) .map_err(|e| Error::from_reason(format!("{}", e)))?; pretokenized .get_splits(tk::OffsetReferential::Original, tk::OffsetType::Char) .into_iter() .map(|(s, (start, end), _)| -> Result<Array> { let mut arr = env.create_array(2)?; let mut offset = env.create_array(2)?; offset.set(0, env.create_uint32(start as u32)?)?; offset.set(1, env.create_uint32(end as u32)?)?; arr.set(0, env.create_string(s)?)?; arr.set(1, offset)?; Ok(arr) }) .collect::<Result<Vec<_>>>() } } /// byte_level(addPrefixSpace: bool = true, useRegex: bool = true) #[napi] pub fn byte_level_pre_tokenizer( add_prefix_space: Option<bool>, use_regex: Option<bool>, ) -> PreTokenizer { let mut byte_level = tk::pre_tokenizers::byte_level::ByteLevel::default(); if let Some(add_prefix_space) = add_prefix_space { byte_level = byte_level.add_prefix_space(add_prefix_space); } if let Some(use_regex) = use_regex { byte_level = byte_level.use_regex(use_regex); } PreTokenizer { pretok: Some(Arc::new(RwLock::new(byte_level.into()))), } } #[napi] pub fn byte_level_alphabet() -> Vec<String> { tk::pre_tokenizers::byte_level::ByteLevel::alphabet() .into_iter() .map(|c| c.to_string()) .collect::<Vec<_>>() } #[napi] pub fn whitespace_pre_tokenizer() -> PreTokenizer { PreTokenizer { pretok: Some(Arc::new(RwLock::new( tk::pre_tokenizers::whitespace::Whitespace.into(), ))), } } #[napi] pub fn whitespace_split_pre_tokenizer() -> PreTokenizer { PreTokenizer { pretok: Some(Arc::new(RwLock::new( tk::pre_tokenizers::whitespace::WhitespaceSplit.into(), ))), } } #[napi] pub fn bert_pre_tokenizer() -> PreTokenizer { PreTokenizer { pretok: Some(Arc::new(RwLock::new( tk::pre_tokenizers::bert::BertPreTokenizer.into(), ))), } } #[napi] pub fn metaspace_pre_tokenizer( #[napi(ts_arg_type = "string = '▁'")] replacement: Option<String>, #[napi(ts_arg_type = "prepend_scheme = 'always'")] prepend_scheme: Option<String>, #[napi(ts_arg_type = "split = true")] split: Option<bool>, ) -> Result<PreTokenizer> { use tk::pre_tokenizers::metaspace::PrependScheme; let split = split.unwrap_or(true); let replacement = replacement.unwrap_or("▁".to_string()); if replacement.chars().count() != 1 { return Err(Error::from_reason( "replacement is supposed to be a single char", )); } let replacement = replacement.chars().next().unwrap(); let prepend_scheme: PrependScheme = match prepend_scheme.unwrap_or(String::from("always")).as_str() { "always" => PrependScheme::Always, "first" => PrependScheme::First, "never" => PrependScheme::Never, _ => { return Err(Error::from_reason( "prepend_scheme is supposed to be either 'always', 'first' or 'never'", )); } }; Ok(PreTokenizer { pretok: Some(Arc::new(RwLock::new( tk::pre_tokenizers::metaspace::Metaspace::new(replacement, prepend_scheme, split).into(), ))), }) } #[napi] pub fn split_pre_tokenizer( pattern: String, behavior: String, invert: Option<bool>, ) -> Result<PreTokenizer> { let behavior: JsSplitDelimiterBehavior = behavior.try_into()?; let invert = invert.unwrap_or(false); Ok(PreTokenizer { pretok: Some(Arc::new(RwLock::new( tk::pre_tokenizers::split::Split::new(pattern, behavior.into(), invert) .map_err(|e| Error::from_reason(e.to_string()))? .into(), ))), }) } #[napi] pub fn punctuation_pre_tokenizer(behavior: Option<String>) -> Result<PreTokenizer> { let behavior = match behavior { Some(behavior) => behavior.try_into()?, None => JsSplitDelimiterBehavior::Isolated, }; Ok(PreTokenizer { pretok: Some(Arc::new(RwLock::new( tk::pre_tokenizers::punctuation::Punctuation::new(behavior.into()).into(), ))), }) } #[napi] pub fn sequence_pre_tokenizer(pre_tokenizers: Vec<&PreTokenizer>) -> PreTokenizer { let mut sequence: Vec<PreTokenizerWrapper> = Vec::with_capacity(pre_tokenizers.len()); pre_tokenizers.into_iter().for_each(|pre_tokenizer| { if let Some(pre_tokenizer) = &pre_tokenizer.pretok { sequence.push((**pre_tokenizer).read().unwrap().clone()) } }); PreTokenizer { pretok: Some(Arc::new(RwLock::new(PreTokenizerWrapper::Sequence( tk::pre_tokenizers::sequence::Sequence::new(sequence), )))), } } #[napi] pub fn char_delimiter_split(delimiter: String) -> Result<PreTokenizer> { if delimiter.chars().count() != 1 { return Err(Error::from_reason( "delimiter is supposed to be a single char", )); } let delimiter = delimiter.chars().next().unwrap(); Ok(PreTokenizer { pretok: Some(Arc::new(RwLock::new( tk::pre_tokenizers::delimiter::CharDelimiterSplit::new(delimiter).into(), ))), }) } #[napi] pub fn digits_pre_tokenizer(individual_digits: Option<bool>) -> PreTokenizer { let individual_digits = individual_digits.unwrap_or(false); PreTokenizer { pretok: Some(Arc::new(RwLock::new( tk::pre_tokenizers::digits::Digits::new(individual_digits).into(), ))), } }
tokenizers/bindings/node/src/pre_tokenizers.rs/0
{ "file_path": "tokenizers/bindings/node/src/pre_tokenizers.rs", "repo_id": "tokenizers", "token_count": 3152 }
243
.PHONY: style check-style test DATA_DIR = data dir_guard=@mkdir -p $(@D) check_dirs := examples py_src/tokenizers tests # Format source code automatically style: python stub.py ruff check $(check_dirs) --fix ruff format $(check_dirs) # Check the source code is formatted correctly check-style: python stub.py --check ruff check examples py_src/tokenizers tests ruff format --check examples py_src/tokenizers tests TESTS_RESOURCES = $(DATA_DIR)/small.txt $(DATA_DIR)/roberta.json # Launch the test suite test: $(TESTS_RESOURCES) pip install pytest requests setuptools_rust numpy pyarrow datasets python -m pytest -s -v tests cargo test --no-default-features $(DATA_DIR)/big.txt : $(dir_guard) wget https://norvig.com/big.txt -O $@ $(DATA_DIR)/small.txt : $(DATA_DIR)/big.txt head -100 $(DATA_DIR)/big.txt > $@ $(DATA_DIR)/roberta.json : $(dir_guard) wget https://huggingface.co/roberta-large/raw/main/tokenizer.json -O $@
tokenizers/bindings/python/Makefile/0
{ "file_path": "tokenizers/bindings/python/Makefile", "repo_id": "tokenizers", "token_count": 355 }
244
from typing import Dict, Iterator, List, Optional, Union from tokenizers import AddedToken, Tokenizer, decoders, trainers from tokenizers.models import WordPiece from tokenizers.normalizers import BertNormalizer from tokenizers.pre_tokenizers import BertPreTokenizer from tokenizers.processors import BertProcessing from .base_tokenizer import BaseTokenizer class BertWordPieceTokenizer(BaseTokenizer): """Bert WordPiece Tokenizer""" def __init__( self, vocab: Optional[Union[str, Dict[str, int]]] = None, unk_token: Union[str, AddedToken] = "[UNK]", sep_token: Union[str, AddedToken] = "[SEP]", cls_token: Union[str, AddedToken] = "[CLS]", pad_token: Union[str, AddedToken] = "[PAD]", mask_token: Union[str, AddedToken] = "[MASK]", clean_text: bool = True, handle_chinese_chars: bool = True, strip_accents: Optional[bool] = None, lowercase: bool = True, wordpieces_prefix: str = "##", ): if vocab is not None: tokenizer = Tokenizer(WordPiece(vocab, unk_token=str(unk_token))) else: tokenizer = Tokenizer(WordPiece(unk_token=str(unk_token))) # Let the tokenizer know about special tokens if they are part of the vocab if tokenizer.token_to_id(str(unk_token)) is not None: tokenizer.add_special_tokens([str(unk_token)]) if tokenizer.token_to_id(str(sep_token)) is not None: tokenizer.add_special_tokens([str(sep_token)]) if tokenizer.token_to_id(str(cls_token)) is not None: tokenizer.add_special_tokens([str(cls_token)]) if tokenizer.token_to_id(str(pad_token)) is not None: tokenizer.add_special_tokens([str(pad_token)]) if tokenizer.token_to_id(str(mask_token)) is not None: tokenizer.add_special_tokens([str(mask_token)]) tokenizer.normalizer = BertNormalizer( clean_text=clean_text, handle_chinese_chars=handle_chinese_chars, strip_accents=strip_accents, lowercase=lowercase, ) tokenizer.pre_tokenizer = BertPreTokenizer() if vocab is not None: sep_token_id = tokenizer.token_to_id(str(sep_token)) if sep_token_id is None: raise TypeError("sep_token not found in the vocabulary") cls_token_id = tokenizer.token_to_id(str(cls_token)) if cls_token_id is None: raise TypeError("cls_token not found in the vocabulary") tokenizer.post_processor = BertProcessing((str(sep_token), sep_token_id), (str(cls_token), cls_token_id)) tokenizer.decoder = decoders.WordPiece(prefix=wordpieces_prefix) parameters = { "model": "BertWordPiece", "unk_token": unk_token, "sep_token": sep_token, "cls_token": cls_token, "pad_token": pad_token, "mask_token": mask_token, "clean_text": clean_text, "handle_chinese_chars": handle_chinese_chars, "strip_accents": strip_accents, "lowercase": lowercase, "wordpieces_prefix": wordpieces_prefix, } super().__init__(tokenizer, parameters) @staticmethod def from_file(vocab: str, **kwargs): vocab = WordPiece.read_file(vocab) return BertWordPieceTokenizer(vocab, **kwargs) def train( self, files: Union[str, List[str]], vocab_size: int = 30000, min_frequency: int = 2, limit_alphabet: int = 1000, initial_alphabet: List[str] = [], special_tokens: List[Union[str, AddedToken]] = [ "[PAD]", "[UNK]", "[CLS]", "[SEP]", "[MASK]", ], show_progress: bool = True, wordpieces_prefix: str = "##", ): """Train the model using the given files""" trainer = trainers.WordPieceTrainer( vocab_size=vocab_size, min_frequency=min_frequency, limit_alphabet=limit_alphabet, initial_alphabet=initial_alphabet, special_tokens=special_tokens, show_progress=show_progress, continuing_subword_prefix=wordpieces_prefix, ) if isinstance(files, str): files = [files] self._tokenizer.train(files, trainer=trainer) def train_from_iterator( self, iterator: Union[Iterator[str], Iterator[Iterator[str]]], vocab_size: int = 30000, min_frequency: int = 2, limit_alphabet: int = 1000, initial_alphabet: List[str] = [], special_tokens: List[Union[str, AddedToken]] = [ "[PAD]", "[UNK]", "[CLS]", "[SEP]", "[MASK]", ], show_progress: bool = True, wordpieces_prefix: str = "##", length: Optional[int] = None, ): """Train the model using the given iterator""" trainer = trainers.WordPieceTrainer( vocab_size=vocab_size, min_frequency=min_frequency, limit_alphabet=limit_alphabet, initial_alphabet=initial_alphabet, special_tokens=special_tokens, show_progress=show_progress, continuing_subword_prefix=wordpieces_prefix, ) self._tokenizer.train_from_iterator( iterator, trainer=trainer, length=length, )
tokenizers/bindings/python/py_src/tokenizers/implementations/bert_wordpiece.py/0
{ "file_path": "tokenizers/bindings/python/py_src/tokenizers/implementations/bert_wordpiece.py", "repo_id": "tokenizers", "token_count": 2637 }
245
# Generated content DO NOT EDIT from .. import trainers Trainer = trainers.Trainer BpeTrainer = trainers.BpeTrainer UnigramTrainer = trainers.UnigramTrainer WordLevelTrainer = trainers.WordLevelTrainer WordPieceTrainer = trainers.WordPieceTrainer
tokenizers/bindings/python/py_src/tokenizers/trainers/__init__.py/0
{ "file_path": "tokenizers/bindings/python/py_src/tokenizers/trainers/__init__.py", "repo_id": "tokenizers", "token_count": 74 }
246
use pyo3::prelude::*; use tk::Token; #[pyclass(module = "tokenizers", name = "Token")] #[derive(Clone)] pub struct PyToken { token: Token, } impl From<Token> for PyToken { fn from(token: Token) -> Self { Self { token } } } impl From<PyToken> for Token { fn from(token: PyToken) -> Self { token.token } } #[pymethods] impl PyToken { #[new] #[pyo3(text_signature = None)] fn new(id: u32, value: String, offsets: (usize, usize)) -> PyToken { Token::new(id, value, offsets).into() } #[getter] fn get_id(&self) -> u32 { self.token.id } #[getter] fn get_value(&self) -> &str { &self.token.value } #[getter] fn get_offsets(&self) -> (usize, usize) { self.token.offsets } fn as_tuple(&self) -> (u32, &str, (usize, usize)) { (self.token.id, &self.token.value, self.token.offsets) } }
tokenizers/bindings/python/src/token.rs/0
{ "file_path": "tokenizers/bindings/python/src/token.rs", "repo_id": "tokenizers", "token_count": 439 }
247
import pickle import pytest from tokenizers import NormalizedString from tokenizers.normalizers import BertNormalizer, Lowercase, Normalizer, Sequence, Strip, Prepend class TestBertNormalizer: def test_instantiate(self): assert isinstance(BertNormalizer(), Normalizer) assert isinstance(BertNormalizer(), BertNormalizer) assert isinstance(pickle.loads(pickle.dumps(BertNormalizer())), BertNormalizer) def test_strip_accents(self): normalizer = BertNormalizer(strip_accents=True, lowercase=False, handle_chinese_chars=False, clean_text=False) output = normalizer.normalize_str("Héllò") assert output == "Hello" def test_handle_chinese_chars(self): normalizer = BertNormalizer(strip_accents=False, lowercase=False, handle_chinese_chars=True, clean_text=False) output = normalizer.normalize_str("你好") assert output == " 你 好 " def test_clean_text(self): normalizer = BertNormalizer(strip_accents=False, lowercase=False, handle_chinese_chars=False, clean_text=True) output = normalizer.normalize_str("\ufeffHello") assert output == "Hello" def test_lowercase(self): normalizer = BertNormalizer(strip_accents=False, lowercase=True, handle_chinese_chars=False, clean_text=False) output = normalizer.normalize_str("Héllò") assert output == "héllò" def test_can_modify(self): normalizer = BertNormalizer(clean_text=True, handle_chinese_chars=True, strip_accents=True, lowercase=True) assert normalizer.clean_text == True assert normalizer.handle_chinese_chars == True assert normalizer.strip_accents == True assert normalizer.lowercase == True # Modify these normalizer.clean_text = False assert normalizer.clean_text == False normalizer.handle_chinese_chars = False assert normalizer.handle_chinese_chars == False normalizer.strip_accents = None assert normalizer.strip_accents == None normalizer.lowercase = False assert normalizer.lowercase == False class TestSequence: def test_instantiate(self): assert isinstance(Sequence([]), Normalizer) assert isinstance(Sequence([]), Sequence) assert isinstance(pickle.loads(pickle.dumps(Sequence([]))), Sequence) def test_can_make_sequences(self): normalizer = Sequence([Lowercase(), Strip()]) output = normalizer.normalize_str(" HELLO ") assert output == "hello" def test_items(self): normalizers = Sequence([BertNormalizer(True, True), Prepend(), Strip()]) assert normalizers[1].__class__ == Prepend normalizers[0].lowercase = False assert not normalizers[0].lowercase assert normalizers[2].__class__ == Strip with pytest.raises(IndexError): print(normalizers[3]) class TestLowercase: def test_instantiate(self): assert isinstance(Lowercase(), Normalizer) assert isinstance(Lowercase(), Lowercase) assert isinstance(pickle.loads(pickle.dumps(Lowercase())), Lowercase) def test_lowercase(self): normalizer = Lowercase() output = normalizer.normalize_str("HELLO") assert output == "hello" class TestStrip: def test_instantiate(self): assert isinstance(Strip(), Normalizer) assert isinstance(Strip(), Strip) assert isinstance(pickle.loads(pickle.dumps(Strip())), Strip) def test_left_strip(self): normalizer = Strip(left=True, right=False) output = normalizer.normalize_str(" hello ") assert output == "hello " def test_right_strip(self): normalizer = Strip(left=False, right=True) output = normalizer.normalize_str(" hello ") assert output == " hello" def test_full_strip(self): normalizer = Strip(left=True, right=True) output = normalizer.normalize_str(" hello ") assert output == "hello" def test_can_modify(self): normalizer = Strip(left=True, right=True) assert normalizer.left == True assert normalizer.right == True # Modify these normalizer.left = False assert normalizer.left == False normalizer.right = False assert normalizer.right == False class TestPrepend: def test_instantiate(self): assert isinstance(Prepend("▁"), Normalizer) assert isinstance(Prepend("▁"), Prepend) assert isinstance(pickle.loads(pickle.dumps(Prepend("▁"))), Prepend) def test_prepend(self): normalizer = Prepend(prepend="▁") output = normalizer.normalize_str("hello") assert output == "▁hello" def test_can_modify(self): normalizer = Prepend("▁") assert normalizer.prepend == "▁" # Modify these normalizer.prepend = "-" assert normalizer.prepend == "-" class TestCustomNormalizer: class BadCustomNormalizer: def normalize(self, normalized, wrong): pass class GoodCustomNormalizer: def normalize(self, normalized): self.kept_normalized = normalized normalized.replace("there", "you") def use_after_normalize(self): self.kept_normalized.replace("something", "else") def test_instantiate(self): bad = Normalizer.custom(TestCustomNormalizer.BadCustomNormalizer()) good_custom = TestCustomNormalizer.GoodCustomNormalizer() good = Normalizer.custom(good_custom) assert isinstance(bad, Normalizer) assert isinstance(good, Normalizer) with pytest.raises(Exception, match="TypeError:.*normalize()"): bad.normalize_str("Hey there!") assert good.normalize_str("Hey there!") == "Hey you!" with pytest.raises(Exception, match="Cannot use a NormalizedStringRefMut outside `normalize`"): good_custom.use_after_normalize() def test_normalizer_interface(self): normalizer = Normalizer.custom(TestCustomNormalizer.GoodCustomNormalizer()) normalized = NormalizedString("Hey there!") normalizer.normalize(normalized) assert repr(normalized) == 'NormalizedString(original="Hey there!", normalized="Hey you!")' assert str(normalized) == "Hey you!"
tokenizers/bindings/python/tests/bindings/test_normalizers.py/0
{ "file_path": "tokenizers/bindings/python/tests/bindings/test_normalizers.py", "repo_id": "tokenizers", "token_count": 2491 }
248
import multiprocessing as mp import os import pytest import requests DATA_PATH = os.path.join("tests", "data") def download(url, with_filename=None): filename = with_filename if with_filename is not None else url.rsplit("/")[-1] filepath = os.path.join(DATA_PATH, filename) if not os.path.exists(filepath): with open(filepath, "wb") as f: response = requests.get(url, stream=True) response.raise_for_status() for chunk in response.iter_content(1024): f.write(chunk) return filepath @pytest.fixture(scope="session") def data_dir(): assert os.getcwd().endswith("python") exist = os.path.exists(DATA_PATH) and os.path.isdir(DATA_PATH) if not exist: os.mkdir(DATA_PATH) @pytest.fixture(scope="session") def roberta_files(data_dir): return { "vocab": download("https://s3.amazonaws.com/models.huggingface.co/bert/roberta-base-vocab.json"), "merges": download("https://s3.amazonaws.com/models.huggingface.co/bert/roberta-base-merges.txt"), } @pytest.fixture(scope="session") def bert_files(data_dir): return { "vocab": download("https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-vocab.txt"), } @pytest.fixture(scope="session") def openai_files(data_dir): return { "vocab": download("https://s3.amazonaws.com/models.huggingface.co/bert/openai-gpt-vocab.json"), "merges": download("https://s3.amazonaws.com/models.huggingface.co/bert/openai-gpt-merges.txt"), } @pytest.fixture(scope="session") def train_files(data_dir): big = download("https://norvig.com/big.txt") small = os.path.join(DATA_PATH, "small.txt") with open(small, "w") as f: with open(big, "r") as g: for i, line in enumerate(g): f.write(line) if i > 100: break return { "small": small, "big": big, } @pytest.fixture(scope="session") def albert_base(data_dir): return download("https://s3.amazonaws.com/models.huggingface.co/bert/albert-base-v1-tokenizer.json") @pytest.fixture(scope="session") def doc_wiki_tokenizer(data_dir): return download( "https://s3.amazonaws.com/models.huggingface.co/bert/anthony/doc-quicktour/tokenizer.json", "tokenizer-wiki.json", ) @pytest.fixture(scope="session") def doc_pipeline_bert_tokenizer(data_dir): return download( "https://s3.amazonaws.com/models.huggingface.co/bert/anthony/doc-pipeline/tokenizer.json", "bert-wiki.json", ) # On MacOS Python 3.8+ the default was modified to `spawn`, we need `fork` in tests. mp.set_start_method("fork") def multiprocessing_with_parallelism(tokenizer, enabled: bool): """ This helper can be used to test that disabling parallelism avoids dead locks when the same tokenizer is used after forking. """ # It's essential to this test that we call 'encode' or 'encode_batch' # before the fork. This causes the main process to "lock" some resources # provided by the Rust "rayon" crate that are needed for parallel processing. tokenizer.encode("Hi") tokenizer.encode_batch(["hi", "there"]) def encode(tokenizer): tokenizer.encode("Hi") tokenizer.encode_batch(["hi", "there"]) # Make sure this environment variable is set before the fork happens os.environ["TOKENIZERS_PARALLELISM"] = str(enabled) p = mp.Process(target=encode, args=(tokenizer,)) p.start() p.join(timeout=1) # At this point the process should have successfully exited, depending on whether parallelism # was activated or not. So we check the status and kill it if needed alive = p.is_alive() if alive: p.terminate() assert (alive and mp.get_start_method() == "fork") == enabled
tokenizers/bindings/python/tests/utils.py/0
{ "file_path": "tokenizers/bindings/python/tests/utils.py", "repo_id": "tokenizers", "token_count": 1569 }
249
Documentation ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The node API has not been documented yet.
tokenizers/docs/source/api/node.inc/0
{ "file_path": "tokenizers/docs/source/api/node.inc", "repo_id": "tokenizers", "token_count": 22 }
250
[package] authors = ["Anthony MOI <m.anthony.moi@gmail.com>", "Nicolas Patry <patry.nicolas@protonmail.com>"] edition = "2018" name = "tokenizers" version = "0.20.0-dev.0" homepage = "https://github.com/huggingface/tokenizers" repository = "https://github.com/huggingface/tokenizers" documentation = "https://docs.rs/tokenizers/" license = "Apache-2.0" keywords = ["tokenizer", "NLP", "huggingface", "BPE", "WordPiece"] readme = "./README.md" description = """ Provides an implementation of today's most used tokenizers, with a focus on performances and versatility. """ exclude = [ "rust-toolchain", "target/*", "Cargo.lock", "benches/*.txt", "benches/*.json", "data/*" ] [lib] name = "tokenizers" path = "src/lib.rs" bench = false [[bench]] name = "bpe_benchmark" harness = false [[bench]] name = "bert_benchmark" harness = false [[bench]] name = "layout_benchmark" harness = false [[bench]] name = "unigram_benchmark" harness = false [[bench]] name = "llama3" required-features = ["http"] harness = false [dependencies] lazy_static = "1.4" rand = "0.8" onig = { version = "6.4", default-features = false, optional = true } regex = "1.10" regex-syntax = "0.8" rayon = "1.10" rayon-cond = "0.3" serde = { version = "1.0", features = [ "derive" ] } serde_json = "1.0" unicode-normalization-alignments = "0.1" unicode_categories = "0.1" unicode-segmentation = "1.11" indicatif = {version = "0.17", optional = true} itertools = "0.12" log = "0.4" derive_builder = "0.20" spm_precompiled = "0.1.3" hf-hub = { version = "0.3.2", optional = true } aho-corasick = "1.1" paste = "1.0.14" macro_rules_attribute = "0.2.0" thiserror = "1.0.49" fancy-regex = { version = "0.13", optional = true} getrandom = { version = "0.2.10" } esaxx-rs = { version = "0.1.10", default-features = false, features=[]} monostate = "0.1.12" [features] default = ["progressbar", "onig", "esaxx_fast"] esaxx_fast = ["esaxx-rs/cpp"] progressbar = ["indicatif"] http = ["hf-hub"] unstable_wasm = ["fancy-regex", "getrandom/js"] [dev-dependencies] criterion = "0.5" tempfile = "3.10" assert_approx_eq = "1.1" tracing = "0.1" tracing-subscriber = "0.3.18" [profile.release] lto = "fat" [[example]] name = "encode_batch" required-features = ["http"]
tokenizers/tokenizers/Cargo.toml/0
{ "file_path": "tokenizers/tokenizers/Cargo.toml", "repo_id": "tokenizers", "token_count": 912 }
251
mod utils; use tokenizers::models::bpe::{Vocab, BPE}; use tokenizers::Tokenizer; use wasm_bindgen::prelude::*; // When the `wee_alloc` feature is enabled, use `wee_alloc` as the global // allocator. #[cfg(feature = "wee_alloc")] #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; #[wasm_bindgen] pub fn tokenize(string: &str) -> Vec<u32> { let vocab: Vocab = vec![ ("a".to_string(), 0), ("##b".to_string(), 1), ("##c".to_string(), 2), ("ab".to_string(), 3), ("abc".to_string(), 4), ] .into_iter() .collect(); let merges = vec![ ("a".to_string(), "##b".to_string()), ("ab".to_string(), "##c".to_string()), ]; let bpe = BPE::builder() .vocab_and_merges(vocab, merges) .unk_token("[UNK]".to_string()) .continuing_subword_prefix("##".to_string()) .build() .unwrap(); let tokenizer = Tokenizer::new(bpe); tokenizer .encode(string, false) .unwrap() .get_ids() .into_iter() .cloned() .collect() }
tokenizers/tokenizers/examples/unstable_wasm/src/lib.rs/0
{ "file_path": "tokenizers/tokenizers/examples/unstable_wasm/src/lib.rs", "repo_id": "tokenizers", "token_count": 543 }
252
use crate::tokenizer::{Decoder, Result}; use serde::{Deserialize, Serialize}; #[derive(Deserialize, Clone, Debug, Serialize)] /// Allows decoding Original BPE by joining all the tokens and then replacing /// the suffix used to identify end-of-words by whitespaces #[serde(tag = "type")] #[non_exhaustive] pub struct BPEDecoder { pub suffix: String, } impl BPEDecoder { pub fn new(suffix: String) -> Self { Self { suffix } } } impl Default for BPEDecoder { fn default() -> Self { Self::new("</w>".into()) } } impl Decoder for BPEDecoder { fn decode_chain(&self, tokens: Vec<String>) -> Result<Vec<String>> { let n = tokens.len() - 1; Ok(tokens .into_iter() .enumerate() .map(|(i, token)| { let replacement = if i == n { "" } else { " " }; token.replace(&self.suffix, replacement) }) .collect()) } }
tokenizers/tokenizers/src/decoders/bpe.rs/0
{ "file_path": "tokenizers/tokenizers/src/decoders/bpe.rs", "repo_id": "tokenizers", "token_count": 419 }
253