


import gc
import unittest

import numpy as np
import torch
from torch.backends.cuda import sdp_kernel

from diffusers import (
    CMStochasticIterativeScheduler,
    ConsistencyModelPipeline,
    UNetaDModel,
)
from diffusers.utils import randn_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu

from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()
class 		__magic_name__						(A__   ,unittest.TestCase				):





     '''simple docstring'''



     __lowercase				:							Optional[Any]	   =       ConsistencyModelPipeline
     __lowercase				:							Any	   =       UNCONDITIONAL_IMAGE_GENERATION_PARAMS
     __lowercase				:							List[Any]	   =       UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS

     # Override required_optional_params to remove num_images_per_prompt
     __lowercase				:							List[Any]	   =       frozenset(
         [
             'num_inference_steps',
             'generator',
             'latents',
             'output_type',
             'return_dict',
             'callback',
             'callback_steps',
         ]				)

     @property
     def 	SCREAMING_SNAKE_CASE__						(					self:Optional[int]   ):
       snake_case__						= UNetaDModel.from_pretrained(
           '''diffusers/consistency-models-test'''     ,		subfolder='''test_unet'''     ,		)
       return unet

     @property
     def 	SCREAMING_SNAKE_CASE__						(					self:Any   ):
       snake_case__						= UNetaDModel.from_pretrained(
           '''diffusers/consistency-models-test'''     ,		subfolder='''test_unet_class_cond'''     ,		)
       return unet

     def 	SCREAMING_SNAKE_CASE__						(					self:Optional[int]     ,		_a:Optional[int]=False   ):
       if class_cond:
         snake_case__						= self.dummy_cond_unet
       else:
         snake_case__						= self.dummy_uncond_unet

       # Default to CM multistep sampler
       snake_case__						= CMStochasticIterativeScheduler(
           num_train_timesteps=40     ,		sigma_min=0.002     ,		sigma_max=80.0     ,		)

       snake_case__						= {
           '''unet''': unet,
           '''scheduler''': scheduler,
       }

       return components

     def 	SCREAMING_SNAKE_CASE__						(					self:List[str]     ,		_a:Optional[int]     ,		_a:str=0   ):
       if str(snake_case_   ).startswith('''mps'''   ):
         snake_case__						= torch.manual_seed(snake_case_   )
       else:
         snake_case__						= torch.Generator(device=snake_case_   ).manual_seed(snake_case_   )

       snake_case__						= {
           '''batch_size''': 1,
           '''num_inference_steps''': None,
           '''timesteps''': [22, 0],
           '''generator''': generator,
           '''output_type''': '''np''',
       }

       return inputs

     def 	SCREAMING_SNAKE_CASE__						(					self:Optional[int]   ):
       snake_case__						= '''cpu'''  # ensure determinism for the device-dependent torch.Generator
       snake_case__						= self.get_dummy_components()
       snake_case__						= ConsistencyModelPipeline(**snake_case_   )
       snake_case__						= pipe.to(snake_case_   )
       pipe.set_progress_bar_config(disable=snake_case_   )

       snake_case__						= self.get_dummy_inputs(snake_case_   )
       snake_case__						= pipe(**snake_case_   ).images
       assert image.shape == (1, 32, 32, 3)

       snake_case__						= image[0, -3:, -3:, -1]
       snake_case__						= np.array([0.3572, 0.6273, 0.4031, 0.3961, 0.4321, 0.5730, 0.5266, 0.4780, 0.5004]   )

       assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1e-3

     def 	SCREAMING_SNAKE_CASE__						(					self:int   ):
       snake_case__						= '''cpu'''  # ensure determinism for the device-dependent torch.Generator
       snake_case__						= self.get_dummy_components(class_cond=snake_case_   )
       snake_case__						= ConsistencyModelPipeline(**snake_case_   )
       snake_case__						= pipe.to(snake_case_   )
       pipe.set_progress_bar_config(disable=snake_case_   )

       snake_case__						= self.get_dummy_inputs(snake_case_   )
       snake_case__						= 0
       snake_case__						= pipe(**snake_case_   ).images
       assert image.shape == (1, 32, 32, 3)

       snake_case__						= image[0, -3:, -3:, -1]
       snake_case__						= np.array([0.3572, 0.6273, 0.4031, 0.3961, 0.4321, 0.5730, 0.5266, 0.4780, 0.5004]   )

       assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1e-3

     def 	SCREAMING_SNAKE_CASE__						(					self:List[str]   ):
       snake_case__						= '''cpu'''  # ensure determinism for the device-dependent torch.Generator
       snake_case__						= self.get_dummy_components()
       snake_case__						= ConsistencyModelPipeline(**snake_case_   )
       snake_case__						= pipe.to(snake_case_   )
       pipe.set_progress_bar_config(disable=snake_case_   )

       snake_case__						= self.get_dummy_inputs(snake_case_   )
       snake_case__						= 1
       snake_case__						= None
       snake_case__						= pipe(**snake_case_   ).images
       assert image.shape == (1, 32, 32, 3)

       snake_case__						= image[0, -3:, -3:, -1]
       snake_case__						= np.array([0.5004, 0.5004, 0.4994, 0.5008, 0.4976, 0.5018, 0.4990, 0.4982, 0.4987]   )

       assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1e-3







     def 	SCREAMING_SNAKE_CASE__						(					self:Optional[Any]   ):
       snake_case__						= '''cpu'''  # ensure determinism for the device-dependent torch.Generator
       snake_case__						= self.get_dummy_components(class_cond=snake_case_   )
       snake_case__						= ConsistencyModelPipeline(**snake_case_   )
       snake_case__						= pipe.to(snake_case_   )
       pipe.set_progress_bar_config(disable=snake_case_   )

       snake_case__						= self.get_dummy_inputs(snake_case_   )
       snake_case__						= 1
       snake_case__						= None
       snake_case__						= 0
       snake_case__						= pipe(**snake_case_   ).images
       assert image.shape == (1, 32, 32, 3)

       snake_case__						= image[0, -3:, -3:, -1]
       snake_case__						= np.array([0.5004, 0.5004, 0.4994, 0.5008, 0.4976, 0.5018, 0.4990, 0.4982, 0.4987]   )

       assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1e-3




@slow
@require_torch_gpu
class 		__magic_name__						(unittest.TestCase				):





     '''simple docstring'''



     def 	SCREAMING_SNAKE_CASE__						(					self:Any   ):
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()

     def 	SCREAMING_SNAKE_CASE__						(					self:List[Any]     ,		_a:Union[str, Any]=0     ,		_a:Dict=False     ,		_a:Optional[int]="cpu"     ,		_a:Union[str, Any]=torch.floataa     ,		_a:List[str]=(1, 3, 64, 64)   ):
       snake_case__						= torch.manual_seed(snake_case_   )

       snake_case__						= {
           '''num_inference_steps''': None,
           '''timesteps''': [22, 0],
           '''class_labels''': 0,
           '''generator''': generator,
           '''output_type''': '''np''',
       }

       if get_fixed_latents:
         snake_case__						= self.get_fixed_latents(seed=snake_case_     ,		device=snake_case_     ,		dtype=snake_case_     ,		shape=snake_case_   )
         snake_case__						= latents

       return inputs

     def 	SCREAMING_SNAKE_CASE__						(					self:List[str]     ,		_a:List[Any]=0     ,		_a:List[str]="cpu"     ,		_a:List[str]=torch.floataa     ,		_a:List[str]=(1, 3, 64, 64)   ):
       if type(snake_case_   ) == str:
         snake_case__						= torch.device(snake_case_   )
       snake_case__						= torch.Generator(device=snake_case_   ).manual_seed(snake_case_   )
       snake_case__						= randn_tensor(snake_case_     ,		generator=snake_case_     ,		device=snake_case_     ,		dtype=snake_case_   )
       return latents

     def 	SCREAMING_SNAKE_CASE__						(					self:Optional[int]   ):
       snake_case__						= UNetaDModel.from_pretrained('''diffusers/consistency_models'''     ,		subfolder='''diffusers_cd_imagenet64_l2'''   )
       snake_case__						= CMStochasticIterativeScheduler(
           num_train_timesteps=40     ,		sigma_min=0.002     ,		sigma_max=80.0     ,		)
       snake_case__						= ConsistencyModelPipeline(unet=snake_case_     ,		scheduler=snake_case_   )
       pipe.to(torch_device=snake_case_   )
       pipe.set_progress_bar_config(disable=snake_case_   )

       snake_case__						= self.get_inputs()
       snake_case__						= pipe(**snake_case_   ).images
       assert image.shape == (1, 64, 64, 3)

       snake_case__						= image[0, -3:, -3:, -1]

       snake_case__						= np.array([0.0888, 0.0881, 0.0666, 0.0479, 0.0292, 0.0195, 0.0201, 0.0163, 0.0254]   )

       assert np.abs(image_slice.flatten() - expected_slice   ).max() < 2e-2

     def 	SCREAMING_SNAKE_CASE__						(					self:List[Any]   ):
       snake_case__						= UNetaDModel.from_pretrained('''diffusers/consistency_models'''     ,		subfolder='''diffusers_cd_imagenet64_l2'''   )
       snake_case__						= CMStochasticIterativeScheduler(
           num_train_timesteps=40     ,		sigma_min=0.002     ,		sigma_max=80.0     ,		)
       snake_case__						= ConsistencyModelPipeline(unet=snake_case_     ,		scheduler=snake_case_   )
       pipe.to(torch_device=snake_case_   )
       pipe.set_progress_bar_config(disable=snake_case_   )

       snake_case__						= self.get_inputs()
       snake_case__						= 1
       snake_case__						= None
       snake_case__						= pipe(**snake_case_   ).images
       assert image.shape == (1, 64, 64, 3)

       snake_case__						= image[0, -3:, -3:, -1]

       snake_case__						= np.array([0.0340, 0.0152, 0.0063, 0.0267, 0.0221, 0.0107, 0.0416, 0.0186, 0.0217]   )

       assert np.abs(image_slice.flatten() - expected_slice   ).max() < 2e-2

     @require_torch_a
     def 	SCREAMING_SNAKE_CASE__						(					self:int   ):
       snake_case__						= UNetaDModel.from_pretrained('''diffusers/consistency_models'''     ,		subfolder='''diffusers_cd_imagenet64_l2'''   )
       snake_case__						= CMStochasticIterativeScheduler(
           num_train_timesteps=40     ,		sigma_min=0.002     ,		sigma_max=80.0     ,		)
       snake_case__						= ConsistencyModelPipeline(unet=snake_case_     ,		scheduler=snake_case_   )
       pipe.to(torch_device=snake_case_     ,		torch_dtype=torch.floataa   )
       pipe.set_progress_bar_config(disable=snake_case_   )

       snake_case__						= self.get_inputs(get_fixed_latents=snake_case_     ,		device=snake_case_   )
       # Ensure usage of flash attention in torch 2.0
       with sdp_kernel(enable_flash=snake_case_     ,		enable_math=snake_case_     ,		enable_mem_efficient=snake_case_   ):
         snake_case__						= pipe(**snake_case_   ).images
       assert image.shape == (1, 64, 64, 3)

       snake_case__						= image[0, -3:, -3:, -1]

       snake_case__						= np.array([0.1875, 0.1428, 0.1289, 0.2151, 0.2092, 0.1477, 0.1877, 0.1641, 0.1353]   )

       assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1e-3







     @require_torch_a
     def 	SCREAMING_SNAKE_CASE__						(					self:List[Any]   ):
       snake_case__						= UNetaDModel.from_pretrained('''diffusers/consistency_models'''     ,		subfolder='''diffusers_cd_imagenet64_l2'''   )
       snake_case__						= CMStochasticIterativeScheduler(
           num_train_timesteps=40     ,		sigma_min=0.002     ,		sigma_max=80.0     ,		)
       snake_case__						= ConsistencyModelPipeline(unet=snake_case_     ,		scheduler=snake_case_   )
       pipe.to(torch_device=snake_case_     ,		torch_dtype=torch.floataa   )
       pipe.set_progress_bar_config(disable=snake_case_   )

       snake_case__						= self.get_inputs(get_fixed_latents=snake_case_     ,		device=snake_case_   )
       snake_case__						= 1
       snake_case__						= None
       # Ensure usage of flash attention in torch 2.0
       with sdp_kernel(enable_flash=snake_case_     ,		enable_math=snake_case_     ,		enable_mem_efficient=snake_case_   ):
         snake_case__						= pipe(**snake_case_   ).images
       assert image.shape == (1, 64, 64, 3)

       snake_case__						= image[0, -3:, -3:, -1]

       snake_case__						= np.array([0.1663, 0.1948, 0.2275, 0.1680, 0.1204, 0.1245, 0.1858, 0.1338, 0.2095]   )

       assert np.abs(image_slice.flatten() - expected_slice   ).max() < 1e-3



"""simple docstring"""
# Usage:
# ./gen-card-allenai-wmt16.py

import os
from pathlib import Path

def  lowercase     (_lowerCAmelCase ,    _lowerCAmelCase ,    _lowerCAmelCase ,    _lowerCAmelCase						):
						__lowerCAmelCase     =  {
						    """en""": """Machine learning is great, isn't it?""",
						    """ru""": """Машинное обучение - это здорово, не так ли?""",
						    """de""": """Maschinelles Lernen ist großartig, nicht wahr?""",
						}

						# BLUE scores as follows:
						# "pair": [fairseq, transformers]
						__lowerCAmelCase     =  {
						    """wmt16-en-de-dist-12-1""": [28.3, 27.52],
						    """wmt16-en-de-dist-6-1""": [27.4, 27.11],
						    """wmt16-en-de-12-1""": [26.9, 25.75],
						}
						__lowerCAmelCase     =  f"""{src_lang}-{tgt_lang}"""

						__lowerCAmelCase     =  f"""
---
language:
- {src_lang}
- {tgt_lang}
thumbnail:
tags:
- translation
- wmt16
- allenai
license: apache-2.0
datasets:
- wmt16
metrics:
- bleu
---

# FSMT

## Model description

This is a ported version of fairseq-based [wmt16 transformer](https://github.com/jungokasai/deep-shallow/) for {src_lang}-{tgt_lang}.

For more details, please, see [Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation](https://arxiv.org/abs/2006.10369).

All 3 models are available:

* [wmt16-en-de-dist-12-1](https://huggingface.co/allenai/wmt16-en-de-dist-12-1)
* [wmt16-en-de-dist-6-1](https://huggingface.co/allenai/wmt16-en-de-dist-6-1)
* [wmt16-en-de-12-1](https://huggingface.co/allenai/wmt16-en-de-12-1)


## Intended uses & limitations

#### How to use

```python
from transformers import FSMTForConditionalGeneration, FSMTTokenizer
mname = \"allenai/{model_name}\"
tokenizer = FSMTTokenizer.from_pretrained(mname)
model = FSMTForConditionalGeneration.from_pretrained(mname)

input = \"{texts[src_lang]}\"
input_ids = tokenizer.encode(input, return_tensors=\"pt\")
outputs = model.generate(input_ids)
decoded = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(decoded) # {texts[tgt_lang]}

```

#### Limitations and bias


## Training data

Pretrained weights were left identical to the original model released by allenai. For more details, please, see the [paper](https://arxiv.org/abs/2006.10369).

## Eval results

Here are the BLEU scores:

model   | fairseq | transformers
-------|---------|----------
{model_name}  | {scores[model_name][0]} | {scores[model_name][1]}

The score is slightly below the score reported in the paper, as the researchers don't use `sacrebleu` and measure the score on tokenized outputs. `transformers` score was measured using `sacrebleu` on detokenized outputs.

The score was calculated using this code:

```bash
git clone https://github.com/huggingface/transformers
cd transformers
export PAIR={pair}
export DATA_DIR=data/$PAIR
export SAVE_DIR=data/$PAIR
export BS=8
export NUM_BEAMS=5
mkdir -p $DATA_DIR
sacrebleu -t wmt16 -l $PAIR --echo src > $DATA_DIR/val.source
sacrebleu -t wmt16 -l $PAIR --echo ref > $DATA_DIR/val.target
echo $PAIR
PYTHONPATH=\"src:examples/seq2seq\" python examples/seq2seq/run_eval.py allenai/{model_name} $DATA_DIR/val.source $SAVE_DIR/test_translations.txt --reference_path $DATA_DIR/val.target --score_path $SAVE_DIR/test_bleu.json --bs $BS --task translation --num_beams $NUM_BEAMS
```

## Data Sources

- [training, etc.](http://www.statmt.org/wmt16/)
- [test set](http://matrix.statmt.org/test_sets/newstest2016.tgz?1504722372)


### BibTeX entry and citation info

```
@misc{{kasai2020deep,
    title={{Deep Encoder, Shallow Decoder: Reevaluating the Speed-Quality Tradeoff in Machine Translation}},
    author={{Jungo Kasai and Nikolaos Pappas and Hao Peng and James Cross and Noah A. Smith}},
    year={{2020}},
    eprint={{2006.10369}},
    archivePrefix={{arXiv}},
    primaryClass={{cs.CL}}
}}
```

"""
						model_card_dir.mkdir(parents=_lowerCAmelCase ,    exist_ok=_lowerCAmelCase						)
						__lowerCAmelCase     =  os.path.join(_lowerCAmelCase ,    """README.md"""						)
						print(f"""Generating {path}"""						)
						with open(_lowerCAmelCase ,    """w""" ,    encoding="""utf-8"""						) as f:
												f.write(_lowerCAmelCase						)


# make sure we are under the root of the project
SCREAMING_SNAKE_CASE_					     =	Path(__file__).resolve().parent.parent.parent
SCREAMING_SNAKE_CASE_					     =	repo_dir / '''model_cards'''

for model_name in ["wmt16-en-de-dist-12-1", "wmt16-en-de-dist-6-1", "wmt16-en-de-12-1"]:
			SCREAMING_SNAKE_CASE_					     =	model_cards_dir / '''allenai''' / model_name
			write_model_card(model_card_dir, src_lang='''en''', tgt_lang='''de''', model_name=model_name)
